警报管理器多次通知

时间:2017-01-06 12:56:07

标签: java android

我想做一个功能,当我点击按钮时,我选择一个日期,并在我收到这些日期的通知后 此代码只允许我接收最后一个通知,而不是其他通知。

String dtStart = String.valueOf(hourOfDay) + ":" + String.valueOf(minute);
Calendar calendar;
Intent intent1;
calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);

intent1 = new Intent(getActivity(), AlarmReceiver.class);
intent1.putExtra("titrefr",titlefr);
intent1.putExtra("contentfr",contentfr);
intent1.putExtra("contentar",content);
intent1.putExtra("titrear",title);
intent1.putExtra("audio",stepAudio);
intent1.putExtra("image",image);

PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1000, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager am = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
//  am.set(AlarmManager.ELAPSED_REALTIME,calendar.getTimeInMillis(),pendingIntent);

am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

1 个答案:

答案 0 :(得分:0)

发生这种情况只是因为警报ID覆盖意味着您设置警报并为每个警报提供1000个id。

 PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1000, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

因此,当您设置上次时间时。警报管理器上次设置为id 1000,因此上次警报正在运行。我很简单,添加一个方法,可以帮助您添加多个警报

    private String setAlarm(int year, int month, int day, int hour, int min) {
                String value = "";
                calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                calendar.set(Calendar.DAY_OF_MONTH, day);
                calendar.set(Calendar.HOUR_OF_DAY, hour);
                calendar.set(Calendar.MINUTE, min);
                calendar.set(Calendar.SECOND, 00);
                if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
                    Toast.makeText(AddDrugFormActivity.this, "Select Valid Time", Toast.LENGTH_LONG).show();
                    value = "INValid";
                } else {
                    value = "Valid";
                    Intent intentAlarm = new Intent(AddDrugFormActivity.this, AlarmReciever.class);
  SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(context)
                    int id = preferences.getInt("id", 0);
                    PendingIntent pIntent = PendingIntent.getBroadcast(AddDrugFormActivity.this, id, intentAlarm, 0);// set id 0 if single alarm require
                    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
                    id = id + 1;
                    editor = preferences.edit();
                    editor.putInt("id", id);
                    editor.commit();

                }
                return value;
            }

您只需使用此方法添加多个警报。这是工作代码。