动态注册的BroadcastReceiver实例没有触发?

时间:2017-10-18 16:50:10

标签: android broadcastreceiver

我一直试图在这里找到问题,但我似乎无法......我的onReceive似乎没有被召唤,这就是我所拥有的:<\ n / p>

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是&#34; rsg.ms.7&#34;)。

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

2 个答案:

答案 0 :(得分:0)

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

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) {
        ...
    }
}

答案 1 :(得分:0)

SELECT productid, sum(count) as count, downloaddate FROM your_table GROUP BY downloaddate 的性质相对于#include <stdio.h> typedef struct { int (*p)[2][2]; } S; int main() { int aa[2][2] = {{1, 2}, {3, 4}}; S s = { .p = &aa }; printf("Four: %p\n", s.p[1][1]); return 0; } 绑定。 例如,它与Widgets的使用,其中广播在应用程序之外。 因此,当您在PendingIntent中从ApplicationContext广播时,您必须提供应用程序上下文而不是较低层。 我曾经遇到过同样的问题,花了我一整天的时间来解决这个问题。