newbieandroid
newbieandroid

Reputation: 161

Check if an alarm manager is running (not working correctly)

first I did read other questions similar to this one, the one that seemed most helpful is this one, and tried using the top two answers to fix my issue, I have two alarm managers in main activity as shown here

private static final int NOTIFICATION_REMINDER_PROMPT = 0;
private static final int NOTIFICATION_REMINDER_UPDATE = 1;

if(!alarmIsRunning(this, new Intent(this, PromptReceiver.class))) {

    Intent notifyIntent = new Intent(this, PromptReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast
            (this, NOTIFICATION_REMINDER_PROMPT, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            1000 * 60 * 60, pendingIntent);

}

if(!alarmIsRunning(this, new Intent(this, UpdateReceiver.class))) {
    Intent notifyIntent2 = new Intent(this, UpdateReceiver.class);
    PendingIntent pendingIntent2 = PendingIntent.getBroadcast
            (this, NOTIFICATION_REMINDER_UPDATE, notifyIntent2, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            1000 * 60 * 60 * 50, pendingIntent2);
}

also the code for function that is used in the if function is as follows

public static boolean alarmIsRunning(Context context, Intent intent){
    return PendingIntent.getBroadcast(context, 0,
            intent, PendingIntent.FLAG_NO_CREATE) != null;
}

Now my issue is that when I debug, the first if condition always gives true, and the second always gives false and runs the code inside, but when I went for the second way which is using the adb shell dumpsys alarm line in my terminal, only the second one is working. There is something that seems to be I don't understand about this.

Upvotes: 0

Views: 326

Answers (1)

Benjamin Scholtz
Benjamin Scholtz

Reputation: 823

When you fetch a pending intent to see if it exists, you need to recreate it exactly as you did before. So you'll need to pass the original request code to the alarmIsRunning() method.

Here is an extract from one of the methods I use for reference:

private fun doesPendingIntentExist(requestCode: Int, intent: Intent): Boolean {
    val tempPendingIntent = PendingIntent.getBroadcast(context,
            requestCode, intent,
            PendingIntent.FLAG_NO_CREATE)
    tempPendingIntent?.cancel()
    return tempPendingIntent != null
}

TL;DR: You need to pass the original request code to the PendingIntent.getBroadcast() method.

Upvotes: 1

Related Questions