Alarm Manager Not Firing

205 views Asked by At

In my code the Interval ( third parameter) on setRepeating() method seems not firing every 5 sec .

It keeps increasing in time, it's like the first one or 2 are mostly in time but the others fires like after 40+secs

So what's wrong here?

public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent i = new Intent(this, MainActivity2Activity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE );
    am.setRepeating(RTC_WAKEUP,System.currentTimeMillis(),1000*5,pi);
      }

  }
3

There are 3 answers

2
kostek On

Take a look here: http://developer.android.com/reference/android/app/AlarmManager.html#setRepeating(int, long, long, android.app.PendingIntent)

As you're firing alarm every 5 seconds:

Note: for timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

Your code is ok. Explanation of a delay you're experiencing may be:

Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
0
Ish On

From what I understand from your code you are trying to run MainActivity2Activity.class 5 seconds after the creation of MainActivity.class.

I would advice you to use FLAG_UPDATE_CURRENT instead of FLAG_CANCEL_CURRENT in your pending intent. The FLAG_CANCEL_CURRENT would retain your first ever pending intent and won't update or create a new one until and unless you cancel the original pending intent first. Using FLAG_UPDATE_CURRENT will ensure that the pending intent is updated every time MainActivity.class is executed, so that pending intent will be fired exactly after 5 seconds the MainActivity.class is created.

Hope this helps.

0
Hiren Patel On

Basically you wrote PendingIntent.FLAG_CANCEL_CURRENT instead of PendingIntent.FLAG_ONE_SHOT.

Code for Set Alarm by Alarm Manager

AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
Intent i1 = new Intent(this, ReceiveAlarmActivity.class);
i1.putExtra("Key", "Value");
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i1, PendingIntent.FLAG_ONE_SHOT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Your_Date.getTime(), 5000 operation);

You have to pass Your Date.

Done