How to run an AsyncTask every x minutes - android

I have an asynctask which retrieve data from webserviece. I want to run this task every 5 minutes to get the updated data from the server, but till now I don't know how can I do it.
I tried this code but my AsyncTask didn't stop
//...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
new AddStringTask().execute();
}
}, 0, 5000);

As being suggested from others, you should use Push (GCM) instead of Poll. taken from this say:
Poll might easy to implement, but you will never be actually
real-time. If you polling interval is 30 min, you can get a message
that is 29 minutes and 59 seconds late. Moreover, polling more often
than every 15-30 min will kill your battery pretty quickly:
https://labs.ericsson.com/apis/mobile-java-push/blog/save-device-battery-mobile-java-push

As Michal K said, you can use AlarmManager with a Service and/or BroadcastReceiver to wake your app periodically.
However, in order to preserve the user's battery I highly recommend not polling the connection.
Instead, you can use Google Cloud Messaging for Android or GCM (formerly called C2DM)
Here's the site:
http://developer.android.com/guide/google/gcm/index.html
EDIT
The main benefit here is that Android phones that have Google accounts will already poll Google's servers periodically. They do this with cooperation from the carriers (like Verizon/AT&T). Because of this, the radio can go into low power mode and receive push notifications. By using Google's service, you enable a way for your app to receive data via push notifications without causing any extra battery drain.
====================
(Also, here is some of the info from my other post about this).
There was a very interesting Google IO talk this year about how the cell radio sits in an idle/low-power state most of the time, and takes a few seconds to "warm up". They also discuss the perils of how polling the internet periodically will really drain the battery.
http://www.youtube.com/watch?v=PwC1OlJo5VM
Battery talk starts about 17:12
http://www.youtube.com/watch?v=PwC1OlJo5VM&feature=player_detailpage#t=1032s
A slide from the presentation:

Related

Worker vs Service android application. Running app for long time, never stops

Android : java class →
Worker vs Service ?
What is the difference between Worker and Service? Which is better to do something in background for a long time. Application never stops.
Dear friends.
Android : java class →
Worker vs Service
I made an android application and inherited the Service class and it checks a website every minute and if there is new information on this website, it sends me a notification.
Does anyone know about Worker and what is the difference between Worker and Service? Which is better to do something in background for long time. I want to make an application, that it never stops.
Don't do this. This is the wrong architecture for a mobile device. You'd kill the battery by forcing the cellular radio to constantly be transmitting. Instead, use push notifications from your server to the device when there's new information.
As for workers vs services- everything in Android is written to prevent long term background processes. Background services can last a max of 2 minutes after your app is no longer in the foreground. A Foreground service lasts longer, but can still be killed for resources. A worker is a better idea for long term work, but can't be done once a minute. And if the phone is in Doze mode (entered a minute or two after the user puts the phone screen off) you're limited to one short period of processing every 15 minutes anyway.
The right way to do this is push messaging. If you want the notificaion to be instant, use high priority messages. This will be better on your server side as well, as N clients pinging every minute would cause a ton of traffic and cost you a ton in hosting fees.

Best practice for creating a repeating HTTP request in Android that won't stop when device sleeps?

I am writing an Android app to alert the user an event in "almost" real time. The app sends an HTTP Get request asynchronously, and processes the received result when it arrives to determine the state of the event. To be reasonably up-to-date, the HTTP requests need to be made every 15-60 seconds.
I have implemented this using a foreground service, thinking this would allow the alert when the app is in the background. The service contains the following code to handle the recurring requests (with an AsyncTask subclass to handle the actual HTTP request):
Handler queryHandler = new Handler();
runQuery = new Runnable() {
#Override
public void run() {
new HTTPGetTask().execute(urlString);
queryHandler.postDelayed(runQuery, queryFrequencyInMilliseconds);
}
};
It works fine until the device sleeps. Then the service sleeps as well, only waking and reporting status at intervals that are far too long to be useful.
I've been reading about AlarmManagers, Partial WakeLocks, WakefulBroadcastReceivers, and Job Schedulers. (e.g., Keep a Service running even when phone is asleep). I need to target older devices (API level 19) so the JobScheduler approach is out.
There are clearly a number of approaches to scheduling recurrent tasks, but it seems that the best approach depends a number of factors, including length of task, frequency of task, how precise the timing needs to be. For example, Android documentation on AlarmManager states
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
Any suggestions on best approach / design pattern for an HTTP request repeating every 15 - 60 seconds, given that the returned result is small, and that the user needs to get the result in a timely fashion when the app is in the background and even if the device sleeps? The timing doesn't need to be exact, but should be reasonably consistent.
(edited to add) Typical use case is that the service would be in operation for 5 to 30 minutes, and would stop once a final event state had been received and the user alerted. I would also probably have a maximum allowed running time of 30 - 60 minutes.
If you have the ability to implement an intermediary server, you could use that to Poll the source server and then provide Push Notifications to the individual devices as needed.
This will mean that your Devices will only need to 'talk' to the network when it is needed (saving Battery etc).
If you are up on AWS, you can use a CloudWatch Timed Event which invokes a Lambda function to call your 'base' server. If there is anything that needs communicating to the devices you can then invoke the Push Notif service (again AWS has SNS or you can just call GCM (Firebase Messaging) or APNS directly).
Good luck!
Gav

