AsyncTask源码分析,kotlin开发桌面程序

} catch (ExecutionException e) {

throw new RuntimeException(“An error occurred while executing doInBackground()”,

e.getCause());

} catch (CancellationException e) {

postResultIfNotInvoked(null);

}

}

};

}

  • 我们先来分析一下mWorker;

mWorker为AsyncTask的一个内部类

,实现了Callable接口,在call方法里面会调用我们的doInBackground方法,这也就是为什么我们的doInBackground。方法是在子线程里面执行的,执行完doInBackground()方法会把结构传递给我们的postResult(result)方法,在result方法,会调用handler发送消息,

接着再handler的handleMessage里面处理,在handleMessage里面,又会调用我们的 finish()方法,finish()方法里面会判断任务是否取消,如果被取消,会调用onCancelled(),否则会调用onPostExecute()方法。

private static class InternalHandler extends Handler {

public InternalHandler() {

super(Looper.getMainLooper());

}

@SuppressWarnings({“unchecked”, “RawUseOfParameterizedType”})

@Override

public void handleMessage(Message msg) {

AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;

switch (msg.what) {

case MESSAGE_POST_RESULT:

// There is only one result

result.mTask.finish(result.mData[0]);

break;

case MESSAGE_POST_PROGRESS:

result.mTask.onProgressUpdate(result.mData);

break;

}

}

}

private void finish(Result result) {

if (isCancelled()) {

onCancelled(result);

} else {

onPostExecute(result);

}

mStatus = Status.FINISHED;

}

  • 接着我们来分析一下mFuture

mFuture = new FutureTask(mWorker) {

@Override

protected void done() {

try {

postResultIfNotInvoked(get());

} catch (InterruptedException e) {

android.util.Log.w(LOG_TAG, e);

} catch (ExecutionException e) {

throw new RuntimeException(“An error occurred while executing doInBackground()”,

e.getCause());

} catch (CancellationException e) {

postResultIfNotInvoked(null);

}

}

};

  1. postResultIfNotInvoked(get());get()表示获取mWorker的call的返回值,即Result。

  • 13
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值