Android - Stop A Service From A Different Class
Solution 1:
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;
publicclassToonServiceextendsService{
publicstatic ToonService toonService;
publicToonService(){
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.
Solution 2:
Definitely you can close the service from another activity.
Method-1: Do the following steps 1. Write a method in Activity 1 that returns that activity reference. 2. Write a method in Activity 1 that closes the service. 3. In Activity2 call the first method and get the reference. Using that reference call the second method
1.privatestatic Context context=this;
publicstatic Context getContext(){
return context;
}
2.publicvoidstop(){
//stop the service here
}
3. In activity 2
Activity context=Activity1.getContext();
context.stop();
Method 2: follow the following steps.
- Write a BroadcastReceiver as an inner class in Activity1 . In onReceive() stop the service.
- Broadcast the intent from the second Activity.
Post a Comment for "Android - Stop A Service From A Different Class"