安卓定位管理器编译错误

3

我正在尝试检索LocationManager类的实例(以获取一些与GPS相关的信息)。我已经编写了一个简单的类来完成这个任务,但最终出现了错误。

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

这是我的类

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

谢谢。
1个回答

10

错误信息表示您正在使用一个类(Context)进行需要类实例的调用。

您需要传递一个 Context 实例到 getLocation 中,并使用该 Context 实例来调用 getSystemService

public static Location getLocation (Context context) {
    LocationManager manager = 
        (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    //....
如果您从Activity中使用LocationManagerHelper,则可以将Activity作为上下文传递:

如果您从Activity中使用LocationManagerHelper,则可以将Activity作为Context传递:

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

那么,为了检查它是否工作,我需要让我的手机同时激活GPS和Wi-Fi吗?到目前为止还没有成功。 - Switch
@MMRUser:根据您展示的代码,启用GPS应该足够了。如果您仍然遇到问题,请提出一个新问题,并描述在运行代码时发生了什么或没有发生什么。 - Dan Breslau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接