I know there are dozens of similar threads on SO about this topic but I just couldn't find one that really solves the problem / or identifies the root cause.
First of all, I'm targetting SDK 22 (Android 5.1) which means I could use the AlarmManager + WakefulBroadcastReceiver + IntentService even if this is not the latest way of doing things.
I'm not interested in the JobScheduler etc solutions, I just want to understand what is happening and why.
The phone I'm testing on has Android 8.0, but it shouldn't matter as I'm targeting Android 5.1.
So the code I'm dealing with sets the alarm for the next day, 06:00.
private fun setupAlarm() {
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.add(Calendar.DAY_OF_YEAR, 1)
calendar.set(Calendar.HOUR_OF_DAY, 6)
calendar.set(Calendar.MINUTE, 0)
val alarmIntent = Intent(this, AlarmReceiver::class.java)
val alarmPendingIntent = PendingIntent.getBroadcast(this, 1221, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, alarmPendingIntent)
}
The AlarmReciever only starts a service:
class AlarmReceiver : WakefulBroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
startWakefulService(context, Intent(context, DownloadingIntentService::class.java));
}
}
This Service then tries to download a file, when finished it calls the completeWakefulIntent(intent) method letting know the system that it's done with its job.
I could not figure out when it is working and when it is not. One morning it did what it should have, on the other, it didn't.
I set up a remote LogCat feature to see whether the IntentService is started but so far I can't see any logs from it, so it means that the alarm is not triggered.
If I set up an alarm for the next minute, even repeating one whatever it works like it should. But when I set back the time for tomorrow morning then it's very unreliable.
Thanks for your help.
I've faced this exact issue myself. See what happens is that setRepeating method let's the android system adjust the time when the alarm should get fired. It will most likely try to batch different alarms in order to optimise battery usage. But in regular cases, if the phone isn't dozing... It generally fires the alarm at correct times.
However if the phone has been idle for a time, the phone goes into doze mode and due to this the alarm gets delayed. I have personally observed delays of upto 1 1:30 hours.
If you want it to fire exactly, you'll have to use the setExactAndAllowWhileIdle method or setAlarmClock method. In this case, you will have to handle the scheduling of your next alarm on your own. The methods work well with doze mode and do fire the alarms at exact times.
There are cons to these methods too. The setExactAndAllowWhileIdle method can only be used to schedule alarms Max once per nine minutes or so. The setAlarmClock method will mostly show a notification like a regular alarm to the user and will indicate the details of the alarm ( this behaviour varies with different os versions )
I used this code to trigger a backup every day. It is working for me, Give it a try.
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyReceiver.class);
intent.setAction("CUSTOM_INTENT");
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 06);
calendar.set(Calendar.MINUTE, 00);
// setRepeating() lets you specify a precise custom interval--in this case,
// 1 day
alarmMgr.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis()/1000,
AlarmManager.INTERVAL_DAY, alarmIntent);
Try this:
Calendar now = Calendar.getInstance();
Calendar alarm = Calendar.getInstance();
alarm.set(Calendar.HOUR_OF_DAY, hourOfDay);
alarm.set(Calendar.MINUTE, minute);
long alarmMillis = alarm.getTimeInMillis();
if (alarm.before(now)) alarmMillis+= 86400000L; //It will add 1 day if your time selected before now
//set alarm method of yours\\
settingAlarmManager(requestCode, alarmMillis);
private void settingAlarmManager(String requestCode, Calendar calendar) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(AddTaskActivity.this, AlarmReceiver.class);
PendingIntent broadcast = PendingIntent.getBroadcast(AddTaskActivity.this,
Integer.valueOf(requestCode), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, broadcast);
}
My Receiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//do your stuff here\\
}
}
Manifest:
<receiver android:name=".utils.AlarmReceiver" />
I have tried above code for setting alarm and do my custom task. Maybe this will help you.
A few things:
The further in time an Alarm is scheduled, the less precise it will be.
Although you are targeting API Level 22, deprecated elements in higher Android version may not fully work, which is the case of the WakefulBroadcastReceiver
You are trying to run a background job in Android 8.0. It's worth exploring the Foreground Service:
It can be started from the background
Correctly notify users that you are indeed doing something while the phone should be idle.
Do not fear running tasks that might take a few seconds to complete.
You might have killed your application. When a user manually kills an app, in most devices all Alarm's and PendingIntent's are killed as well.
A scheduling strategy many developer use is not to set a repeating Alarm, yet have two single Alarms that reschedule each other continuously ( #Kushan mentioned something similar in his answer).
In short:
Have a Scheduler start as soon as possible during the day (even when a user opens your app, it can be fired multiple times). Check if the desired PendingIntents already exist (your background jobs). If they do not, just schedule them. As well, schedule another Alarm around 11.55.
All this midnight scheduler has to do, is to re-schedule the main AlarmManager in 5 minutes, which is then going to schedule the jobs and the midnight alarm for the next days.
This method allows you to:
schedule exact alarms, since repeating ones do not have the exact option.
reduce the time distance of your scheduled alarms, which will then generally be treated with more precision by the OS.
avoid alarms that trigger immediately because scheduled in the past
Also, try to get the most from the API version you are using:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
this.alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
rtcStartingTime.getTimeInMillis(),
pendingIntent
);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
this.alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
rtcStartingTime.getTimeInMillis(),
pendingIntent
);
} else {
this.alarmManager.set(
AlarmManager.RTC_WAKEUP,
rtcStartingTime.getTimeInMillis(),
pendingIntent
);
}
Related
I'm developing an app which you can schedule your time and It reminds you on time just like google calendar. I use AlarmManager class and set a Repeating task to check Database every one minute and see if there is any alarm on that time or not.
#Override
public void onReceive(Context context, Intent intent) {
Calendar now = Calendar.getInstance();
doRepeatingWorks(now.getTimeInMillis()); // Like Checking if one day passed to do some tasks
checkDbIfThereIsSomeSchedule(now);
}
And I call this to start alarm manager:
public void setAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), G.ALARM_CHECK_INTERVAL_MILIS, pendingIntent);
}
But it's inaccurate and sometimes I figure out that the task killer apps kill my alarm and make it totally worthless.
Although using a foregroundService is battery consuming and it goes on user's nerve with the notification.
Is there any solutions or alternatives for this problem?
I use AlarmManager class and set a Repeating task to check Database every one minute and see if there is any alarm on that time or not
That is a truly awful approach. This sort of behavior is precisely why Doze mode and app standby were added in Android 6.0.
Is there any solutions or alternatives for this problem?"
Schedule an alarm event for first event. When you get control, notify the user about the event, then schedule an alarm event for the next event in sequence. If the user adds a new event that is sooner than your first event, cancel the previous alarm and schedule one for the new first event.
You don't need to check there is an alarm in each 1 min. I hope this post helps you - Scheduled Alarm Manager not working Android
I'm new in android. I struggle with my application approximately 3 weeks. I need sent and receive packets in normal mode and sleep mode. My app must exchange data a 5 seconds. I tried using alarmmanager but on android 5 it's not works. On android 5 an interval changes it on 60 seconds. Such a solution makes the battery wears out quickly. When I use normal asynctask, not IntentService, then it works only when screen is ON and app is visible. When app is hidden or I click power OFF then exchange data stops working. What is the best solutions?
Even RTC_WAKEUP doesn't help most of the times.
Solution that worked for my app when device in deep sleep mode:
Use WakefulBroadcastReceiver combined with AlarmManager.
Service is started by startWakefulService() and when it is finished, it releases the wake lock by calling completeWakefulIntent(intent). So the device will be allowed to go back to sleep.
I'm not adding any code. Search for examples on how to use WakefulBroadcastReceiver with AlarmManager. Even WakefulBroadcastReceiver doc has some template code.
Also reduce the frequency of alarm so you can avoid draining so much battery.
You can use the AlarmManager class to wake up the device at a particular time, then fire off an operation at whatever interval you'd like. Code from the docs found here:
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
...
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
Notice the last line of this block. You can use the method setRepeating() to set whatever interval you'd like.
I am developing an app which displays notifications by using AlarmManager.
For that I'm taking the user input values for hour, minute and second.
Something like:
int hour = 4;
int min = 40;
int sec =36
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.HOUR, hour);
Calendar_Object.set(Calendar.MINUTE, min);
Calendar_Object.set(Calendar.SECOND, sec);
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyView.this,0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, Calendar_Object.getTimeInMillis(), myIntent);
Notifications and the rest of the code work fine, but the problem is that instead of 4:40:36 the notifications get invoked on the current time(as soon as i run/debug the app).
I think there is some problem in Calender_Object part.
Looking for a solution.
Thanks in advance.
Please note: Alarms will be executed immediately, if the notification time has elapsed already.
As a workaround you might want to consider a date part too. Or just a variable in memory which acts as a boolean if the time has elapsed or not.
From the Docs:
If the stated trigger time is in the past, the alarm will be triggered immediately. If there is already an alarm for this Intent scheduled (with the equality of two intents being defined by filterEquals(Intent)), then it will be removed and replaced by this one.
Also please consider the API level 19 version of how AlarmManager works.
I scheduled alarm using Calendar class as below
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,1);
cal.getTimeInMillis();
cal.set(Calendar.MINUTE,05);
long TriggerMillis = cal.getTimeInMillis();
AlarmManager aManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
aManager.set(AlarmManager.RTC_WAKEUP, TriggerMillis,pIntent);
where pIntent is an pending intent to proceed further when alarm triggers.
The event triggers with few seconds delay. Is that any problem using Calendar class for this task. Any suggestions?
TIA..
You have two issues:
It is not reliable to use a _WAKEUP alarm with a service directly. The only reliable patterns involve WakefulBroadcastReceiver, my WakefulIntentService, or something along those lines, where the PendingIntent will be to a BroadcastReceiver.
If your android:targetSdkVersion is 19 or higher, and you are running on an API Level 19+ device, set() is inexact. Ideally, you allow it to be inexact, or perhaps use setWindow() to control how off it will be, to minimize the power hit of your alarm event. If it absolutely has to occur at a precise moment, you will need to use setExact(). Since setWindow() and setExact() are new to API Level 19, you will need to fall back to set() on older devices, by examining Build.VERSION.SDK_INT and branching accordingly.
I think you should use the function
setExactAndAllowWhileIdle
For example:
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 100, pendingIntent); // +100 is to set nearly to the current time
You have to know that this is not a repeating alarm, so at the end of your BroadcastReceiver you should set the next alarm.
Regards
I've set a repeating alarm on a service and decided that it's most convenient to reset the alarm from within the called service. The reason is that the service already has code to check if it's within a user-defined schedule (time range). When it's outside the time range, it resets the alarm to start at the future time selected by the user. Maybe I'm approaching this wrong but I'll put this question out there and see what you think.
An activity kicks off the service by creating a repeating alarm:
//Activity
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(getApplicationContext(), MyService.class);
intent.setData(Uri.parse("MyService://identifier"));
PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
intervalInMins*60000, pIntent);
The service has something like this:
//Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Uri Action = intent.getData();
try {
if (Action.equals(Uri.parse("MyService://identifier"))) {
//Simplifying the code here: CalculatedOffset is determined from the current time
//and scheduled start time. intervalInMins is read from settings.
if (!WithinSchedule()) {
Calendar cal = Calendar.getInstance();
PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + CalculatedOffset,
intervalInMins*60000, pIntent);
}
}
} catch (NullPointerException np) {
np.printStackTrace();
}
return Service.START_REDELIVER_INTENT;
}
I was hoping to re-use the intent to reset the repeating alarm. With this new code, I'm seeing multiple alarms stack up firing rapidly in succession around when the start time hits. It should not spaz out like that, but should fire at regular intervals as it did before the scheduling reset. I need to catch it in the debugger but haven't been able to determine the exact conditions yet. Is my understanding of alarms completely off base here? Is there a better way to do this?
Addendum: A wrinkle in this is that I'm using RootTools to gain superuser privileges in order to work around Android 4.2's airplane mode. This hasn't been a problem before the scheduling, but I'm suspicious whether su is blocking for a long time while the alarms stack up.
Re-using the intent inside the service that receives the alarm does work. I've switched from using a Repeating Alarm to a single-shot alarm which gets re-armed every time the service is called. Unfortunately this didn't fix the problem of the alarms stacking. The culprit is definitely su blocking. It may be RootTools or su itself. I need to update the library from 2.6 to 3.x and see if that makes any difference.