想要在子线程处理数据,然后在主线程更新UI,可以定义两个Handler,一个是workHandler运行在子线程,一个是mainHandler运行在主线程,在workHandler的handleMessage方法中处理数据,然后使用mainHandler的post方法更新UI,代码如下:
activity_my.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/text1"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试结果" />
<Button
android:id="@+id/button1"
android:layout_centerInParent="true"
android:layout_below="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击延迟1s,显示HelloKitty"/>
<Button
android:id="@+id/button2"
android:layout_centerInParent="true"
android:layout_below="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结束线程的消息循环"/>
</RelativeLayout>
MyActivity:
public class MyActivity extends AppCompatActivity {
private Handler mainHandler;
private TextView text;
private Button button1, button2;
private Handler workHandler;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
text = (TextView) findViewById(R.id.text1);
mainHandler = new Handler();
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
Log.d("test1111", "thread1:" + Thread.currentThread().getName());
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
workHandler = new Handler(Looper.myLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.d("test1111", "thread2:" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mainHandler.post(new Runnable() {
@Override
public void run () {
text.setText("HelloKitty");
}
});
}
};
workHandler.sendEmptyMessage(0);
Looper.loop();
Log.d("test1111", "after looper loop");
}
}).start();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(workHandler != null){
workHandler.getLooper().quit();
}
}
});
}
}
点击“显示HelloKitty”后,打印如下:
D/test1111: thread1:main
D/test1111: thread2:Thread-2
点击“结束线程的消息循环”后,打印如下:
D/test1111: after looper loop
可以看到workHandler的handleMessage()方法运行在子线程,Looper.loop()之后的代码在调用Looper的quit方法后才会执行。
这里必须要执行Looper.prepare(),否则执行会出错。
接下来我们使用HandlerThread实现相同的功能:
public class MyActivity2 extends AppCompatActivity {
private Handler mainHandler;
private TextView text;
private Button button1, button2;
private HandlerThread mHandlerThread;
private Handler workHandler;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
text = (TextView) findViewById(R.id.text1);
mainHandler = new Handler();
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
mHandlerThread = new HandlerThread("handlerThread");
mHandlerThread.start();
Log.d("test1111", "thread3:" + Thread.currentThread().getName());
workHandler = new Handler(mHandlerThread.getLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.d("test1111", "thread4:" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mainHandler.post(new Runnable() {
@Override
public void run () {
text.setText("HelloKitty");
}
});
}
};
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
workHandler.sendEmptyMessage(0);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandlerThread.quit();
}
});
}
}
点击“显示HelloKitty”按钮后,打印如下:
D/test1111: thread3:main
D/test1111: thread4:handlerThread
可以看到workHandler的handleMessage()方法运行在子线程,线程名为我们命名的的名字:handlerThread。
接下来我们看看HandlerThread的源码,HandlerThread类继承于Thread类,mHandlerThread.start()即开启了一个子线程,但是在使用HandlerThread的时候不需要执行Looper.prepare(),为什么呢?原来在HandlerThread的run()方法里面已经执行了。
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
//Looper.loop()后面的方法在执行Looper的quit方法后才会执行
mTid = -1;
}
public Looper getLooper() {
if (!isAlive()) {
return null;
}
boolean wasInterrupted = false;
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
wasInterrupted = true;
}
}
}
/*
* We may need to restore the thread's interrupted flag, because it may
* have been cleared above since we eat InterruptedExceptions
*/
if (wasInterrupted) {
Thread.currentThread().interrupt();
}
return mLooper;
}
这里使用了同步锁wait()和 notifyAll(),在run()中成功创建Looper对象后,立即调用notifyAll()通知getLooper()中的wait()结束等待并返回run()中创建的Looper对象,使得Handler与该Looper对象绑定。Looper.prepare()设置了子线程唯一的Looper,Looper.loop()会从MessageQueue中取出消息执行msg.target.dispatchMessage(msg),最终执行Handler的handleMessage()方法,所以handleMessage()方法执行在子线程中。