I want to replace the Thread.sleep(time) calls in my code with alarms set with AlarmManager. How can I return to the proceeding code after the alarm has elapsed. It looks like I use a PendingIntent but how to I point it back to the proceeding code after the time has elapsed?.
Well, it depends on what values you have for time. If you are sleeping for 100ms, you definitely don't want to use AlarmManager, as piotrpo suggests. However, if you are sleeping for several minutes, then AlarmManager is appropriate.
AlarmManger and PendingIntents impose big overheads, so be careful with using them.
Alarm manager is not designed to something like that. .sleep() is also not good. Please read about Timer and Handler classes.
Related
I have to perform this use case (not code , just the right usage)
The use case : I need to fetch some data from the network everyday at 00:30 . These data provide me some specific times , and one of them is around 4:30 (changes everyday by +1 minute -1 minute , depends on the server response, can't use ++ or -- logic anywhere) . On this one (4:30), I need to schedule an Alarm . What is unclear :
Should I use AlarmManager directly for this ?
Should I use WorkManager to get the time when I need to alarm and than use AlarmManager ?
Should I just use WorkManager ?
The reason why I am confused is because some blogs I have read say that is better to stick to AlarmManager if I have some work at a specific time, but still, I can do it with WorkManager
So how is this done ?
Should I use AlarmManager directly for this ?
Yes you should. AlarmManager is the best option as far as I know to handle tasks like yours and also is the safer option when dealing with doze mode. Use the first alarm to set the second alarm at a specific time.
Should I use WorkManager to get the time when I need to alarm and than use AlarmManager ?
If you want to use this approach you need to call AlarmManager and dispatch a Worker on WorkManager. The WorkManager need to run before a specific time and is not guaranteed that the Worker finish or will be executed before 4.30.
The reason why I am confused is because some blogs I have read say that is better to stick to AlarmManager if I have some work at a specific time, but still, I can do it with WorkManager
WorkManager doesn't guarantee the time of execution. It probably can do this in the future.
Should I just use WorkManager ?
No, for the reasons expressed before.
Android-Job is the short term response of your use case if you wanna use a job scheduler. Also you can see a table of features and differences if you go to the link.
Edit 17/03/2020:
Android-Job is deprecated.
What is the best way to implement repeating alarm in my android application? Every user selects a specific time and I want to notify them when this time approaches on daily bases. I have come across this, but I am wondering whether this is the best way?
The alarm manager should meet your needs. There is no better way except for maybe having a server ping your client.
Since android really doesn't like things that repeat on a predictable interval, and since recent versions don't let you repeat on an exact fixed interval anyway, you'll need to schedule the alarm at the time you want, and then when that alarm fires, schedule a new one for the next day at the time you want.
use
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarm_time,
intervel, pendingIntent);
in your activity
Hi I need to set AlarmManager to run a reminder for me to take medication. I need to repeat it by custom amount of days and custom amount of times to take in the day.
So is there an efficient way to set the AlarmManager or CommonsWare's Implementation of the AlarmManager to remind me "twice a day starting at 9AM for the next 5 days" to remind me to take medication? Pls advice and tnx in advance for any constructive help in sample code and in relevant tutorials.
I haven't looked into Mark's AlarmManager implementation, but there is no way, in general, to get the bare AlarmManager to do what you are trying to do. You can schedule a single alarm, at a specific time, or a repeating alarm, that repeats at fixed intervals. If you want something that handles complex schedules like the one you describe, you'll have to write or find code that does it.
You want to use a PendingIntent with the AlarmManager. The idea is to schedule the pendingIntent with the alarmManager, have that trigger an intentService or broadcast, setup another pendingIntent with the alarmManager for the next desired event. You want to keep in mind that you'll need the BOOT_RECEIVED permission in case the user reboots their device. I have complex scheduling in Audio Control and this is exactly what I do.
Here is a pretty decent tutorial of what I mean:
http://android-er.blogspot.com/2010/10/simple-example-of-alarm-service-using.html
You need to schedule an alarm to the next time you want to take the medicine - according to your algorithm (for example if its twice a day, and you got to the pending intent callback for the first time today, then schedule the next alarm to start after [6,7,8,9,10...] hours).
You will need to save both last time of the alarm launch and the user settings in shared prefs/file/DB.
You need to handle process down (android killed it or the device was rebooted). In the case of device reboot you should use the boot receiver to start your service, but you need to remember that from android 3.1 the user has to use at least one time the GUI in order for you to intercept the boot completed receiver. The boot completed receiver should look when was the last time that the alarm launched, and according to the user settings set the next alarm launch.
In the case of android killed your service, you will need to make research, i can't help here.
see example
Are there any major differences between CountDownTimer and AlarmManager? I don't mean syntax or how to use it but wondering if there are such tasks when you certainly can say that I should use one of them, not another?
Simple example, I have to launch some action once a minute. What should I use? CountDownTimer or AlarmManager? How it depends?
AlarmManager generally is used for purposes where your application is closed or must execute some repeating task(s). It is also slightly less precise than Timer or Handler.
CountDownTimer is used more for running a specific task at a duration (onFinish), and being updated periodically until it executes (onTick).
In your specific case, I believe you should be using AlarmManager, since it can repeat indefinitely. If you want something to execute every second for 10 seconds, for example, use CountDownTimer.
CountDownTimer
CountDownTimer will run in the context of your Activity. means It can be killed at any time, If your app is not on forground.
AlarmManager
A total different approach uses Sticky Intents. And tells your Receiver, after some time. It does not depends on the Activity's life Cycle.
So if you want to do some operation every minute, even your app is not on forground then you should use AlarmManager, otherwise CountDownTimer will do the job for you.
As described here :
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
So in your case is better to use CountDownTimer, since you don't want to do the action even if the app is closed.
i have a method in my app that i want to be called repeatedly depending on what the user chooses. like if every hour is chosen by the user, the activity fires a method that is being called every hour. i would like to know the best way to schedule this repeated task.
i have been experimenting with Timers and Timer task, but for some reason it doesn't not seem to work when i use the java calendar class with it, like this:
Calendar c1 = Calendar.getInstance();
c1.add(Calendar.SECOND, 30);
updateTimer.scheduleAtFixedRate(cleanCompletedCache, c1.getTimeInMillis(),hour );
and from what i have been reading, Handlers are not suitable for this multi-repeating task. would i have to use an alarm manager for this and why won't the above code execute correctly? thanks
You want the AlarmManager and it's setRepeating or setInexactRepeating calls.
There you schedule an Intent to be delivered to your application, and write an intent receiver to process it. This way, the activation of your application is entirely the responsibility of the Android system, and your application does not need to run for the entire hour it is just waiting to activate.
If, for some odd reason, you would need your code running between timer invocations, you need to keep a background service running, but you'd still use AlarmManager to get the wakeup.