Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Android上中断执行的Runnable

Android上中断执行的Runnableimport 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