问题
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