开发者

getSystemService is undefined for the type for GetLocation

I have GetURL method defined to find my location from network provider, you can send the code below.

If I define that code piece in my main class with Activity this works nicely but when I would like to create a seperate class (for instance GetLocation class), I cannot use getSystemService method and I receive error in subject (getSystemService is undefined for the type for GetLocation). There are couple of entries regarding this topic but I don't understand fully.

That's a rookie question so take this into account while answering :) Thanks guys.

public String 开发者_如何学JAVAGetURL () {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String locationProvider = LocationManager.NETWORK_PROVIDER;
    mostRecentLocation = locationManager.getLastKnownLocation(locationProvider);
    if(mostRecentLocation != null) {
        double lat = mostRecentLocation.getLatitude();
        double lng = mostRecentLocation.getLongitude();
        currentLocation = "Lat: " + lat + " Lng: " + lng;
        Log.e("LOCATION -------------", currentLocation + "");
    }
    return currentLocation;
}


The method getSystemService() belongs to the Context class.

Therefore if you want to move getUrl() to become a utility method elsewhere, you need to pass in a Context object, such as the current Activity (as it inherits from Context).

For example:
Util.java

public static String getUrl(Context context) {
    LocationManager lm = (LocationManager) 
        context.getSystemService(Context.LOCATION_SERVICE);

    // ... your existing code ...
    return currentLocation;
}

MyActivity.java

public void onCreate() {
    // ... usual stuff ...

    String url = getUrl(this);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