Search code examples
androidandroid-servicebackground-process

How to stop START_STICKY android service from activity


I have created an android service that I want to keep running until I asked it to close from activity. I have created it with START_STICKY return onStartcommand() that works fine and keep running even if I close the app. But the problem is I want to stop the service on button click (e.g radio button: Run in background Yes/No).

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

Solution

  • In the onClick() method of your button, do this:

    Intent intent = new Intent(MyActivity.this, MyService.class);
    stopService(intent);