如何从广播中执行正在运行的服务的方法?

501*_*ted 2 service android communication broadcast

在广播中,我想从服务 XYZ 调用非静态方法。该服务由接收器在启动时启动。有人有想法从这个正在运行的服务运行方法吗?该论坛中的一种解决方案是将方法设为静态并使用单例模式来执行。但还有其他方法吗?也许用活页夹?

//编辑例如我有以下类:

public class MyService extends Service{
   .....
   public void method(){
      //TODO
   }
}
Run Code Online (Sandbox Code Playgroud)
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
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能调用该方法method()?我知道我可以使用context.getSystemService()系统服务进行投射。但是我怎样才能得到自己的服务对象呢?

问候

jli*_*aum 5

setAction您可以在启动 的意图中使用将操作字符串添加到您的意图中Service。在您的服务中onStartcommand您可以提取意图的操作,并基于此您可以在服务中执行该方法。

您将始终使用以下命令向您的服务发送命令startService这不会两次启动您的服务。它将启动一次,或者将新意图发送到服务。

因此,在启动时完成的部分中,您应该将意图操作设置为您想要的任何内容,然后启动服务 - 您可以完全删除 else 块。

在您的服务中实现onStartCommand,提取意图的操作,并根据该操作您可以执行您的方法。