package com.example.handlerthread;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
/**
* HandlerThread就是一个线程,与一般线程不同在于,内部已经创建了一个Looper,将该Looper传递给
* Handler使用时,能够让Handler具备执行异步任务的能力
*/
private WeakHandlerThread mHandlerThread;
@SuppressLint("HandlerLeak")
private WeakMainHandler mMainHandler = new WeakMainHandler(this)
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 界面更新
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 要创建对象开启线程,让HandlerThread创建Looper
mHandlerThread = new WeakHandlerThread("weak_handler_thread", this);
mHandlerThread.start();
}
/**
* 主线程Handler
*/
private static class WeakMainHandler extends Handler {
private WeakReference<MainActivity> weakReference;
WeakMainHandler(MainActivity activity) {
weakReference = new WeakReference<>(activity);
}
void clear() {
if (weakReference != null) {
weakReference.clear();
}
}
}
/**
* HandlerThread线程
*/
private static final class WeakHandlerThread extends HandlerThread {
private WeakReference<MainActivity> weakReference;
private Handler threadHandler;
WeakHandlerThread(String name, MainActivity activity) {
super(name);
weakReference = new WeakReference<>(activity);
}
// 可以初始化其他操作
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
threadHandler = new Handler(getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
// 耗时操作
return false;
}
});
}
void clear() {
if (threadHandler != null) {
threadHandler.removeCallbacksAndMessages(null);
}
if (weakReference != null) {
weakReference.clear();
}
}
}
@Override
protected void onStop() {
super.onStop();
if (isFinishing()) {
// 释放资源,防止内存泄漏
if (mHandlerThread != null) {
mHandlerThread.quit();
mHandlerThread.clear();
}
if (mMainHandler != null) {
mMainHandler.removeCallbacksAndMessages(null);
mMainHandler.clear();
}
}
}
}
Android HandlerThread
最新推荐文章于 2020-08-24 09:40:04 发布