当前位置: 代码迷 >> Android >> android上中止执行的Runnable
  详细解决方案

android上中止执行的Runnable

热度:110   发布时间:2016-05-01 10:56:04.0
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            }        }    }}

  相关解决方案