Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat alarm everyday accurately (Alarm manager)

I set an alarm to repeat everyday. but it will have a few seconds or minutes error. How can I make it more accurate?

PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), notificationId, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 30);
long startUpTime = calendar.getTimeInMillis();
if (System.currentTimeMillis() > startUpTime) {
    startUpTime = startUpTime + 24*60*60*1000;
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startUpTime,  24*60*60*1000 , pendingIntent);
like image 596
Hung Wei Chun Avatar asked Jan 17 '15 15:01

Hung Wei Chun


People also ask

Does alarm Manager persist even after reboot?

Start an alarm when the device restarts This ensures that the AlarmManager will continue doing its task without the user needing to manually restart the alarm.

What is exact alarm?

What is this permission? The new exact alarm permission ( SCHEDULE_EXACT_ALARM ) was created to save system resources. Alarms that must be executed in an exact time may be triggered when the phone is on power-saving mode or Doze, making the app consumes more battery than it should.


1 Answers

1) get time form timepicker basis

calNow = Calendar.getInstance();
calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);

if (calSet.compareTo(calNow) <= 0) {
    //Today Set time passed, count to tomorrow
    calSet.add(Calendar.DATE, 1);
}

2) Set alarm for Daily basis

Intent intent = new Intent(AddAlarmNewActivity.this, OnAlarmReceive.class);
intent.putExtra("alarmTitle", mTitle.getText().toString());
intent.putExtra("alarmId", insertedId + "");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 
                                                         (int)insertedId,
                                                         intent,
                                                         PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
                          targetCal.getTimeInMillis(), 
                          24*60*60*1000, 
                          pendingIntent);
like image 198
priti Avatar answered Sep 24 '22 16:09

priti