Android - slow network acces when phone is in iddle mode

I have application which for every 10 seconds do some request to server (http client). I read a lot about application life cycle. My application has service with foreground flag and it's work well (application work all time) when android is "active". I don't have phone with real android, so I am testing on emulator, but my friend testing it on smartphone and he notice that when he leave his phone, request are post for 10, 30 minutes, even hour. If he turn on screen, then request time is back to 10 seconds (he have access to server so he see logs). Is this known behavior? Because he installed gmail notifier from google, and this same problem (big delay). Any solution for this? My service have timer task (so request is sent in async task)
Regards
First of all, if you're polling every 10 seconds, that's gonna drain a lot of battery and network bandwidth.
I recommend using a lower frequency or server push.
For the polling issue, how do you implemented the polling ?
Do you use timers ? if so, what options do you pass in ? Or do you use a thread that sleeps for 10 seconds ?
Depending on the version, Android may turn off all processes, or delay network requests to run every 30 minutes to preserver battery power and bandwidth. (Starting up the network components drain a lot of battery than keeping them running. So If your app turns ON network, do a poll, then simply turn it off, Android may schedule it to align with all other requests on the system.)
Can you provide us more info about how you do the polling ?
UPDATE
You might have to schedule a 'WakeLock' so android knows when to wake up for your service. I think, by default, android doesn't wake up for timer requests that are scheduled very frequently and it schedules them as I explained. WakeLocks on the other hand can force android to wake up.
See this question and WakeLock Documentation
Make sure you pass the correct parameters, so you don't turn the screen ON. (Would be really annoying.)
UPDATE
I still recommend using server push for this, which will save battery and bandwidth while keeping the updates real time.

How to poll a webservice at finite interval from android?

i am developing an android app to show notifications.How can i poll a webservice at finite interval (say 10 min interval) to check for any update and show as notification in android notification panel.
You do not need a service. I feel like a broken record. In this use case a service will sit there for 95% of the time doing nothing but still using system resources and more importantly drain the battery.
Please see my answer on a similar question that uses an Alarm from the AlarmManager:
Running task periodicaly(once a day/once a week)
Edit:
Look at this tutorial from the Android Development site for how to implement notifications: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
There is Cloud to Device Messaging service provided by Google C2DM . You can use this service to push message into all registered mobile devices. This not only improves performance but also makes sure that the Battery is not drained while continuously polling the server.
For your scenario, you can write in a java class to regularly poll the web service and use C2DM service to push the message to your Android phone which can be shown as a Notification. Check out this tutorial by Vogella on link. Or better, if you are using the web service just for fetching updated details, then you can avoid the web service and directly call the C2DM Push Service to push message to all registered devices whenever there is a change.
Hope this helped. :)
use timer in which you can call to that web service after finite interval for e.x
Timer waitingTimer = new Timer();
waitingTimer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
// code to hit xml after time interval
}
});
}
},0,20000); // mention time interval after which your xml will be hit.
Here 20000 means after every 20 sec it will be hit.
Define a service, having a thread with a timer, on timeout invoke webservice.

Best way to have an Android app poll periodically in the background

Take the Gmail app as an example. Whether the phone is on or not, it polls every 10 minutes or so to download new emails which may have arrived since you last checked.
I know how to create a new service and bind to it. But I can see a few ways to accomplish this:
Bind once, and have the service run in an infinite loop, sleeping for 10 minutes between each loop
Bind and unbind right when it's done, scheduling the next bind somehow in 10 minutes
Using the AlarmManager class to schedule future polls
What are the trade offs? How does the Gmail app accomplish it?
Thanks!
Gmail app uses pushing, not polling. I suggest using this technique instead, polling is a battery killer in mobile devices.
To implement pushing, take a look at C2DM.
If you still want to poll, the recommended way would be to set up a periodic alarm in the AlarmManager.
UPDATE: Google has deprecated C2DM and replaced it with Google Cloud Messaging (GCM)
UPDATE: Google has deprecated GCM and replaced it with
Firebase Cloud Messaging (FCM)
For a continuous, but not intensive poll like the one you comment (in the range of minutes between polls), I would implement it with AlarmManager. That way you make sure the phone wakes up to poll without the need for a wakelock, which would destroy your battery. As CommonsWare pointed out, you will still need to implement a wakelock for the time your code is executing, but you can release it as soon as the code is done, avoiding keeping the phone on while just waiting. See his comment for an example on how to implement it.
I would use a Service if, instead, you need faster polls during a shorter period of time (seconds between each poll), since setting alarms does not make sense to such short periods, and the battery would drain anyway.

Categories

Resources