Waiting for Intent Using ONE_SHOT

I currently have this code:

public static void setupAlarm(Context context) { Intent myIntent = new Intent(context, Receiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_NO_CREATE); if (pendingIntent != null) { return; } else { pendingIntent = PendingIntent.getBroadcast(context, PENDING_INTENT_RETRY, myIntent, PendingIntent.FLAG_ONE_SHOT); } AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.MINUTE, 2); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } 

I want to use one-time intentions and wait for the fire. If at the same time someone asks for a new alarm, if there is an alarm, I do not want to configure anything. Now my question is: after the first alarm, the pending intent is deleted due to the ONE_SHOT flag, but can I create the pending intent again or not?

+6
source share
1 answer

Yes, of course, you can create it again. You will get another PendingIntent from the first.

However, there are a few problems with the code you posted. First of all, you create a PendingIntent as follows:

  pendingIntent = PendingIntent.getBroadcast(context, PENDING_INTENT_RETRY, myIntent, PendingIntent.FLAG_ONE_SHOT); 

but you check if it exists like this:

  pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_NO_CREATE); 

This check will always return null because you are using a different requestCode ! When you create a PendingIntent , you pass PENDING_INTENT_RETRY as requestCode , but when you check if it exists, you pass 0 as requestCode .

The second problem is how FLAG_ONE_SHOT works. If you create a PendingIntent using FLAG_ONE_SHOT and then try to get a PendingIntent using FLAG_NO_CREATE , it will always return null, even if PendingIntent has not been used! Because of this behavior, you cannot use FLAG_NO_CREATE to determine if an alarm is waiting if you set this alarm using the PendingIntent created using FLAG_ONE_SHOT .

If you really want to use this architecture, you cannot use FLAG_ONE_SHOT . Just create a PendingIntent normally (without flags) and verify its existence with FLAG_NO_CREATE .

+11
source

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


All Articles