Search code examples
androidalarmmanagerandroid-alarmsrepeatingalarm

Android:Alarm Manager Misfires


I am creating an alarm manager in OnCreate of an activity which should run after 2 hours but Its running after every few mins can someone help in what I may be doing is wrong?

public class DrawerActivity extends AppCompatActivity {

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_menu);
        ButterKnife.bind(this);
 setUpFitnessAlarm();

}

}

private void setUpFitnessAlarm(){
        Intent alarmIntent = new Intent(DrawerActivity.this, GoogleFitAutoStart.class);
        pendingIntent = PendingIntent.getBroadcast(DrawerActivity.this, 0, alarmIntent, 0);


        int wkupTime;

             wkupTime =72000;
            Log.i(TAG,"Default timer fetch : "+wkupTime);



        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), wkupTime, pendingIntent);


    }

Solution

  • The 3rd parameter of AlarmManager.setInexactRepeating(...) is in milliseconds, not seconds. The correct number would be 2 * 60 * 60 * 1000 = 7200000.

    Also remember that it probably won't be exactly 2 hours, because Android groups alarms together to save power (Doze). It might be 2 hours and 2 minutes, or 1 hour and 59 minutes. If you want to have exactly 2 hours, then use setExact(...), but only use this when really needed.