发送消息到handlerthread

时间:2018-11-15 22:59:13

标签: android android-handler android-looper android-thread

任务很简单。我要做的就是将消息从MainActivity发送到自己的HandlerThread。

所有代码均已附加并注释

MyHandlerThread

public class MyHandlerThread extends HandlerThread implements Handler.Callback {

private static final String TAG = "MyHandlerThread";

public MyHandlerThread(String name) {
    super(name);
    Log.i(TAG,this.getName());
}

/**
 * @param msg A {@link Message Message} object
 * @return True if no further handling is desired
 */
@Override
public boolean handleMessage(Message msg) {
    Log.i(TAG,Integer.toString(msg.arg1)); //The message sent from MainActivity dosent end up here. Why?
    Log.i(TAG,Integer.toString(msg.arg2));
    return false;
}
}

MainActivity

class MainActivity : AppCompatActivity() {

private val TAG = "MainActivity"
private val workerThread = MyHandlerThread("MyThread");


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //setContentView(R.layout.activity_main)
    setContentView(R.layout.gauge_layout);
    workerThread.start()



    val mHandler: Handler = Handler(workerThread.looper) //Attach a handler to the MyHandlerThread looper

    var msg = mHandler.obtainMessage() // Get a message from the MyHandlerThread messageque
    msg.arg1 = 12 //Just add some int
    msg.arg2 = 99
    mHandler.sendMessage(msg) //Where is this message sent? The .sendMessage() returns true. It dosent end up in MyHandlerThread handleMessage()
}
}

我没有收到任何错误,.sendMessage返回true。但是我不知道它的发送位置或为什么它最终出现在MyHandlerThread handleMessage中。

希望有人可以提供帮助。

0 个答案:

没有答案