Run Handler messages in a background thread
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);
You can try something like this
private void createHandler() { Thread thread = new Thread() { public void run() { Looper.prepare(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // Do Work handler.removeCallbacks(this); Looper.myLooper().quit(); } }, 2000); Looper.loop(); } }; thread.start(); }
You can set up a Looper in a background thread using Looper.prepare()
and Looper.loop
.