I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler
class. Here is a snippet from my code:
handler = new Handler(); Runnable r = new Runnable() { public void run() { tv.append("Hello World"); } }; handler.postDelayed(r, 1000);
When I run this application the text is displayed only once. Why?
The best way to do this thing is to use AlarmManager class. 2) set Broadcast receiver in Alarmmanager, it will call Receiver every particular time duration, now from Receiver you can start your thread . if you use Timer task and other scheduler, Android will kill them after some time.
A thread is a thread of execution in a program. TimerTask. A task that can be scheduled for one-time or repeated execution by a Timer . The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run .
AsyncTask is a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished. It's just a wrapper which uses a couple of runnables but handles all the intricacies of creating the thread and handling messaging between the threads.
There are two main ways to create handler threads. Create a new handler thread, and get the looper. Now, create a new handler by assigning the looper of the created handler thread and post your tasks on this handler. Extend the handler thread by creating the CustomHandlerThread class.
The simple fix to your example is :
handler = new Handler(); final Runnable r = new Runnable() { public void run() { tv.append("Hello World"); handler.postDelayed(this, 1000); } }; handler.postDelayed(r, 1000);
Or we can use normal thread for example (with original Runner) :
Thread thread = new Thread() { @Override public void run() { try { while(true) { sleep(1000); handler.post(this); } } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start();
You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.
More details are here http://developer.android.com/reference/android/os/Handler.html
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