为什么LocationManager在初始化后为空?我正在尝试removeUpdates()

时间:2015-08-24 12:21:46

标签: android nullpointerexception gps locationmanager

我有一个类“OldLocationService”(通常我使用的是GoogleApiClient中的融合位置,但我保留该类以防旧版Google Play):

public class OldLocationService {
    static Location loc;
    private static final String TAG = MainActivity.class.getSimpleName();
    protected LocationManager service;

    private final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            Log.d(TAG, "New location: " + location.toString());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

    };

    public void EnableGPS(String provider, Context ctx) {
        service = (LocationManager) ctx.getSystemService(ctx.LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(provider);
        if (enabled) {
            service.requestLocationUpdates(provider, 10000, 0, mLocationListener, Looper.getMainLooper());
        }
        else
        {
            Log.d(TAG, "GPS is not enabled");
        }
    }

    public void DisableGPS() {
        try {
            if (!(service==null)) {
                service.removeUpdates(mLocationListener);
            } else {
                Log.d(TAG, "service is null");
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

}

我正在打电话给另一个班级的某个地方:

OldLocationService OLS = new OldLocationService();
OLS.EnableGPS(LocationManager.NETWORK_PROVIDER, mContext);

我正确地获得了位置。但是,当我尝试禁用GPS时:

OldLocationService ols = new OldLocationService();
ols.DisableGPS();

然后在logcat中我得到:

  

服务为空

为什么我无法移除GPS更新?怎么做?

对不起我的英文错误,

Defozo

1 个答案:

答案 0 :(得分:1)

首先不要创建OldLocationService类的2个实例..您必须从启动它们的同一实例中删除更新...因为每个实例都有自己的变量/字段副本,你的案件protected LocationManager service;

OldLocationService ols = new OldLocationService(); // declare it globally


// in middle of some code
OLS.EnableGPS(LocationManager.NETWORK_PROVIDER, mContext);
 // more code here

如果您要从Service删除位置更新,则必须将代码放在同一个实例的onDestroy()方法中:

public void onDestroy(){
    ols.DisableGPS();
    super.onDestroy();
}