服务中的广播接收器未接收意图

时间:2016-06-18 18:49:37

标签: java android android-intent android-broadcastreceiver

我知道有很多与此主题相关的问题,但似乎对我没什么用。

我有一项服务,它接收来自多个活动的广播,并且我使用不同的行动来区分它们,以便接收每个广播。

这是我的代码

MyService.java //这是服务类

private BroadcastReceiver SleepTimeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG,"SleepTimeReceiver onReceive is called");
        if (intent.getAction().equals("sleepTimeFinished")) {
            Log.d(TAG,"intents are matching");
        }
    }
};

@Override
public void onCreate() {
    Log.d(TAG,"onCreate is called");
    .
    .
    registerReceiver(SleepTimeReceiver,new IntentFilter("sleepTimeFinished"));
}

@Override
public void onDestroy() {
    Log.d(TAG, "on destroy is called");
    unregisterReceiver(SleepTimeReceiver);
}

MyActivity.java //这是活动类

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG,"About to send broadcast");
    Intent sleepTimeFinishedIntent = new Intent(this, MyService.class);
    sleepTimeFinishedIntent.setAction("sleepTimeFinished");
    sendBroadcast(sleepTimeFinishedIntent);
    Log.d(TAG,"broadcast has been sent");
}

我还尝试在清单文件中添加接收器,但无济于事。在logcat中,我可以看到除接收器的onReceive方法之外的所有方法的日志。有人可以帮我这个。这个简单的问题一直困扰着我几个小时。

2 个答案:

答案 0 :(得分:0)

你开始服务了吗?我没有看到在onCreate开始,你在那里发送广播 - 也许收件人还没有注册?

答案 1 :(得分:0)

在我看来,您应该使用LocalBroadcastManager,因为您只处理从您自己的应用程序中发送的广播。

因此,onCreate() MyService.java BroadcastReceiver注册您的LocalBroadcastManager.getInstance(this).registerReceiver(sleepTimeReceiver, new IntentFilter("sleepTimeFinished")); ,如下所示:

onCreate()

然后从MyActivity.java Intent sleepTimeFinishedIntent = new Intent("sleepTimeFinished"); LocalBroadcastManager.getInstance(this).sendBroadcast(sleepTimeFinishedIntent); 发送您的广播:

onDestroy()

在MyService.java的LocalBroadcastManager.getInstance(this).unregisterReceiver(sleepTimeReceiver); 中取消注册本地广播接收器,如下所示:

sleepTimeReceiver

您可能已经注意到我还将广播接收器的名称改为以小写字母开头,只是为了保持一致性。 所以它是SleepTimeReceiver而不是asdf = (['0', ...], ['1', ...], ['2', ...], ['3.0', ...], ['3.1', ...], ['3.2', ...], ['4', ...] , ['5.0', ...], ['5.1', ...])