Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a Runnable thread in Android at defined intervals?

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?

like image 546
Rajapandian Avatar asked Dec 17 '09 12:12

Rajapandian


People also ask

How do you run a thread periodically?

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.

What is runnable thread in Android?

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 .

What is the difference between AsyncTask and thread runnable?

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.

How do I get multithreading on my Android?

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.


1 Answers

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

like image 89
alex2k8 Avatar answered Sep 17 '22 17:09

alex2k8