设为首页 加入收藏

TOP

Android上中断执行的Runnable
2014-11-24 07:43:27 来源: 作者: 【 】 浏览:0
Tags: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 2.3 StrictMode 使用 下一篇Android AsynTask 实现原理

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·PostgreSQL 索引 - (2025-12-25 22:20:43)
·MySQL Node.js 连接 (2025-12-25 22:20:41)
·SQL 撤销索引、表以 (2025-12-25 22:20:38)
·Linux系统简介 (2025-12-25 21:55:25)
·Linux安装MySQL过程 (2025-12-25 21:55:22)