Android 如何通过服务内部的BroadcastReceiver接收操作
我在接收小部件作为PendingEvent发送的意图时遇到问题: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
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,非常感谢!我搜索了大约两个小时,试图找到问题的原因。但你的回答最终让我找到了正确的地方@阿诺罗,非常感谢!我搜索了大约两个小时,试图找到问题的原因。但你的回答最终让我找到了正确的地方!