TaskReminer works only one alarm

时间:2017-10-12 10:09:35

标签: java android android-pendingintent

There is an alarm-reminder. How to make the alarm triggered more than once, and at each reminder? Only one alarm clock works, the rest are overwritten.

Code:

public class ReminderManager {

private Context mContext;
private AlarmManager mAlarmManager;

public ReminderManager(Context context) {
    mContext = context;
    mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
}

public void setReminder(Long taskId, Calendar when) {

    if (when.getTimeInMillis() < System.currentTimeMillis()) {
        return;
    }

    Intent i = new Intent(mContext, OnAlarmReceiver.class);
    i.putExtra(DbAdapter.KEY_ROWID, (long)taskId);
    PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_ONE_SHOT);
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pi);
}

}

I understand that the problem is in requestCode, but I can not understand how to solve it ..

1 个答案:

答案 0 :(得分:0)

PendingIntent pi = PendingIntent.getBroadcast(mContext,{unique id}, i, PendingIntent.FLAG_ONE_SHOT);

The each pending intent is to be provided a unique id. create a random id and assign that id as unique id to the pending intent. Otherwise pending intent will be overwritten

For unique id create random numbers

Random rand = new Random();
int  n = rand.nextInt();

Or use id from database if any.