Android - Stop a Service from a different class

走远了吗. 提交于 2019-12-12 16:54:30

问题


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.


回答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;

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.




回答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. private static Context context=this;
   public static  Context getContext(){
        return context;
   }

2. public void stop(){
       //stop the service here
   }

3.  In activity 2
     Activity context=Activity1.getContext();
     context.stop();

Method 2: follow the following steps.

  1. Write a BroadcastReceiver as an inner class in Activity1 . In onReceive() stop the service.
  2. Broadcast the intent from the second Activity.


来源:https://stackoverflow.com/questions/22100189/android-stop-a-service-from-a-different-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!