我正在开发一个Android应用程序。在这个应用程序中,我试图设置多个警报与用户的日期时间。我知道这可以使用广播接收器完成。这是我尝试过的代码:
private void setReminder(Calendar time){
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
alarmIntent.putExtra("name",teacherName);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC,time.getTimeInMillis(),pendingIntent);
}
但问题是它只适用于一个警报。当我设置多个警报时,警报响应最后一次用户使用第一个警报的结果设置。我该怎么做才能正确发射所有报警?一个完整示例的代码帮助了我很多。提前致谢
答案 0 :(得分:0)
添加多个警报,如:
private void setReminder(Calendar time){
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
alarmIntent.putExtra("name",teacherName);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), getRandom(), alarmIntent, 0);
alarmManager.set(AlarmManager.RTC,time.getTimeInMillis(),pendingIntent);
}
getRandon()
功能
private int getRandom() {
Random random = new Random();
return random.nextInt(99999) + 1;
}
答案 1 :(得分:0)
试试这段代码。 使用for循环进行多次警报
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentsArrayList = new ArrayList<PendingIntent>();
for(i = 0; i < 5; ++i)
{
Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
// i the request code for every alarm with current position
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), i, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC,
time.getTimeInMillis() + 60000 * i,
pendingIntent);
alarmIntent.putExtra("name",teacherName+i);
intentsArrayList.add(pendingIntent);
}