import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import java.lang.ref.WeakReference;
public class MyHandlerThread implements Runnable {
/**
* mReadyFence对象通过synchronized保护mReady/mRunning两个变量
*/
private Object mReadyFence = new Object();
private boolean mReady;
private boolean mRunning;
private MyHandler mHandler;
public void start() {
synchronized (mReadyFence) {
if (mRunning) {
return;
}
mRunning = true;
new Thread(this, "TestThread").start();
while (!mReady) {
try {
mReadyFence.wait();
} catch (InterruptedException ie) {
// ignore
}
}
}
mHandler.sendEmptyMessage(MSG_START);
}
public void stop() {
mHandler.sendEmptyMessage(MSG_STOP);
mHandler.sendMessage(mHandler.obtainMessage(MSG_QUIT));
}
public boolean isRunning() {
synchronized (mReadyFence) {
return mRunning;
}
}
public void frameAvailable() {
synchronized (mReadyFence) {
if (!mReady) return;
}
mHandler.sendEmptyMessage(MSG_FRAME);
}
@Override
public void run() {
Looper.prepare();
synchronized (mReadyFence) {
mHandler = new MyHandler(this);
mReady = true;
mReadyFence.notifyAll();
}
Looper.loop();
synchronized (mReadyFence) {
mReady = mRunning = false;
mHandler = null;
}
}
private final static int MSG_START = 1;
private final static int MSG_STOP = 2;
private final static int MSG_FRAME = 3;
private final static int MSG_QUIT = 4;
private class MyHandler extends Handler {
private WeakReference<MyHandlerThread> mWeakThread;
public MyHandler(MyHandlerThread thread) {
mWeakThread = new WeakReference<MyHandlerThread>(thread);
}
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case MSG_START:
handleStart();
break;
case MSG_STOP:
handleStop();
break;
case MSG_FRAME:
handleFrame();
break;
case MSG_QUIT:
Looper.myLooper().quitSafely();
break;
}
}
}
private void handleStart() {
}
private void handleStop() {
}
private void handleFrame() {
}
}
网友评论