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.
Related
I have some data in my SQLite database table. When my app starts, I want to send that data to the server every 5 minutes.
When the app is closed, it should stop.
What is the best approach for this?
Should I use Service or IntentService?
Should I use AlarmManager, Handler or any other thing?
I'm aware of my application speed. I don't want to make it slow. What is the effective approach?
If you are only transmitting when the app is in foreground, you can do it with a Handler.
You start the handler in onResume() and cancel it in onPause().
And perform the transmision with an AsyncTask or in a separate thread.
If you need to stransmit in background, you can use a service instead and schedule it with the AlarmManager.
And then start the service from the app's Activity.
I am not sure how IntentService would be used for this.
As you just want to run your process while the app is foreground, then TimerTask or Handler with conjunction to Message or Runable is good. It won't bother much your app's performance. If you ask about the better one from these two I'll say it's Handler. Check the details here in this answer:
https://stackoverflow.com/a/3975337/4128371
But if you want a really good performance then I'll suggest to go with AlarmManager. Otherwise Handler is a good option.
Alarm manager is not precise, an alarm schedule for 5 minutes may be that when the device is sleeping it will be fired at twice or triple the time.
If you want accuracy the device does not have to fall in sleep. ( I know that will shorten battery duration)
If you want to prevent the device to go to sleep you need to launch a foreground Service with a non dismissable Notification. That's the Service has to call startForeground()
While the device is awake both Alarmamanager and Handler + Runnable will be accurate ... I prefer the Handler.
I am creating a notification app, which will alert user after they set a reminder notification. My current implementation logic is:
Create a Service, which starts running in background when user opens their app.
In onCreate() method of service, I am implementing a Timer task which will repeat after 5000ms interval and will call a method, which will check all reminders set by user and notify user if any reminder is set for current time.
I use broadcast receiver to run the service on Boot_Completed event, if in case user turns off their phone.
This implementation is working good, I have faced no issues with it, but my concern is that is this a good practice? Keeping in mind that service running and checking every 5 secs will consume battery. Also if user turns on Stamina Mode, Power saving mode or any such mode, will OS kill my service. Is there anything I can do to give priority to my Service not to be killed.
If there is any other more efficient way to implement this sort of task, I want to implement that in my project.
Looking forward for suggestions.
Much Appreciated.
best approach is wakeful intent service with alarm receiver as mentioned here
https://github.com/commonsguy/cwac-wakeful
all good but use AlarmManager.setRepeating() as timer. the intent come even if your app killed.
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.
ok I have this application which needs to send periodic updates to a web-service, I have done a fair amount of research and I've come up with two service implementation patterns.
Implement a service with a thread, the periodic update time may vary therefore, I will put the thread to sleep with the required time-interval, then call the web-service again. I also need to update an activity, therefore will be using a broadcast receiver or a messenger.
Use a Service with a schedule timer/alarm manager, wake the system and use intent services coupled with a broadcast receiver.
Which would be the best approach?
I think I would go with the #2 option :
Create an IntentService to do the update.
Register a BroadcastReceiver with IntentFilter(s) and start the IntentService from it.
Use AlarmManager to Broadcast the registered action at the required time intervals.
I prefer this method because :
It is a very flexible pattern : You can start the service anytime by registering the same receiver for different actions like network connection changes, system boot changes etc.,
It keeps the logic loosely coupled from other parts of the app.
There is no hassle of managing threads. You get it for free by using IntentService
It is more android-ish way of solving this problem.
The main difference would be that a background service can be shut down by the user and then you won't get any more updates. If you register events with the AlarmManager, then you control when/if these events take place. If the user shuts down your app and goes into a task manager and shuts down any running services related to your app, the AlarmManager is still going to wake up and send a message that your BroadcastReceiver will receive.
In android a service is used to run in background. But the same can also be accomplished using alarm manager. The alarm receiver can do the same things that you would do in a service. So what is the need of service in android?
Well Both are totally different thigns.
AlarmManager Class is used to perform certain Events on after specific Time Intervalr or it can be on a regular Time Interval. An Events can be execution of Service too. AlarmManager allow you to schedule your application to be run at some point in the future.
While in case of Service it is a background process which doesnt have/requier a UI. A Service is not a saperate process or Service is not a thread. A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use
Actually these are two very different things. Alarm Manager can be used to do some tasks periodically using service. But Service can be used also e.g. to move some heavy work out of the UI thread(download data from rest server) or in case of foreground services, to do some work continously (mp3 player).
You can get some explanation on how to use service (with some advices considering AlarmManager) on Styling Android.
Generally,a service is used to process logic when you don't need a UI anymore. For example the service I want to use checks a social networking site for updates every 15 minutes . The service has the logic of processing the update. But who will start the service every 15 minutes? That is where AlarmManager is used. It will periodically start my service every 15 minutes once, so that the service could execute its logic and stop itself once the job is done and my application doesn't keep draining the battery.