【问题标题】:How to execute methods from a running service from broadcast?如何从广播中执行正在运行的服务中的方法?
【发布时间】:2012-12-29 16:41:05
【问题描述】:

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

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

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
    }
}

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

问候

【问题讨论】:

  • 我不确定您要完成什么。当您从服务广播时,您可以在任何活动活动中收听该广播 - 当您收到广播时,您可以在活动中执行您想要的任何内容。如果您在服务接收到广播时尝试在服务中运行方法,那么您也可以在没有单例的情况下执行此操作。
  • 我的服务和我的广播属于独立类。在更新中我有一个例子

标签: android service communication broadcast


【解决方案1】:

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

您将始终使用startService 向您的服务发送命令,这不会启动您的服务两次。它要么启动一次,要么将新 Intent 发送到服务。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2016-06-02
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多