I want to configure HandlerThread from a GUI thread. Then, after some time, when the button is pressed in the GUI, it launches callHello (), which then sends a message to the HelloLogger object, which is in the stream without the GUI, which asynchronously registers "Hello World". I tried several things, some blocks indefinitely, some never receive a message, etc. Etc. The code below is more or less close to the one I have, please, can someone change it to work?
public class HandlerThreadExample { private MyHandlerThread mMyHandlerThread; private Looper mLooper; private Handler mHandler; public HandlerThreadExample(){ mMyHandlerThread = new MyHandlerThread(); mMyHandlerThread.start(); mLooper = mMyHandlerThread.getLooper(); } public void callHello() { mHandler.sendEmptyMessage(1); } private class MyHandlerThread extends HandlerThread { private HelloLogger mHelloLogger; private Handler mHandler; public MyHandlerThread() { super("The MyHandlerThread thread", HandlerThread.NORM_PRIORITY); } public void run (){ mHelloLogger = new HelloLogger(); mHandler = new Handler(getLooper()){ public void handleMessage(Message msg){ mHelloLogger.logHello(); } }; super.run(); } } private class HelloLogger { public HelloLogger (){ } public void logHello(){ Log.d("HandlerThreadExample", "Hello World"); } } }
Found examples:
At least now I can close the damn tabs
Solution provided by pskink
public class HandlerThreadExample2 { private static int MSG_START_HELLO = 0; private static int MSG_HELLO_COMPLETE = 1; private HandlerThread ht; private Handler mHtHandler; private Handler mUiHandler; private boolean helloReady = false; public HandlerThreadExample2(){ ht = new HandlerThread("The new thread"); ht.start(); Log.d(App.TAG, "UI: handler thread started"); mUiHandler = new Handler(){ public void handleMessage(Message msg){ if (msg.what == MSG_HELLO_COMPLETE){ Log.d(App.TAG, "UI Thread: received notification of sleep completed "); helloReady = true; } } }; mHtHandler = new Handler(ht.getLooper()){ public void handleMessage (Message msg){ if (msg.what == MSG_START_HELLO){ Log.d(App.TAG, "handleMessage " + msg.what + " in " + Thread.currentThread() + " now sleeping"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } Log.d(App.TAG, "Woke up, notifying UI thread..."); mUiHandler.sendEmptyMessage(MSG_HELLO_COMPLETE); } } }; } public void sendLongHello(){ if (helloReady){ Log.d(App.TAG, "sending hello " + Thread.currentThread()); mHtHandler.sendEmptyMessage(MSG_START_HELLO); helloReady = false; } else { Log.e(App.TAG, "Cannot do hello yet - not ready"); } } }
android multithreading android-handler android-handlerthread
Jodes Aug 02 '14 at 11:03 2014-08-02 11:03
source share