- CompoundButton 源码分析
- LinearLayout 源码分析
- SearchView 源码解析
- LruCache 源码解析
- ViewDragHelper 源码解析
- BottomSheets 源码解析
- Media Player 源码分析
- NavigationView 源码解析
- Service 源码解析
- Binder 源码分析
- Android 应用 Preference 相关及源码浅析 SharePreferences 篇
- ScrollView 源码解析
- Handler 源码解析
- NestedScrollView 源码解析
- SQLiteOpenHelper/SQLiteDatabase/Cursor 源码解析
- Bundle 源码解析
- LocalBroadcastManager 源码解析
- Toast 源码解析
- TextInputLayout
- LayoutInflater 和 LayoutInflaterCompat 源码解析
- TextView 源码解析
- NestedScrolling 事件机制源码解析
- ViewGroup 源码解析
- StaticLayout 源码分析
- AtomicFile 源码解析
- AtomicFile 源码解析
- Spannable 源码分析
- Notification 之 Android 5.0 实现原理
- CoordinatorLayout 源码分析
- Scroller 源码解析
- SwipeRefreshLayout 源码分析
- FloatingActionButton 源码解析
- AsyncTask 源码分析
- TabLayout 源码解析
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
2.4、取消异步任务
AsyncTask.cancel(mayInterruptIfRunning);
mayInterruptIfRunning 是 boolean 类型的(注意这里 true 和 false 的区别),其调用流程:AsyncTask.cancel() -> FutureTask.cancel()。FutureTask.cancel() 的源码如下:
public boolean cancel(boolean mayInterruptIfRunning) {
//检测当前状态是否是 NEW,如果不是,说明任务已经完成或取消或中断,所以直接返回。
if (!(state == NEW &&
U.compareAndSwapInt(this, STATE, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
//如果 mayInterruptIfRunning 为 true 的时候,线程就会调用 interrupt() 方法,抛出异常。
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
//调用 interrupt 方法,状态设置为 INTERRUPTING,然后试着中断线程,完成后设置状态为 INTERRUPTED
t.interrupt();
} finally { // final state
U.putOrderedInt(this, STATE, INTERRUPTED);
}
}
} finally {
//通知等待线程的结果(因为 FutureTask.get() 法获得计算结果的唯一方法,如果计算没有完成,此方法会堵塞直到计算完成)
finishCompletion();
}
return true;
}
以下是我代码例子中 doInBackground() 中注释的,这里主要是为了强调 true 和 false 的区别。
try {
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}- 如果线程处于休眠状态,为 true 则正在执行的线程将会中断,抛出异常,但执行的任务线程会继续执行完毕调用
onCanceled()。为 false 则正在执行的线程不会中断,任务线程执行完毕调用onCanceled()。 - 如果线程不处于休眠状态,为 true 和 false 都没有区别,任务线程执行完毕后调用
onCanceled()。 正确地取消要在doInBackground(Void... params)使用isCancelled()来判断,退出循环操作。如下面的
@Override
protected Boolean doInBackground(Void... params) {
while (progress < 10000) {
progress = progress + 2;
Log.i("当前的进度", "progress==" + progress);
publishProgress(progress);
//判断是不是调用了 AsyncTask.cancel(mayInterruptIfRunning),如果已经调用了,
if(isCancelled())
{
break;//跳出循环,马上调用 onCancelled() 方法,不需要等 doInBackground 执行完任务
}
}
return true;
}绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论