AsyncTask使用

AsyncTask是一个轻量级的异步任务类,用于在线程池中执行后台任务并更新UI。它有特定的使用条件,如必须在主线程创建和调用execute方法,且一个对象只能执行一次。通过executeOnExecutor()可以实现并行执行任务。在实际应用中,例如下载图片并显示进度,可以利用AsyncTask进行处理。
摘要由CSDN通过智能技术生成

AsyncTask是一个轻量级的异步任务类。它可以在线程池中执行耗时的后台任务。然后把执行的进度和结果传递给主线程并且在主线程中更新UI。

AsyncTask基本介绍

本身是一个抽象类:

public abstract class AsyncTask<Params, Progress, Result> {}

其中参数如下:

泛型 意义
Params 异步任务的入参,比如下载图片时传入String类型的url
Progress 任务执行的进度
Result 任务的执行结果

几个常用的方法介绍如下:

  1. void onPreExecute() : 任务开启前的准备,设置UI的状态等(位于主线程
  2. Result doInBackground(Params...param) : 开启子线程执行后台任务,Params就是三个泛型中的第一个;Result为任务执行的返回值当作参数传入onPostExecute()函数(位于子线程
  3. void onPostExecute(Result result) : 任务执行完毕后回调此方法,可在这里进行UI更新等(位于主线程
  4. void onProgressUpdate(Progress... values) : 任务执行的过程中进行进度更新,参数即为泛型的第二个(位于主线程
  5. publishProgress(PROGRESS_MAX, maxLen): 在后台任务执行过程中调用此方法会调用onProgressUpdate()方法对UI进行更新

使用方法:

new AsyncTask().execute(Params);

AsyncTask使用的条件限制

  1. 必须在主线程中创建
  2. execute方法必须在UI线程中调用
  3. 不要在程序中直接调用一系列方法doInBackground等
  4. 一个对象只能执行一次,即只能调用一次execute方法

AsyncTask源码简单介绍

大致的流程如下图(比较简陋,有很多没有提及的地方):
在这里插入图片描述
接下来我列出我认为相对重要的方法:

  1. 构造方法
    实例化mWorker/mFuture,并将两者绑定。
 /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        this((Looper) null);
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     *
     * @hide
     */
    public AsyncTask(@Nullable Handler handler) {
        this(handler != null ? handler.getLooper() : null);
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     *
     * @hide
     */
    public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

		// 实例化Callable
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值