MyException - 我的异常网
当前位置:我的异常网» Android » android上中止执行的Runnable

android上中止执行的Runnable

www.myexceptions.net  网友分享于:2013-04-10  浏览:12次
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
            }
        }
    }
}

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有