简体   繁体   中英

Android service not stopping when stopService() is called

I'm having an issue stopping a service that I have started.

The service is called when the user logs in, and starts to track the user's location. This is working fine. The service is meant to stop when the user presses the logout button and is successfully logged out.

It's an android service that is being called through a JavaScript interface by a HTML button.

Here is my Main Class which contains the methods for starting and stopping the service:

public class CasesMain extends DroidGap {
Intent gpsTracking;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.init();

    appView.addJavascriptInterface(this, "StartGPS");

    super.loadUrl(Config.getStartUrl());
}
public void startGPS(){
    gpsTracking = new Intent(this, MyService.class);
    startService(gpsTracking);
}

public void stopGPS(){
    stopService( gpsTracking );
}

}

Here is the MyService class:

public class MyService extends Service {
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();

private boolean gps_enabled = false;
private boolean network_enabled = false;

private Handler handler = new Handler();
Thread t;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
}

@Override
public void onDestroy() {
}

@Override
public void onStart(Intent intent, int startid) {
}

public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT)
            .show();

    final Runnable r = new Runnable() {
        public void run() {
            location();
            handler.postDelayed(this, 10000);
        }
    };
    handler.postDelayed(r, 10000);
    return START_STICKY;
}

public void location() {
    locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    try {
        gps_enabled = locManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }
    try {
        network_enabled = locManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }
    if (gps_enabled) {
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                0, locListener);
    }
    if (network_enabled) {
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                0, 0, locListener);
    }
}

private class myLocationListener implements LocationListener {
    double lat_old = 0.0;
    double lon_old = 0.0;
    double lat_new;
    double lon_new;

    @Override
    public void onLocationChanged(Location location) {

        if (location != null) {
            locManager.removeUpdates(locListener);
            lon_new = location.getLongitude();
            lat_new = location.getLatitude();
            String longitude = "Longitude: " + location.getLongitude();
            String latitude = "Latitude: " + location.getLatitude();
            Log.v("Debug",  "Latt: " + latitude + " Long: " + longitude);
            Toast.makeText(getApplicationContext(),
                    longitude + "\n" + latitude, Toast.LENGTH_SHORT).show();
            lat_old = lat_new;
            lon_old = lon_new;
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

}

And here is my call to stop the service: window.StartGPS.stopGPS();

The start works perfectly, but when I log out, the app continues to show messages of the latt and long meaning the call to stopService() either didn't work or is not called.

Can anyone see where my mistake is or what is going wrong?

Any help would be greatly appreciated!

FIXED Adding handler.removeCallbacksAndMessages(null); in the onDestroy() method of MyService fixed it for me.

Can anyone see where my mistake is or what is going wrong?

You have an empty onDestroy() method. You need to call removeCallbacks() on your Handler there.

If you are using any android.os.Handler in the service remember to call removeCallbacksAndMessages like this:

   @Override
    public void onDestroy() {
        Toast.makeText(this, "service onDestroy", Toast.LENGTH_LONG).show();
        Utils.cancelNotification(this);
        customHandler.removeCallbacksAndMessages(null);
    }

And the service will destroy successfully. It worked for me.

Here's what I would suggest 1) Put more log statements in calls leading to stopService. 2) Implement On ServiceConnection interface and see what's happening in OServiceConnected and onServiceDisconnected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM