当前位置: 移动技术网 > 移动技术>移动开发>Android > AsyncTask的简单实用

AsyncTask的简单实用

2020年07月17日  | 移动技术网移动技术  | 我要评论

1.基本描述

1.1.AsyncTask是Android提供的轻量级( 实现代码量少) 的异步类。
1.2.为了降低异步通信的开发难度,提供了AsyncTask。
1.3.AsyncTask直接继承于0bject类,位于android.os包中。
1.4.使用AsyncTask可以忽略Looper、MessageQueue、Handler等复杂对象,更便捷的完成异步耗时操作。

2.简单使用:

 

2.1.extends AsyncTask<Params, Progress, Result>

继承AsyncTask 

/**
 * Params, the type of the parameters sent to the task uponexecution.在执行AsyncTask需要传入的参数,可用于在后台任务中使用
 * Progress, the type of the progress units published during the background computation.后台任务执行时,UI显示当前进度,
 * Result, the type of the result of the background computation. 执行完毕需要对结果进行返回
 */

2.2.实现必要方法:

异步的代码基本都在这里完成

@Override
protected Boolean doInBackground(Void... voids) {
    return null;
}
子线程中执行 完成后通过return返回结果 但是此方法并不能进行UI操作

2.3.重写其他几个方法

  //后台任务开始执行前调用,用于界面的初始化操作,比如显示出精度条
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          
        }
  //进行UI操作
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
           
        }

        //任务完毕调用 可以执行UI操作比如关闭进度条
        @Override
        protected void onPostExecute(Boolean aBoolean) {
           super.onPostExecute(aBoolean);
          
        }

2.4.启动

new myAsyncTask().execute();

3.完整代码举例:

package com.example.myasynctaskdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import org.w3c.dom.DOMImplementation;

import java.util.function.DoubleToIntFunction;

public class MainActivity extends AppCompatActivity {
    private ProgressBar pb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button3 = findViewById(R.id.button3);
        pb = findViewById(R.id.pb);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new UpDataTask().execute();
            }
        });
    }

    /**
     * Params, the type of the parameters sent to the task uponexecution.在执行AsyncTask需要传入的参数,可用于在后台任务中使用
     * Progress, the type of the progress units published during the background computation.后台任务执行时,UI显示当前进度,
     * Result, the type of the result of the background computation. 执行完毕需要对结果进行返回
     */
    class UpDataTask extends AsyncTask<Void, Integer, Boolean> {



        //后台任务开始执行前调用,用于界面的初始化操作,比如显示出精度条
        @Override
        protected void onPreExecute() {
//            super.onPreExecute();
            pb.setVisibility(View.VISIBLE);
        }

        //子线程中执行 完成后通过return返回结果 但是此方法并不能进行UI操作
        @Override
        protected Boolean doInBackground(Void... voids) {

            int count = 0;
            while (true) {
                try {
                    count++;
                    publishProgress(count);//反馈任务执行进度 调用后很快会调用onProgressUpdate
                    if (count > 100)
                        break;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }



        //进行UI操作
        @Override
        protected void onProgressUpdate(Integer... values) {
//            super.onProgressUpdate(values);
            pb.setProgress(values[0]);
        }

        //任务完毕调用 可以执行UI操作比如关闭进度条
        @Override
        protected void onPostExecute(Boolean aBoolean) {
//            super.onPostExecute(aBoolean);
            pb.setVisibility(View.GONE);
        }
    }
}

对应的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启异步" />

    <ProgressBar
        android:id="@+id/pb"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="50"
        android:visibility="gone" />

</LinearLayout>

转发表明出处https://blog.csdn.net/qq_35698774/article/details/107394945

点击下载

android互助群:

 

本文地址:https://blog.csdn.net/qq_35698774/article/details/107394945

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网