Android – Stop a Service from a different class

In the application i’m making I want to start an intent in one activity

Intent toonService = new Intent(Login.this, ToonService.class);
toonService.putExtra("toonName", result.getName());
Login.this.startService(toonService);

Will the following code close the intent i just opened? If not how can i get it to?

Intent toonService = new Intent(MainActivity.this,ToonService.class);
MainActivity.this.stopService(toonService);

the second piece of code would be called at a time completly unrelated to the first piece of code.

Answer

Well, assuming you only want one instance of this service running at once you could hold a static variable in the service class and access it from anywhere. Example;

public class ToonService extends Service{

    public static ToonService toonService;

    public ToonService(){
        toonService = this;
    }
    ...

}

The constructor for ToonService now stores the created instance in the static variable toonService. Now you can access that service from anywhere from the class. Example below;

ToonService.toonService.stopSelf();

You could also handle multiple instances by having the class store a static List of running instances, rather than just the single instance. It is worth noting, that when you tell a service to stop, you are only requesting that it is stopped. Ultimately the Android OS will determine when it is closed.

Leave a Reply

Your email address will not be published. Required fields are marked *