如何通过 Service 内的 BroadcastReceiver 接收操作
我在接收小部件作为 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
我还尝试将意图过滤器(使用 MY_ACTION 操作)添加到 MyService 的清单文件中,但它会导致调用 MyService 的 onStartCommand 方法。这不是我想要的。我需要调用mIntentReceiver的onReceive方法。
I have problem with receiving an intent sended by widget as PendingIntent:
intent = new Intent(MyService.MY_ACTION);
pendingIntent = PendingIntent.getService(this, 0, intent, 0);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
I added a broadcast receiver to 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();
}
}
};
and finally I registered this receiver i onCreate method of the service:
IntentFilter filter = new IntentFilter();
filter.addAction(MY_ACTION);
registerReceiver(mIntentReceiver, filter);
And now when th MyService is running and I click the button, I get :
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
I also tried to add an intent-filter (with MY_ACTION action) to manifest file to MyService but it causes calling onStartCommand method of MyService. And that is not what I want. I need to call the onReceive method of mIntentReceiver.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想让我做什么?
如果您在 Service
onCreate
方法中注册广播接收器,则:您应该引发广播意图,而不是服务意图。更改此:
pendingIntent = PendingIntent.getService(this, 0, Intent, 0);
为此:
What do you want to do?
If you register a broadcast receiver in your Service
onCreate
method then:You should raise a broadcast intent, not a service intent. Change this:
pendingIntent = PendingIntent.getService(this, 0, intent, 0);
To this:
为此,您应该从
IntentService
扩展您的服务。您将在服务的onHandleIntent()
方法中收到广播。For such purposes you should extend your service from
IntentService
. You will receive the broadcast inonHandleIntent()
method of your service.