多个意图,但广播接收器只调用一次

时间:2016-07-23 13:20:39

标签: android broadcastreceiver alarmmanager android-pendingintent

我想在特定时刻执行数据库操作,并将警报管理器和未决意图与广播接收器结合使用。

这样可行,但是当同一广播接收器必须在短时间内(f.ex.在一分钟内)内接收多个意图时,onreceive()只会被调用一次。

  Intent intent2 = new Intent(this, CustomBroadcastReceiver.class);
    intent2.putExtra("taskId", currentTask.getTaskId());
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
            ((long) dataSource.fetchTask(task.getTaskId()).getTaskTime() * 60 * 1000), pendingIntent1);

和广播接收者的接受方法:

  @Override
public void onReceive(Context context, Intent intent) {
    dataSource = new DataSourceClass(context);
    dataSource.open();

    int taskId = intent.getIntExtra("taskId", 0);

    dataSource.setTaskStatus(3, taskId);
    dataSource.setCatInActive(dataSource.fetchTask(taskId).getTaskCategory())
}

关于我做错了什么的任何建议?

1 个答案:

答案 0 :(得分:2)

而不是set(),您可以在KITKAT之后使用setExact()

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
    }

getBroadcast()中的第二个参数是requestCode,它就像是一个ID一样,因此,每个PendingIntent都应该有一个唯一的requestCode(又名ID)。你的所有pendingIntent1都有相同的requestCode(0),我不确定是不是导致问题的原因可能是,你可以为每个pendingIntent设置一个不同的requestCode,如下所示:

    int i = sharedPrefs.getInt("i", 0);

    Intent intent2 = new Intent(this, CustomBroadcastReceiver.class);
    intent2.putExtra("taskId", currentTask.getTaskId());
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, i++, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
            ((long) dataSource.fetchTask(task.getTaskId()).getTaskTime() * 60 * 1000), pendingIntent1);

    sharedPrefs.edit.putInt("i", i).apply();