Search code examples
androidandroid-studioandroid-intentservice

How to stop Android Service started with a custom intent


I built a class called MService extend Service in Android Studio , I started the service like this: - inside onClick associated with a button-

Intent serviceIntent = new Intent(getApplicationContext(), MService.class);
serviceIntent.putExtra("ID", "1"); 
startService(serviceIntent);

The Service onStartCommand method lunched and worked pretty good..

The problem is I don't know how to end the Service when a Button clicked, I tried to do this:

stopService(new Intent(getApplicationContext(), MService.class));

inside a onClick method , the onDestroy lunched, but the Service still running How can I stop it?


Solution

  • inside a onClick method , the onDestroy lunched, but the Service still running

    If onDestroy() of your service was called, then afterwards, the service is not running. Your code might still be running.

    If you start things in a service, such as a background thread, it is your job to stop them and clean that up, typically in your onDestroy() method.