How to execute methods from a running service from broadcast?

≯℡__Kan透↙ 提交于 2020-01-14 01:40:14

问题


on a broadcast I want to call a non static method from Service XYZ. The Service is start by the receiver on boot. Has someone a idea to run methods from this running service? One solution in this forum is to make the method static and use a singleton pattern to execute. But is there another method? Maybe with a binder?

//EDIT for example i have the following clases:

public class MyService extends Service{
   .....
   public void method(){
      //TODO
   }
}
public class MyBroadcastReceiver extends BroadcastReceiver{
   .....
  public void onReceive(Context context, Intent intent) {
    String intentAction=intent.getAction();
    if(intentAction.equals(Intent.ACTION_BOOT_COMPLETED)){  
        //start service
        Intent serviceIntent = new Intent(context, MyService.class);
        context.startService(serviceIntent);

    }
    else{ 
     //TODO call method() in MyService
    }
}

how can i call the method method()? I know that i can cast with context.getSystemService() system services. But how can i get my own service object?

greetings


回答1:


You can add an action string to your intent using setAction in the intent that launches the Service. In your service's onStartcommand you can extract the intent's action, and based off that you can execute the method in your service.

You will always send commands to your service using startService this will not launch your service twice. It will either get started once, or the new intent is sent to the service.

So, in your on boot completed section you should set the intent action to whatever you want, and start the service - you can remove the else block completely.

In your Service implement the onStartCommand, extract the intent's action, and based off that action you can just execute your method.



来源:https://stackoverflow.com/questions/14340168/how-to-execute-methods-from-a-running-service-from-broadcast

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