动态注册的 BroadcastReceiver 实例未触发?

Dynamically registered BroadcastReceiver instance not firing?

我一直试图在这里找到问题,但我似乎无法...我的 onReceive 似乎没有被调用,这就是我所拥有的:

public abstract class NoUpdatesTimer extends BroadcastReceiver {
    private Context context;
    private PendingIntent pendingIntent;

    public NoUpdatesTimer(Context context) {
        this.context = context;
        Intent intent = new Intent(Constants.ALARM_NO_LOC_UPDATES);
        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        context.registerReceiver(this, new IntentFilter(Constants.ALARM_NO_LOC_UPDATES));
    }

    public void scheduleCheck(long delayMillis) {
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMillis, pendingIntent);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ...
    }
}

经过一些调试,我确认调用了 scheduleChecking 但没有调用 onReceive 方法。我还尝试从 shell 触发此代码,使用:

adb shell am broadcast -a rsg.ms.7

(其中 Constants.ALARM_NO_LOC_UPDATES 是 "rsg.ms.7")。

你能告诉我要更改什么以便调用 onReceive 吗?

使用应用程序上下文而不是传入的服务上下文似乎可以正常工作,但不确定原因:

public abstract class NoUpdatesTimer extends BroadcastReceiver {
    private Context context;
    private PendingIntent pendingIntent;

    public NoUpdatesTimer(Context context) {
        this.context = context.getApplicationContext();
        Intent intent = new Intent(Constants.ALARM_NO_LOC_UPDATES);
        pendingIntent = PendingIntent.getBroadcast(this.context, 0, intent, 0);
        this.context.registerReceiver(this, new IntentFilter(Constants.ALARM_NO_LOC_UPDATES));
    }

    public void scheduleCheck(long delayMillis) {
        AlarmManager alarmManager = (AlarmManager)this.context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMillis, pendingIntent);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ...
    }
}

PendingIntent的性质与ApplicationContext相对。 例如,它与 Widgets 一起使用,其中广播在应用程序外部。 因此,当您在 PendingIntent.getBroadcast 中从 PendingIntent 接收广播时,您必须提供应用程序上下文而不是较低层。 我曾经遇到过同样的问题,我花了一整天的时间才弄明白。