为什么 LocationManager 初始化后为空?我正在尝试删除更新()

Why LocationManager is null after initialization? I'm trying to removeUpdates()

我有一个 class "OldLocationService"(通常我使用 GoogleApiClient 的融合位置,但我保留 class 以防旧的 Google 播放):

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

}

另一个地方class我打电话给:

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

而且我得到的位置是正确的。但是,当我尝试禁用 GPS 时:

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

然后在 logcat 我得到:

service is null

为什么我不能删除 GPS 更新?怎么做?

抱歉我的英语错误,

Defozo

首先,不要创建 OldLocationService class.. 的 2 个实例。您必须从启动它们的同一个实例中删除更新.. 因为每个实例都有自己的副本variables/fields,在你的情况下 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();
}