Android之Handler详解(三)
程序员文章站
2022-01-21 19:02:38
...
c、将消息队列绑定到子线程上,主线程只管通过Handler往子线程的消息队列中投递消息即可。
package com.dxyh.test;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
public class MainActivity extends Activity {
private final static String TAG = "HandlerTest";
private final static int TASK_BEGIN = 1;
private final static int TASK_1 = 2;
private final static int TASK_2 = 3;
private final static int TASK_END = 4;
private MyHandler mHandler = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "[M_TID:" + Thread.currentThread().getId() + "]" +
"This is in main thread.");
HandlerThread myLooperThread = new HandlerThread("my looper thread");
myLooperThread.start();
Looper looper = myLooperThread.getLooper();
mHandler = new MyHandler(looper);
// 启动任务(消息只有标识,立即投递)
mHandler.sendEmptyMessage(TASK_BEGIN);
Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_START to handler.");
// 开始任务1(在mHandler的消息队列中获取一个Message对象,避免重复构造)
Message msg1 = mHandler.obtainMessage(TASK_1);
msg1.obj = "This is task1";
mHandler.sendMessage(msg1);
Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_1 to handler.");
// 开启任务2(和上面类似)
Message msg2 = Message.obtain();
msg2.arg1 = 10;
msg2.arg2 = 20;
msg2.what = TASK_2;
mHandler.sendMessage(msg2);
Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_2 to handler.");
// 结束任务(空消息体,延时2s投递)
mHandler.sendEmptyMessageDelayed(TASK_END, 2000);
Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_END to handler.");
}
class MyHandler extends Handler {
public MyHandler(Looper looper) {
super(looper);
}
// 现在在每个case之后,你可以做任何耗时的操作了
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TASK_BEGIN:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_BEGIN");
break;
case TASK_1:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_1");
break;
case TASK_2:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_2");
break;
case TASK_END:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_END");
finish();
break;
}
super.handleMessage(msg);
}
}
}
运行结果:
上一篇: ubuntu创建用户+文件读写权限+新用户添加到组
下一篇: day4_JAVA字符串