繁体   English   中英

Activity不从IntentService接收广播

[英]Activity doesn't receive Broadcast from IntentService

我正在尝试从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>

感谢您查看我的问题。

更改

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");

}

在创建要广播的意图时,请在操作前添加您的包名称,并将其设置如下:

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()来记录事物。 原因如下:

不应使用System.out.println()(或本机代码的printf())。 System.out和System.err被重定向到/ dev / null,因此您的print语句将没有可见效果。 但是,为这些调用发生的所有字符串构建仍然会被执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM