Update Time for AlarmManager (Android)

I use AlarmManager to display event notification at the date and time of the event. But how can I update the time when the AlarmManager sends a PendingIndent to my application when the event is updated?

When an event is raised, the following code is called:

public void setOneTimeAlarm() { Intent intent = new Intent(this, TimerReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, month); c.set(Calendar.DAY_OF_MONTH, day-1); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 00); long date = c.getTimeInMillis(); mAlarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); } 

Called Indent - TimerReciver:

 @Override public void onReceive(Context context, Intent intent) { Log.v("TimerReceiver", "onReceive called!"); Intent notificationIntent = new Intent(context, ListTests.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 123, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Resources res = context.getResources(); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); long[] pattern = {0,300}; builder.setContentIntent(contentIntent) .setSmallIcon(R.drawable.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher)) .setTicker(res.getString(R.string.app_name)) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setVibrate(pattern) .setContentTitle(res.getString(R.string.notification_title)) .setContentText(res.getString(R.string.notification_text)); Notification n = builder.build(); nm.notify(789, n); } 
+4
source share
1 answer

I have found a solution. It turns out that the second argument to getBroadcast(Context context, int requestCode, Intent intent, int flags) matters even if the documentation says

requestCode Private request code for the sender ( currently not used ).

When a request identifier is used for each event, the alarm is updated and alarms are generated for each event.

The reason is that with two different request codes, filterEquals(Intent) will be false. The AlarmManager set(...) documentation says:

If time has taken place in the past, the alarm goes off immediately. If there is already an alarm for this intention (with the equality of two intentions defined by filterEquals(Intent)) , then it will be deleted and replaced with one.

I also changed PendingIntent.FLAG_ONE_SHOT to PendingIndent.FLAG_CANCEL_CURRENT .

+7
source

Source: https://habr.com/ru/post/1482854/


All Articles