Reputation: 5049
I have the need to send and take something from a server in Android on every 10 seconds. Here, on StackOverflow, and in the documentation I found literally dozens of ways to implement it (and everything I tried does the job), but it seems that everywhere someone says something is wrong with that way.
I tried with a looping AsyncTask
until it is canceled (that is untill the activity is killed), and I found out that it's not a good solution. Before that I tried with regular Threads
, then I found out that it drains the battery a lot.
Now I've done it with a Runnable
and and the ScheduledExecutorService's scheduleAtFixedRate
function, similar to the code proposed here:
How to run an async task for every x mins in android? . Needless to say, it works. But will it work if my Activity is in the background, for example the user is answering an incoming call?
In the end, I don't know anymore what is the most proper way of doing it on an Android phone.
Tnx in advance.
Upvotes: 2
Views: 541
Reputation: 10762
Would recommend using the AlarmManager and BroadcastReceivers if you need your scheduled task to occur even when your app is not currently running.
Otherwise the documentation recommends using Handlers.
As discussed in the comments of AmitD's question. If the task needs to run in the background, you can use an AsyncTask inside the handler callback to achieve this.
final Handler handler = new Handler() {
public void handlerMessage(Message msg) {
new AsyncTask<TaskParameterType,Integer,TaskResultType>() {
protected TaskResultType doInBackground(TaskParameterType... taskParameters) {
// Perform background task - runs asynchronously
}
protected void onProgressUpdate(Integer... progress) {
// update the UI with progress (in response to call to publishProgress())
// - runs on UI thread
}
protected void onPostExecute(TaskResultType result) {
// update the UI with completion - runs on UI thread
}
}.execute(taskParameterObject);
}
};
handler.postMessageDelayed(msg, delayMillis);
For repeated executions the doc also mentions ScheduledThreadPoolExecutor as an option (which is preferred over java.util.Timer, primarily due to extra flexibility, it seems).
final Handler handler = new Handler() {
public void handlerMessage(Message msg) {
// update the UI - runs on the UI thread
}
};
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
ScheduledFuture f = exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
// perform background task - runs on a background thread
handler.sendMessage(msg); // trigger UI update
}
}, 0, 10, TimeUnit.SECONDS);
Upvotes: 1
Reputation: 19185
Use Handler
it has various methods like postDelayed(Runnable r, long delayMillis),postAtTime(Runnable r, Object token, long uptimeMillis)
etc.
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
//Start runnable here.
}
};
mHandler.sendMessageDelayed(msg, delayMillis)
Upvotes: 1
Reputation: 1003
Implementing repeating tasks is largely a function of the enormity/processing of the task. Will the UI block on your task. If so, then you can AsyncTask with a Handler and TimerTask.
In your activity onCreate or any generic function :
final Handler handler = new Handler();
timer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
// Instantiate the AsyncTask here and call the execute method
} catch (Exception e) {
e.printStackTrace();
}
}
});
timer.schedule(doAsynchronousTask,0,UPDATE_FREQUENCY)
}
Upvotes: 1
Reputation: 18670
I think I would use the Timer
class with a TimerTask
: http://developer.android.com/reference/java/util/Timer.html
Upvotes: 0