Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 553
user3293629 Avatar asked Dec 07 '25 02:12

user3293629


1 Answers

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.

like image 63
Rudi Kershaw Avatar answered Dec 08 '25 15:12

Rudi Kershaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!