Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Handler messages in a background thread

I want to run some Runnable in a background thread. I want to use Handler because it's convenient for delays. What I mean is

handler.post(runnable, delay); 

Where runnable should be run in background Thread. Is it possible to create such Handler? Is there a "background" Looper somewhere or how can I create it?

P.S. I know how to do it with a custom class extends Thread but it requires a little more coding effort than doing it the handler way. So please don't post other solutions or something like

handler.post(new Runnable() {     @Override     public void run() {         new Thread() {             @Override             public void run() {                 //action             }         }.start();     } }); 

I just wander if Handler can do it the "clean" way.

like image 388
Yaroslav Mytkalyk Avatar asked Sep 09 '13 08:09

Yaroslav Mytkalyk


People also ask

How is handler class used for background thread processing?

Purpose of the Handler class. A Handler object registers itself with the thread in which it is created. It provides a channel to send data to this thread, for example the main thread. The data which can be posted via the Handler class can be an instance of the Message or the Runnable class.

Does handler run on UI thread?

A Handler allows communicating back with UI thread from other background thread . This is useful in android as android doesn't allow other threads to communicate directly with UI thread. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.


1 Answers

You can simply do this:

private Handler mHandler;  private HandlerThread mHandlerThread;  public void startHandlerThread(){     mHandlerThread = new HandlerThread("HandlerThread");     mHandlerThread.start();     mHandler = new Handler(mHandlerThread.getLooper()); } 

Then invoke with:

mHandler.postDelayed(new Runnable() {         @Override         public void run() {           // Your task goes here         }     },1000); 
like image 101
Himanshu Khandelwal Avatar answered Oct 08 '22 18:10

Himanshu Khandelwal