GaborH GaborH - 1 month ago 14
Android Question

Where/how should I start my AlarmManager to not execute everytime when my Fragement created?

I would like to setup a notification which triggers every 20 seconds. I set an AlarmReceiver in my onCreate() method in my Fragment:

Intent alarmIntent = new Intent(getActivity(), IntentService.AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 20000, pendingIntent);


In my IntentService class I have the following static class:

public static class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

Intent send = new Intent(context, IntentService.class);
context.startService(send);
}
}


I would like to create my Notification in that IntentService class which I start above.

The AlarmManager works, and it executes in every 20 seconds, but it is also triggered every time when my Fragment created.

My question is: Where/how should I start my AlarmManager to not execute everytime when my Fragement created?

Answer

You're not telling the alarm manager to set off the alarm in 20 seconds from now and then every 20 seconds, but now and then every 20 seconds. That's why Android fires the alarm right away - it catches up on past alarms and "now" is some milliseconds past when the code finishes. You need to make sure that the first scheduled alarm is in the future.

So what you really need is this:

alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 20000, 20000, pendingIntent);

This tells the alarm manager to schedule the next alarm in 20 seconds, repeating every 20 seconds.