質問

In my service, in some scenarios I can't stop the GPS from searching and draining the device battery.

LocationListenerAgent.java

@Override
public void onCreate() {
    thisContext = this;
    // Register ourselves for location updates

    networkListener = new LocationListenerAgent();
    gpsListener = new LocationListenerAgent();

    lmgrNet = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    lmgrGps = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    gps_enabled = lmgrGps.isProviderEnabled(LocationManager.GPS_PROVIDER);
    lmgrNet.requestLocationUpdates("network", ONE_MINUTE, 10, networkListener);
    lmgrGps.requestLocationUpdates("gps", ONE_MINUTE, 10, gpsListener);

    super.onCreate();
}

@Override
public void onDestroy() {
    super.onDestroy();
    // Unregister listener
    lmgrNet.removeUpdates(this);
    lmgrNet = null;
    lmgrGps.removeUpdates(this);
    lmgrGps = null;
}

From some places in my app when I press "back" on the main activity, which destroys the app, this is called:

@Override
protected void onStop() {
    if (mBound) {
        unbindService(mConnection); //this is a callback to the locationlisteneragent class to bind it to a service
        mBound = false;
    }
    super.onStop();
}
@Override
protected void onDestroy() {

    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
    stopService(new Intent(this, LocationListenerAgent.class));
    super.onDestroy();
}

maybe my super.On lifecycle methods need to be before the code with the method.

What else do I need to do to stop the GPS??? I've seen other people having problems with this and the answers don't seem so absolute.

In other scenarios in my app, the GPS does stop.

役に立ちましたか?

解決

I solved my issue. I know I didn't mention mapview in the original post but if you are also using MapView the solution is that mapview can use a GPS service unrelated to your own gps location listening service.

In your mapview

private MyLocationOverlay currLocationOverlay;

@Override
protected void onStop() {
    if(currLocationOverlay!=null)
        currLocationOverlay.disableMyLocation();
    super.onStop();
}
@Override
protected void onDestroy() {
    if(currLocationOverlay!=null)
        currLocationOverlay.disableMyLocation();
    stopService(new Intent(this, LocationListenerAgent.class));
    super.onDestroy();
}

他のヒント

Based on the code you posted, I think you are not removing the location updates.

In your onDestroy() method it should be:

lmgrNet.removeUpdates(networkListener);
lmgrNet.removeUpdates(gpsListener);

You can Also Stop like this

stopService(new Intent(AlertsActivity.this,PollingService.class)); android.os.Process.killProcess(android.os.Process.myPid());

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top