Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何通过服务内部的BroadcastReceiver接收操作_Android_Service_Action_Broadcastreceiver_Android Pendingintent - Fatal编程技术网

Android 如何通过服务内部的BroadcastReceiver接收操作

Android 如何通过服务内部的BroadcastReceiver接收操作,android,service,action,broadcastreceiver,android-pendingintent,Android,Service,Action,Broadcastreceiver,Android Pendingintent,我在接收小部件作为PendingEvent发送的意图时遇到问题: intent = new Intent(MyService.MY_ACTION); pendingIntent = PendingIntent.getService(this, 0, intent, 0); views.setOnClickPendingIntent(R.id.button, pendingIntent); 我在MyService中添加了一个广播接收器: private BroadcastReceiver mIn

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

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();
        }
    }
};
最后,我注册了服务的receiver I 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,但这会导致调用MyService的onStartCommand方法。这不是我想要的。我需要调用mIntentReceiver的onReceive方法。

您想做什么

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

  • 您应该提出广播意图,而不是服务意图。更改此项:

    pendingent=pendingent.getService(this,0,intent,0)

为此:

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

    • 你想做什么

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

      • 您应该提出广播意图,而不是服务意图。更改此项:

        pendingent=pendingent.getService(this,0,intent,0)

      为此:

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

      为此,您应该从
      IntentService
      扩展您的服务。您将通过服务的
      onHandleIntent()
      方法接收广播。

      为此,您应该从
      IntentService
      扩展您的服务。您将通过
      onHandleIntent()
      的服务方式接收广播。

      @aromero,非常感谢!我搜索了大约两个小时,试图找到问题的原因。但你的回答最终让我找到了正确的地方@阿诺罗,非常感谢!我搜索了大约两个小时,试图找到问题的原因。但你的回答最终让我找到了正确的地方!