I have an activity that uses AlarmManager
to create an alarm that's SUPPOSED to go off every 3 minutes. It does when the app is closed, but when you open the app and as soon as you start going to different aspects of the app, the alarm onReceive() method is called on every single Activity load!
How do I stop that functionality?
I want the alarm to run ONLY EVERY 3 MINUTES
Here is my broadcast receiver:
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Testing...", Toast.LENGTH_SHORT).show();
}
Here is my setalarm method (in MainActivity onCreate)
public void startAlarmManager()
{
Intent dialogIntent = new Intent(getBaseContext(), AlarmReceiver.class);
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
pendingIntent = PendingIntent.getBroadcast(this, 0, dialogIntent,PendingIntent.FLAG_CANCEL_CURRENT);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 180000, pendingIntent);
}
Your code to create the alarm is in onCreate(), so the alarm is getting created each time onCreate() is called. You could set a boolean flag when you first create the alarm, and only set the alarm when necessary. Just make sure you save that boolean to the bundle and retrieve it in onCreate() if the bundle is not null.
There is a very nice diagram of the Activity lifecycle here.
In your particular case, you should understand that onCreate()
is called by the system quite often. For instance, whenever you rotate the device to change its orientation (for example, from portrait to landscape), onCreate()
is called (in addition to other lifecycle methods). These methods are called in a specific order and at specific times, so you need to program 'around' that lifecycle.