Android location manager compilation failed

I am trying to get an instance of the LocationManager class (get some GPS related information). I used to write a simple class, but in the end I gave an error

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

here is 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;
    }
}

Thank.

+3
source share
1 answer

The error message means that you are using class ( Context) to call which instance class is required .

You need to pass the Context instance into getLocationand use this context instance to invoke getSystemService.

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

If you use LocationManagerHelperfrom Activity, you can pass Activity as context:

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

Source: https://habr.com/ru/post/1789911/


All Articles