CountDownTimer vs AlarmManager - android

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.

Related

Execute task in background at application start and for ever - Android

My Application needs to have one (async) task which is always a network operation and the first time a DB query as well.
It needs to be executed with a certain interval amount of time which is not fixed (could be 1 minute or 1 hour or anything in between) and also when the application is not active.
What is the best and the simplest solution in such case between Asynctask/Thread/Service/Alarm/anything not mentioned.
For that you need a service, not an AsyncTask:
http://www.vogella.com/tutorials/AndroidServices/article.html
Services persist even after activities are dismissed. Be careful though, draining the battery will anger your users. Also, services can be destroyed if memory runs low, so be careful.
The scheduling of a task to run in the future should use AlarmManager. The execution of the operation should run in a service since you specify that sometimes it will occur when the app is not active.
You can also use a TimerTask but it's a little more drain on battery and not as precise as AlarmManager. You can also use a handler to postAtTime
Here is a good reference:
difference between timer and alarmmanager
and another one:
What is better in Android? Timer or Alarm?
It really depends on the frequency and use-case. I've used all of these - I view TimerTasks as "keep checking frequently for short time" vs. handlers for "check again in a while" vs. AlarmManager for "I want to keep checking every hour for a long while"

Android: CountDownTimer in BroadcastReceiver

I have an app that uses a CountDownTimer inside a BraodcastReceiver. The CountDownTimer can be for upwards of 1 hour. The timer shows the countdown in the Notifications area (second intervals).
Some users have reported that the app seems to hang on long count downs. The CountDownTimer is triggered by a widget.
Does anyone know if a CountDownTimer can be stopped and reclaimed by the OS?
The alternative would be to set a recurring alarm at 1 second intervals which runs a service. Is there a better option?
Does anyone know if a CountDownTimer can be stopped and reclaimed by the OS?
Your process will be.
The alternative would be to set a recurring alarm at 1 second intervals which runs a service.
That's not an option in any practical sense, if by "recurring alarm" you mean AlarmManager. AlarmManager is not designed for every-second events.
Is there a better option?
This is one of the few cases that justifies a foreground service. Since you have a Notification anyway, and since your AlarmManager approach would keep the service around constantly anyway, you may as well dispense with the AlarmManager and use startForeground() to keep the service around. Update the Notification that you are using with startForeground(), and use ScheduledExecutorService to get control every second on a background thread.
When the countdown is done, call stopForeground() and stopSelf() to get rid of it all.

how to keep an Intent service running

I have two examples of Intentservice. One is the Download example in the commonsware book. the other is at http://www.vogella.com/articles/AndroidServices/article.html#servicecommunication_handler.
Both of these examples show the service executing a finite task and they both apparently destroy themselves by running to the end of the scope of the onHandleIntent event.
The service I am writing has to have events and listen for things. One is a LocationListener listening for GPS movement. Another makes Posts to a REST service and listens for replys. I want it to run until a time has elapsed or until it was told to quit by the activity that started it.
How do I keep it running? Where, for instance, do I put my implementation of LocationListener?
Thanks, Gary
How do I keep it running?
You don't. IntentService is designed to do a piece of work (or perhaps a few off a queue, if commands happen to come in rapidly), then shut down.
The service I am writing has to have events and listen for things.
Then you should not be using an IntentService. Use a regular Service, with your own background thread(s) as needed.
To keep a service running, your service need to return START_STICKY in the service method onStartCommand().
With this, the service will be running even if you exit form your activity.
Note:
The Android still kills services after some time (30 mintus to 1 hour) if they are not foreground services. Use startForeground(notification) to make it foreground.
good luck
You can achieve this in either of two ways,
AlarmManager
TimerTask
AlarmManager is android's in-buite class that allows you to execute certain action on particular time peroid.
TimerTask does same thing as AlarmManager, you can repeat certain action of your code again and again.
However AlarmManager is ligher in the execution so i suggest you to go with AlarmManager class.
Create an AlarmManager that fetches the GPS Co-ordinates and post them to server on regular interval basis.
Have a look at to this AlarmManager Example.

Execute code at specific time: Handler? AlarmManager?

I need to execute code at intervals, sometimes 10 seconds, sometimes 5 minutes. The code should be executed at exact 10 seconds from start, then at exact 5 minutes and 10 seconds from start, etc.
A Chronometer is ticking along from the start, so the execution time must be accurate.
Using Handler.postDelayed does not work, because the code to execute could take some time. The next execution of the code could be late when that happens.
When I wanted to implement AlarmManager, I saw the 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 I'm a bit confused, how should I do this to guarantee correct execution?
As Chris stated, there's no such thing as exact timing in Android.
But you could try it like this to come near realtime...
some Pseudocode for waiting 5s:
class mJob implements Runnable{
public void run(){
while(System.currentTimeMillis()<myExactTime){ //poll for your time
Thread.sleep(1);
}
//Ok, we are as near as we'll ever get
//call here your 'realtime' function or whatever you need
}
}
mHandler.postDelayed(mJob,4950); //the closer to 5000, the better for the cpu but you could miss your `myExactTime`
I don't now how exact this is, you'll just have to try it. But I see no other way to become more 'realtime' with the normal SDK. You could even remove the sleep(1) to become even closer to your myExactTime.
For the next call use something like this (scratch):
nextCallDelayInMillis = starttimeInMillis+No1_Delay+No2_Delay-System.currentTimeMillis();
Have a look at this post : Time/Date change listener. you can use setRepeating() method, or alternatively set the timer again after each execution.
As android is not a hard-realtime OS, exact timing of execution is not possible without substantial kernel modifications. Even there, you are unlikely on a typical android device to have much in the way of exactly timed means of useful I/O, so just running your code at the perfect time may not be enough.
At best you can determine using the more reliable of the timers the latest point at which your code could have run, and take after-the-fact compensation measures.
In terms of the available timing methods, a major consideration should be if you intend the device to wakeup from sleep to accomplish events, in which case you should use the Alarm Manager, if you intend to keep the device awake, in which case you should use a Wake Lock, or if you are okay with your events happening only when the device is awake and your service or activity is running, in which case you can use a simple Timer.
You didn't specify if your code runs while application is running or as background service. It's important, because after you lock your device, Android goes to sleep mode, where CPU is off and functions like postDelayed wont be activated. Intents asking to start activities too.
But AlarmManager broadcasts will.
I'll quote from here
The AlarmManager is best used for tasks that need to
run even when the application isn’t open. For normal timing operations
that need to run during application use (ticks, timeouts, etc), it is
more efficient to use the postDelayed() and postAtTime() methods of a
Handler. The AlarmManager requires too much overhead to justify it
being used this way.
I suggest you to use postDelay, for any post to handler, handler is opening new thread and code is executing simultaneously.
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
//some code
mHandler.postDelayed(this, 1000);
}
};
Here is my complete code I used postDelay for displaying count down timer: https://github.com/minimaldevelop/antistress/blob/master/src/com/minimaldevelop/antistress/AntiStressExerciseActivity.java
Also here I using AlarmManger but only as remainder to display message at notification bar when application is closed.

Which type of service in Android will use more system resources

Would it be better to have a service that is continually running a timer and executing a task every five seconds. Or would it be more efficient to have an alarm manager starting the service every five seconds? How about every second? I'm interested to hear your responses. Thanks!
According to the AlarmManager documentation, it's only for cases where you want to run at a specific time. For what you're talking about, you'll want to use a Handler, with postDelayed().
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.

Categories

Resources