Android: stopService in another activity

How do I stop a service at another event?

I am starting a service in my summary activity

SocketServiceIntent = new Intent(this, SocketService.class);
SocketServiceIntent.putExtra("MessageParcelable", mp);


And start my statusActivity from my summaryActivity

Intent intent = new Intent(SummaryActivity.this,
intent.putExtra("MessageParcelable", mp);


My problem is that I don't know how I can assign my status to the SocketServiceIntent activity.


source to share

4 answers

You should call Activity(ContextWrapper)#stopService


stopService(new Intent(SummaryActivity.this, SocketService.class));




You haven't explained how you are currently trying to use stopService () and what kind of error you are getting. Expand your question a bit and you may have more helpful answers.

You need to call this from your activity:

stopService(new Intent(SummaryActivity.this, SocketService.class));


Replace "SummaryActivity" with the name of the Activity class from which you are stopping the service.

Before stopping it, make sure you have the unbound service from all . As the Android docs explain , you cannot stop a service that is currently associated with an activity.

As a design hint: It is often better to call stopSelf()

from the current service rather than directly using stopService()

. You can add a method shutdown()

to your AIDL interface that allows the Activity to request a call stopSelf()

. This encapsulates the stopping logic and gives you the ability to control the state of your Service when it is stopped, similar to how you would handle it Thread


For example:

public MyService extends IntentService {

    private boolean shutdown = false;

    public void doSomeLengthyTask() {
        // This can finish, and the Service will not shutdown before 
        // getResult() is called...

    public Result getResult() {
        Result result = processResult();

        // We only stop the service when we're ready
        if (shutdown) {

        return result;

    // This method is exposed via the AIDL interface
    public void shutdown() {
        shutdown = true;



This is especially true since your intent assumes that you can deal with network sockets. You have to make sure that you closed your socket connections properly before your service is stopped.



just call stopService on summaryActivity



Start the service:

// Java
Intent SocketServiceIntent = new Intent(this, SocketService.class);
SocketServiceIntent.putExtra("MessageParcelable", mp);



Stop the service in any action:

stopService(new Intent(this, SocketService.class))





All Articles