How to set a Timer to a Service? - android

In my app I have a Service that runs when i open my app (through onCreate method) and it just displays a simple notification, so I want the Service to close and re-open ( stopService > startService ) every 60seconds that is set by the timer. How do I set the timer to do it?

Please, look at and use AlarmManager
With AlarmManager you will be able to allow a service to start at a stablished time, alse you can use the setrepeating alarm to schedule an alarm to go off after a certain amount of time and then repeating constantly as long as you want it to.

Use AlarmManager to be poked every minute. Then in your BroadcastReceiver's onReceive() poke service to do the job by i.e. doing startService() with special intent.

Related

Getting elapsed time from AlarmManager

Pretty new to android, so forgive me if this is a dumb question...
So, I'm making an app with a countdown timer that will ring periodically, and then again when the countdown hits zero - simple enough. However, I want the app to keep running even when the user closes the application or the phone is asleep, so that whenever the timer rings, the app will wake up and display an activity showing the time until the countdown is finished. To do this, I'll need to use a service, and lo and behold, the google devs made the AlarmManager service just for me! Sweet!
However, I noticed 2 things:
1) the AlarmManager class has no default constructor, so I'm assuming I can't just extend it and tack some logic on so that I can get all this done in one shot. Ok, cool - I'll just make a service that instantiates AlarmManager at the start, and implement my logic there.
2) In the documentation, I don't see any way of getting either the elapsed time or the remaining time from AlarmManager once it is running.
So, my question is: does this mean that I will need two timers that I start at the same time? Say, an AlarmManager to wake the phone up and call the activity, and a CountDownTimer contained in the service to hold the remaining time and call the alarm ringtone?
Thanks for helping out my clueless ass.
You could extend AlarmManager. However the common way is to get an instance of it, which is running as a system service.
Get the instance using Context.getSystemService(Context.ALARM_SERVICE) and you will be able to register your PendingIntent to that system service, which is independent to your own app. The PendingIntent can either start an activity or send broadcast with some Intent. You don't monitor the elapsed time constantly in AlarmManager. Rather, you calculate the time difference between the current time of your method call, and the desired time to fire your event. And then you set an alarm in AlarmManager with a PendingIntent representing the action you wish to take at that interval, or a time point.
On the other hand, if you want maximum flexibility, run your service as foreground service and listen for system broadcast like ACTION_TIME_TICK, which is fired every minute. Alternatively if you don't run service in foreground you could also run your service with START_STICKY, which guarantees that your service will be restarted after the system kills it (due to sleep or closing app). Think this as a background service that is constantly running. This provides you a lot of flexibility in your implementation.

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.

CountDownTimer service

Im trying to make a countdown timer run in the background of my activity, it needs to run constantly until it finishes, but not sure how to make it work with a service. I also need to update the display on my main activity
Uh, not all services run 100% of the time. Nothing is a battery drain unless it's executing at 100%. If you look at the actual battery consumption of an Android device, you'll see that the largest percentage comes from the screen. The next comes from radios. Running a process costs very little.
You can use an IntentService to fire off an alarm at regular intervals. The service can send intents to itself. Have one intent action to start the service, and one to turn off the alarm. Make a third action for resetting the alarm.
To start the service, send a "start" intent to the IntentService using startService(intent). This should trigger a method that creates an intent with action "cycle", puts the intent in a PendingIntent, and schedules a repeating alarm with AlarmManager.setRepeating().
After the interval that you set for the alarm, the AlarmManager will take the "cycle" intent out of the PendingIntent and send it back to your service. Your service should handle "cycle" by rebuilding the PendingIntent and restarting the alarm. This goes on indefinitely. You can put anything else you want to do when the alarm goes off in the handling for the "cycle" action.
When you want the alarm to stop, send the "stop" intent. In response, your service should cancel the alarm by reconstructing the PendingIntent and then calling AlarmManager.cancel().
Notes: The main entry point for an IntentService is onHandleIntent(). You call everything else from there. When that method finishes, the service goes inactive until it receives another intent. The only place you can "see" it is in cached processes. Once you stop the alarm, the system will eventually figure out that the service isn't being used, and garbage-collect it.
Services are the way to do background work. I suppose you can run some AsyncTask or a thread, but you still want to run them in a Service, otherwise you've linked them to something that's running in the foreground. If the task doesn't need to interact with the user, particularly if it can work asynchronously to your activity, then use a service.

Timer Task VS Alarm Manager usage in Android Service

I need to fetch news/event updates from the server at regular intervals like for every 20mins in my Android App. AFAIK Intent Service and Broadcast Receiver combination will be better than using Service As I am not going to communicate with the running Service. In order to fetch events at regular intervals I know 2 options
1) Using Timer Task ScheduleAtFixedRate, I am going to start IntentService, which will fetch events once & broadcast if any updates and destroy itself. After Given Interval, IntentService will be again fired by TimerTask
2) Simply starting Intent Service at the start of app and within Intent Service onHandleIntent method Starting a TimerTask ScheduleAtFixedRate. If this is preferred way, How and when I cancel Timer Task and When the Intent Service is going to get Destroyed.
or I have to use Alarm Manager. Note I need these updates as long as I am using the App, also I need updates for every 20 to 30 mins not for every 1 or 3 mins.
Any body please suggest me, Thanks in Advance.
Go for AlarmManager. I have tried TimerTask before, it does not work properly in some devices and get killed after some time.

How to keep a task alive after phone sleeps?

my application needs to send a message to my server every 30 seconds or so.
I understand I need to use AlarmManager using RTC_WAKEUP or ELAPSED_REALTIME_WAKEUP.
now I don't understand two things:
1) If the AlarmManager wakes up the device, why do I need to aquire a WakeLock?
2) I saw an example for using AlarmManager with WakeLock. In this example, its setting the alarm to send a broadcast to a broadcast receiver which then acquires a static wake lock and then start an IntentService which runs a task.
now, my question is, in my case, I need to follow this example entirely? why don't set the alarm to start a service instead?

Categories

Resources