【问题标题】:How to receive action by BroadcastReceiver inside Service如何在 Service 中通过 BroadcastReceiver 接收动作
【发布时间】:2011-09-21 14:39:28
【问题描述】:

我在接收小部件作为 PendingIntent 发送的意图时遇到问题:

intent = new Intent(MyService.MY_ACTION);
pendingIntent = PendingIntent.getService(this, 0, intent, 0);
views.setOnClickPendingIntent(R.id.button, pendingIntent);

我在 MyService 中添加了一个广播接收器:

private BroadcastReceiver mIntentReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Log.d(TAG, "Intent command received");
        String action = intent.getAction();

        if( MY_ACTION.equals(action))
        {
            doSomeAction();
        }
    }
};

最后我在服务的 onCreate 方法中注册了这个接收器:

IntentFilter filter = new IntentFilter();
filter.addAction(MY_ACTION);
registerReceiver(mIntentReceiver, filter);

现在当 MyService 正在运行并单击按钮时,我得到:

09-21 14:21:18.723: WARN/ActivityManager(59): Unable to start service Intent { act=com.myapp.MyService.MY_ACTION flg=0x10000000 bnds=[31,280][71,317] }: not found

我还尝试向 MyService 的清单文件添加一个意图过滤器(使用 MY_ACTION 操作),但这会导致调用 MyService 的 onStartCommand 方法。这不是我想要的。我需要调用mIntentReceiver的onReceive方法。

【问题讨论】:

    标签: android service action broadcastreceiver android-pendingintent


    【解决方案1】:

    你想做什么?

    如果您在 Service onCreate 方法中注册广播接收器,则:

    • 您应该提出广播意图,而不是服务意图。改变这个:

      pendingIntent = PendingIntent.getService(this, 0, intent, 0);

    到这里:

    pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    
    • 您的服务应该正在运行以侦听此广播事件,这不会运行您的服务,因为您在创建服务时正在注册接收器。

    【讨论】:

    • @aromero,非常感谢!我搜索了大约两个小时,并试图找到我的问题的原因。但是你的回答终于把我指向了正确的地方!
    【解决方案2】:

    出于此类目的,您应该从IntentService 扩展您的服务。您将在您的服务的onHandleIntent() 方法中收到广播。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多