user7263173
user7263173

Reputation:

Android : stopservice from an activity that did not start it

I have an App.java that starts 2 services in onCreate().

I have a MainActivity and in a Log-Off method in MainActivity, I need to stop these 2 services.

How do I do it? Since this MainActivity doesn't start these 2 services, is it possible to stop from it?

Upvotes: 0

Views: 118

Answers (1)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29783

You can use stopService() directly like this:

stopService(new Intent(MainActivity.this, YourService.class));

But as seanhodges says in https://stackoverflow.com/a/9665584/4758255,

It's often better to call stopSelf() from within the running Service rather than using stopService() directly. You can add a shutdown() method into your AIDL interface, which allows an Activity to request a stopSelf() be called.

Instead using AIDL interface, you can utilize EventBus.

Something like this:

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) {
       stopSelf();
    }

    return result;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    EventBus.getDefault().register(this);
  }

  @Override
  public void onDestroy() {
    EventBus.getDefault().unregister(this);
    super.onDestroy();
  }

  // This method receive the Event for stopping the service
  @Subscribe
  public void onMessageEvent(StopServiceEvent event) {
    shutdown = true;
  }
}

Where StopServiceEvent is a simple class:

public class StopServiceEvent {
}

You only need to send the event to stop the service from your MainActivity with:

EventBus.getDefault().post(new StopServiceEvent());

Upvotes: 1

Related Questions