Schedule multiple activity expectations with AlarmManager

I recently noticed strange behavior when I tried to schedule actions to be launched in the future using AlarmManager. Look at the code below, the first action starts after 20 seconds, and the second action does not start after 40 seconds, but only after 60 seconds. Can someone explain why the second intention does not provide for the appointment of a second action instead of the third intention. Does this mean that I can only have one intention for activity in AlarmManager.

//pending intent for morning Intent myIntent1 = new Intent(this, Activity1.class); pendingIntent1 = PendingIntent.getActivity(this, 0, myIntent1, 0); AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE); Calendar calendar1 = Calendar.getInstance(); //calendar1.set(Calendar.YEAR, Calendar.MONTH + 1, Calendar.DAY_OF_MONTH, morningTime, 0, 0); calendar1.setTimeInMillis(System.currentTimeMillis()); calendar1.add(Calendar.SECOND, 20); alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingIntent1); //pending intent for noon Intent myIntent2 = new Intent(this, Activity2.class); pendingIntent2 = PendingIntent.getActivity(this, 0, myIntent2, 0); AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE); Calendar calendar2 = Calendar.getInstance(); //calendar2.set(Calendar.YEAR, Calendar.MONTH + 1, Calendar.DAY_OF_MONTH, noonTime, 0, 0); calendar2.setTimeInMillis(System.currentTimeMillis()); calendar2.add(Calendar.SECOND, 40); alarmManager2.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), pendingIntent2); //pending intent for night Intent myIntent = new Intent(this, Activity2.class); pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); //calendar.set(Calendar.YEAR, Calendar.MONTH + 1, Calendar.DAY_OF_MONTH, nightTime, 0, 0); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 60); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);' 
+4
source share
1 answer

Does this mean that I can only have one intention for activity in AlarmManager.

No, but that means you need a separate PendingIntents . You call:

 Intent myIntent = new Intent(this, Activity2.class); pendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0); 

twice, and therefore two calls to getActivity() return the same PendingIntent .

Or:

  • Use a different value for the second getActivity() parameter or

  • Do something for the Intent objects to make them different enough, for example, using different action lines (note: additional functions are not enough)

+15
source

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


All Articles