Android上中斷執行的Runnable
import android.content.Context;
import android.os.Handler;
import android.os.Process;
public abstract class CancelableThread implements Runnable {
private volatile boolean mStopped;
private Object mObject;
private Thread mThread;
private Context mContext;
private Handler mHandler;
public CancelableThread(Context context, Object obj, Handler handler) {
mObject = obj;
mContext = context;
mHandler = handler;
}
public CancelableThread(Context context, Handler handler) {
this(context, null, handler);
}
public CancelableThread(Context context, Object obj) {
this(context, obj, null);
}
public void start() {
if (mThread == null) {
mStopped = false;
mThread = new Thread(this, "CancelableThread");
mThread.start();
}
}
public void stop() {
if (mThread != null) {
mStopped = true;
mThread.interrupt();
mThread = null;
}
}
protected abstract void doWork(Context c, Object obj, Handler handler);
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (!mStopped) {
try {
doWork(mContext, mObject, mHandler);
mStopped = true;
Thread.sleep(10);
} catch (InterruptedException e) {
// Ignore
}
}
}
}
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11