Let's say that I want to perform some action every 10 seconds and it doesn't necessarily need to update the view.
The question is: is it better (I mean more efficient and effective) to use timer with timertask like here:
final Handler handler = new Handler(); TimerTask timertask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { <some task> } }); } }; timer = new Timer(); timer.schedule(timertask, 0, 15000); }
or just a handler with postdelayed
final Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { <some task> } }; handler.postDelayed(r, 15000);
Also I would be grateful if you could explain when to use which approach and why one of them is more efficient than another (if it actually is).
Handler is better than TimerTask . The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).
Timer and TimerTask are java util classes that we use to schedule tasks in a background thread. Basically, TimerTask is the task to perform, and Timer is the scheduler.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .
Handler
is better than TimerTask
.
The Java TimerTask
and the Android Handler
both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler
over TimerTask
in Android (see here, here, here, here, here, and here).
Some of reported problems with TimerTask include:
Example
The best source for all kinds of Android examples that I have seen is at Codepath. Here is a Handler
example from there for a repeating task.
// Create the Handler object (on the main thread by default) Handler handler = new Handler(); // Define the code block to be executed private Runnable runnableCode = new Runnable() { @Override public void run() { // Do something here on the main thread Log.d("Handlers", "Called on main thread"); // Repeat this the same runnable code block again another 2 seconds handler.postDelayed(runnableCode, 2000); } }; // Start the initial runnable task by posting through the handler handler.post(runnableCode);
Related
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With