AsyncTask基本使用

作者: UC_ | 来源:发表于2020-08-19 02:04 被阅读0次

描述及作用

  • AsyncTask(异步任务类),比Handler更轻量,更适合简单的异步操作
  • 内部实现了对Thread和Handler的封装,方便后台线程操作后UI的更新
  • 在用AsyncTask进行UI更新时,不用额外创建Handler,直接用AsyncTask内部封装好的几个方法

三个泛型参数

AsyncTask直接继承于Object类,位置为android.os.AsyncTask,使用AsyncTask要提供三个泛型参数,作用是控制AsyncTask的子类在执行线程任务时每个阶段的返回类型

方法 描述
Params 开始异步任务执行时传入的参数类型,对应execute()中传递的参数
Progress 异步任务执行过程中,返回任务进度值的类型
Result 异步任务执行完成后,返回的结果类型,与doInBackground()的返回值类型保持一致

核心方法

execute(),执行AsyncTask
cancel(true),取消AsyncTask
isCancelled(),判断是否被取消

执行顺序onPreExecute->doInBackground->onProgressUpdate->onPostExecute(在执行被取消时调用onCancelled)

重写方法 描述
doinBackground() 在子线程执行(异步任务)耗时操作,执行完后有返回结果
onPreExecute() 在doinBackground执行前
onProgressUpdate() 在UI线程中更新doinBackground的执行进度
onPostExecute() 接收doinBackground执行完后的返回结果,并显示到界面上去 ,如果执行被取消则无法调用
onCancelled() 在执行被取消时调用

从源码可以知道被重写方法的返回值,参数,即上述的三个泛型参数,以及他们所在的线程
doinBackground(),是抽象方法,在继承AsyncTask时,要求重写,其他按需求重写

源码 线程
protected abstract Result doInBackground(Params... params); @WorkerThread
protected void onPreExecute() {} @MainThread
protected void onProgressUpdate(Progress... values) {} @MainThread
protected void onPostExecute(Result result) {} @MainThread
protected void onCancelled(Result result) {onCancelled();} @MainThread
protected void onCancelled() {} @MainThread

Demo

1.定义一个AsyncTask子类
2.在UI线程实例化子类
3.在UI线程中启动(->取消)

效果


布局文件activity_progress.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProgressActivity"
    android:background="#CCCCCC"
    >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="尚未开始"
        android:textSize="28sp"
        android:layout_marginBottom="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:progress="0"
        app:layout_constraintTop_toBottomOf="@id/text" />

    <ImageView
        android:id="@+id/start"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="100dp"
        android:src="@mipmap/start"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/progress_bar" />

    <ImageView
        android:id="@+id/cancel"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_marginTop="30dp"
        android:layout_marginRight="100dp"
        android:src="@mipmap/stop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/progress_bar" />

</androidx.constraintlayout.widget.ConstraintLayout>

Activity文件,ProgressActivity.java

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ProgressActivity extends AppCompatActivity {

    //初始化控件
    private TextView text;
    private ImageView start,cancel;
    private ProgressBar progressBar;
    //初始化一个AsyncTask子类
    private ProgressTask pTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress);

        progressBar=findViewById(R.id.progress_bar);
        start=findViewById(R.id.start);
        cancel=findViewById(R.id.cancel);
        text=findViewById(R.id.text);

        //实例一个AsyncTask子类
        pTask=new ProgressTask();

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //执行异步任务
                pTask.execute();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消异步任务
                pTask.cancel(true);
            }
        });
    }

    //子类继承AsyncTask
    class ProgressTask extends AsyncTask<Void,Integer,String>{

        //执行doInBackground之前的操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            text.setText("加载中");
        }

        //执行任务中的耗时操作,返回线程任务的执行结果
        @Override
        protected String doInBackground(Void... voids) {
            //模拟耗时操作
            try {
                for (int i=1;i<=100;i++){
                    publishProgress(i);
                    Thread.sleep(50);
                }
                return "加载完毕";
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        //在主线程中显示线程任务的执行进度,在doInBackground方法中调用publishProgress方法则触发该方法
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
            text.setText("加载..."+values[0]+"%");
        }

        //接受线程任务的执行结果,将执行结果显示在界面上
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s!=null){
                text.setText(s);
            }
            //异步任务每次只能用一次,如果还想用,再实例一次AsyncTask子类
            pTask=new ProgressTask();
        }

        //取消cancel异步任务时触发
        @Override
        protected void onCancelled() {
            super.onCancelled();
            text.setText("已取消");
            progressBar.setProgress(0);
            //异步任务每次只能用一次,如果还想用,再实例一次AsyncTask子类
            pTask=new ProgressTask();
        }
    }
}

相关文章

网友评论

    本文标题:AsyncTask基本使用

    本文链接:https://www.haomeiwen.com/subject/abkqjktx.html