package com.example.hasee.androidmsg;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
import android.util.Log;
import android.os.HandlerThread;
public class MainActivity extends Activity {
private Button mButton;
private Thread myThread;
private MyThread myThread2;
private HandlerThread myThread3;
private Handler mHandler;
private Handler mHandler3;
private final String TAG="MessageTest";
private int ButtonCount = 0;
private int mMessageCount = 0;
class MyRunnable implements Runnable {
/* 线程执行主体 */
public void run () {
int count = 0;
for (;;) {
;
}
}
}
class MyThread extends Thread {
private Looper mLooper;
/* 发送消息者需要知道该线程的Looper */
public Looper getmLooper(){
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
@Override
public void run() {
super.run();
Looper.prepare();//创建消息队列
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Looper.loop();//启动消息循环
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Message msg = new Message();
mHandler.sendMessage(msg);
mHandler3.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "get Message for Thread3 ");
}
});
}
});
/* 直接使用 Thread 无法实现消息处理,根本原因无法获取looper */
myThread = new Thread(new MyRunnable(), "MessageTestThread");
myThread.start();
/* 实现一个myThread类 */
myThread2 = new MyThread();
myThread2.start();
/* 通过Handler 来发送消息,发送给谁?Looper决定,同时传入回调函数,接收线程用于消息处理 */
mHandler = new Handler(myThread2.getmLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Log.d(TAG, "myThread2 ");
return false;
}
});
/* 直接使用 HandlerThread 类 */
myThread3 = new HandlerThread("MessageTestThread3");
myThread3.start();
mHandler3 = new Handler(myThread3.getLooper());
}
}
Android 消息处理机制——线程通信
最新推荐文章于 2024-08-22 15:47:11 发布