我正在尝试从IntentService向Activity发送广播,但它不起作用,即使服务确实发送了广播(我通过调试工具检查)。
奇怪的是,我很少有其他服务广播,但只有这个特定的服务不起作用。
这是我的代码:
IntentService:
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Intent myItent = new Intent ("test");
sendBroadcast(intent);
}
MainActivity中的BroadcastReceiver:
private BroadcastReceiver testbcreceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "succeed",
Toast.LENGTH_SHORT).show();
System.out.println("success");
}
};
onResume,我注册了BroadcastReceiver。请注意,我在这里有4个服务,4个中有2个正常工作。
protected void onResume() {
super.onResume();
mds.open();
registerReceiver(testbcreceiver, new IntentFilter("test"));
registerReceiver(downloadServiceReceiver, new IntentFilter(
DownloadChapterService.NOTIFICATION));
registerReceiver(parsingMangaReceiver, new IntentFilter(
ParsingMangaLinkService.NOTIFICATION));
registerReceiver(parsingMangaChapterReceiver, new IntentFilter(
ParsingChapterMangaService.NOTIFICATION));
}
在AndroidManifest.xml中:
<service android:name="anvu.bk.service.ToastService">
</service>
感谢您查看我的问题。
答案 0 :(得分:2)
改变它
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Intent myItent = new Intent ("test");
sendBroadcast(intent);
System.out.println("wait");
}
要
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Intent myItent = new Intent ();
myItent .setAction(DownloadChapterService.NOTIFICATION); // Define intent-filter
sendBroadcast(myItent );
System.out.println("wait");
}
答案 1 :(得分:0)
创建广播意图时,请在操作前加上您的包名称,并将其设置如下:
public static final String TEST_ACTION = "anvu.bk.service.TEST_ACTION";
protected void onHandleIntent(Intent intent) {
Intent myItent = new Intent ();
myIntent.setAction(TEST_ACTION);
sendBroadcast(intent);
}
然后,在你的onResume()中,注册你的接收者:
IntentFilter filter = new IntentFilter();
//basically, we need the same string as when we were preparing intent for broadcast
//so set action this way, or use string "anvu.bk.service.TEST_ACTION" instead
//of course, use the class name where you declared TEST_ACTION :)
filter.addAction(IntentService.TEST_ACTION);
registerReceiver(testbreceiver, filter);
然后记得在onDestroy()中注销你的接收器:
unregisterReceiver(testbreceiver);
作为旁注,请不要使用System.out.println() - 使用Android的Log.d()来记录事物。 Here's why:
不应该使用System.out.println()(或本机代码的printf())。 System.out和System.err被重定向到/ dev / null,因此您的print语句将没有可见效果。但是,为这些调用发生的所有字符串构建仍然会被执行。