这里只是写了个HandlerThread的简单栗子,什么也不多说。
以后有时间再说一下原理什么的。
package com.audienl.test;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.AnyThread;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.Random;
public class HandlerThreadActivity extends AppCompatActivity {
private static final String TAG = "HandlerThreadActivity";
private TextView mTvShow;
private Handler mHandler = new Handler();// UI线程的Handler
private HandlerThread mHandlerThread;
private HandlerThreadHandler mHandlerThreadHandler;// HandlerThread的Handler
private boolean isUpdate = false;
public static void start(Context context) {
Intent starter = new Intent(context, HandlerThreadActivity.class);
context.startActivity(starter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handle_thread);
mTvShow = (TextView) findViewById(R.id.tv_show);
// 创建工作线程,并初始化其Handler。注意:一定要是线程start之后,因为Looper.prepare()在run方法里面。
mHandlerThread = new HandlerThread("update");
mHandlerThread.start();
mHandlerThreadHandler = new HandlerThreadHandler(mHandlerThread.getLooper(), this);
}
/**
* 更新界面
*/
@AnyThread
private void update(int num) {
mHandler.post(new Runnable() {
@Override
public void run() {
mTvShow.setText(String.valueOf(num));
Log.i(TAG, "Update: " + num);
}
});
}
/**
* 使用静态内部类,以及弱引用,避免内存泄漏。
*/
private final static class HandlerThreadHandler extends Handler {
private WeakReference<HandlerThreadActivity> mActivity;
public HandlerThreadHandler(Looper looper, HandlerThreadActivity activity) {
super(looper);
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
HandlerThreadActivity activity = mActivity.get();
if (activity != null) {
if (activity.isUpdate) {
activity.update(new Random().nextInt());
SystemClock.sleep(2000);
if (activity.mHandlerThreadHandler != null) {
activity.mHandlerThreadHandler.sendEmptyMessage(0);
}
}
}
}
}
@Override
protected void onStart() {
super.onStart();
isUpdate = true;
mHandlerThreadHandler.sendEmptyMessage(0);
}
@Override
protected void onStop() {
super.onStop();
isUpdate = false;
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
mHandlerThreadHandler = null;
}
}