Search code examples
androidandroid-serviceondestroy

Android stopService() not stopping


This is the code I am running to stop my service that is running in the background. If i push the stop button the service just keeps running. The toast from the onDestroy function runs but the service doen't stop. Anny help?

   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnStart = (Button) findViewById(R.id.btnStart);
    btnStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), myServices.class));
            //dialContactPhone("123123123");
        }
    });
    Button btnstop = (Button) findViewById(R.id.btnStop);
    btnstop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), myServices.class));
        }
    });

}

This is the code in the service.

@Override
public int onStartCommand(Intent intent,  int flags, int startId) {
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
        // success! we have an accelerometer

        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        vibrateThreshold = accelerometer.getMaximumRange() / 2;
        running = false;
    } else {
        // fai! we dont have an accelerometer!
    }

    //initialize vibration

return START_STICKY;
}

@Override
public void onDestroy(){
    super.onDestroy();
    Toast.makeText(this, "Servive stoped", Toast.LENGTH_LONG).show();
}

Solution

  • If by "the service doen't stop", you mean "the sensor readings keep arriving", that is because you did not unregister your listener in onDestroy(). Do that by calling unregisterListener() on the SensorManager in onDestroy(), passing in your listener (which looks like it is this).