2

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

2
  • I'm not sure what you're trying to accomplish. When you broadcast from a service you can listen to that broadcast in any active activity - when you receive the broadcast you can execute whatever you want in your activity. If you're trying to run a method in your service when it receives a broadcast, then you can do that as well without a singleton. Jan 15, 2013 at 15:10
  • my service and my broadcast are in Independent clases. In the update i have one example Jan 15, 2013 at 18:39

1 Answer 1

5

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.