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.
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.
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.
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);
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