useful if we need to watch the status of a thread.
import android.os.Message;
import android.os.Handler;
import android.os.MessageQueue;
import android.os.Looper;
import java.util.ArrayList;
import android.util.Log;
public class WatcherThread extends Thread{
private ArrayList<ThreadObservableInfo> mObservableList;
boolean bRun;
public String TAG = "WatcherThread";
public static WatcherThread g_instance = null;
private WatcherThread(){
bRun = true;
mObservableList
= new ArrayList<ThreadObservableInfo>();
}
public static WatcherThread getInstance(){
if(null == g_instance){
g_instance = new WatcherThread();
}
return g_instance;
}
boolean addCurrent(){
return addObservable(CurrentThreadInfo());
}
boolean addObservable(ThreadObservableInfo threadInfo){
for (ThreadObservableInfo info : mObservableList) {
if (info.mThread.getId()== Thread.currentThread().getId()){
return false;
}
}
return mObservableList.add(threadInfo);
}
boolean removeCurrent(){
for (ThreadObservableInfo info : mObservableList) {
if (info.mThread.getId()== Thread.currentThread().getId()){
return removeObserverable(info);
}
}
return false;
}
boolean removeObserverable(ThreadObservableInfo threadInfo){
return mObservableList.remove(threadInfo);
}
void clear(){
mObservableList.clear();
}
void startTrace(){
synchronized(WatcherThread.this){
bRun = true;
}
try{
this.start();
}catch(Exception e){
Log.d(TAG, "lyftest new e="+e);
}
}
@Override
public void run(){
while(bRun){
for (ThreadObservableInfo info : mObservableList) {
info.setAlive(false);
info.helloObserver();
}
try{
Thread.sleep(800);
}catch(InterruptedException e){
;
}
for (ThreadObservableInfo info : mObservableList) {
info.checkAlive();
}
}
}
public void stopTrace(){
synchronized(WatcherThread.this){
bRun = false;
}
g_instance = null;
}
public ThreadObservableInfo CurrentThreadInfo(){
return new ThreadObservableInfo();
}
public class ThreadObservableInfo{
public MessageQueue mQueue;
public Handler mHandler;
public Thread mThread;
public boolean mAlive = false;
public String mName;
public int mTimes = 0;
ThreadObservableInfo(){
//get infor from the current thread;
mHandler = new Handler();
mQueue = Looper.getMainLooper().myQueue();
mThread = Thread.currentThread();
}
void setAlive(boolean value){
mAlive = value;
}
void helloObserver(){
Runnable r = new Runnable(){
public void run(){
setAlive(true);
}
};
Message msg = Message.obtain(mHandler, r);
mHandler.sendMessage(msg);
}
boolean isAlive(){
return mAlive;
}
void dumpThread(){
Log.d("ThreadObservableInfo", "WatcherThread name="+mName);
mQueue.dumpQueue_l();
}
void checkAlive(){
if (mAlive){
mTimes = 0;
return;
}
if (mTimes >= 5){
mTimes = 0;
dumpThread();
}
}
}
}