我有一个类“ 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更新?怎么做?

对不起,我的英语错误,

德福佐

最佳答案

首先,不要创建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();
}

关于android - 为什么初始化后LocationManager为null?我正在尝试removeUpdates(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32182206/

10-10 10:00