Switch
Switch

Reputation: 15463

Android location manager compilation error

I'm trying to retrieve an instance of a LocationManager class (do get some GPS related information). I have used wrote a simple class to do so, but it end up giving me an error

Cannot make a static reference to the non-static method getSystemService(String) from the type Context

here's my class

public class LocationManagerHelper {

    static Location location = null;

    public static Location getLocation () {
        LocationManager manager = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE);

        if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            System.out.println("Provider is disabled");
        }
        return location;
    }
}

Thanks.

Upvotes: 3

Views: 3674

Answers (1)

Dan Breslau
Dan Breslau

Reputation: 11522

The error message means that you're using a class (Context) to make a call that requires a class instance.

You need to pass a Context instance into getLocation, and use that Context instance to invoke getSystemService.

public static Location getLocation (Context context) {
    LocationManager manager = 
        (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    //....

If you're using LocationManagerHelper from an Activity, then you could pass the Activity as a Context:

LocationManagerHelper.getLocation(this); // "this" being an Activity instance

Upvotes: 10

Related Questions