0309-AsyncTask知识点

本文详细介绍了Android中的AsyncTask类,包括其基本概念、使用方法及如何实现倒计时和进度条功能。通过具体实例展示了AsyncTask的灵活性和便利性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.什么是AsyncTask?

AsyncTask是安卓提供轻量级的异步类;
为了降低异步通信的开发难度,提供了AsyncTask;
AsyncTask直接继承于Object类,位于Android.os包;
使用AsyncTask可以直接忽略Looper、MessageQueue、
Handler等复杂对象、更便捷的完成异步耗时操作。

二、如何使用AsyncTask?

1.新建内部类继承AsyncTask
2.定义AsyncTask的三种泛型参数
3.重写doInBackgroud方法
4.重写onPreExecute方法
5.重写onProgressupdate方法
6..重写onPostExecute方法
7.在需要启动的地方execute方法

三、如何使用AsyncTask做倒计时?

带进度的AsyncTask中方法的调用顺序:
使用AsyncTask做倒计时首先要定义AsyncTask,
在UI线程中启动AsyncTask
初始化控件
在doInBackgroud中做耗时操作
在onProgressUpdate中得到进度设置控件进度
最后根据result设置控件,onPostExecute方法里更新UI

代码如下

在xml布局中设置控件
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:textSize="25sp"
            android:text="设置时间"
            />
        <EditText
            android:id="@+id/ed_text"
            android:layout_width="50dp"
            android:layout_height="40dp"
            />
        <TextView
            android:id="@+id/se_tv"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:textSize="25sp"
            android:text="秒"
            />
    </LinearLayout>

    <TextView
        android:id="@+id/djs_tv"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textSize="30sp"
        android:gravity="center"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="开始计时"
        android:textSize="25sp"
        android:id="@+id/st_btn"
        />
 </LinearLayout>

初始化控件,做准备

 private EditText editText1;
    private TextView textView;
    private Button button;

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

        bindID();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int time=Integer.parseInt(editText1.getText().toString());
                new MyAsyncTask().execute(time);
            }
        });
    }

    private void bindID() {
        editText1=findViewById(R.id.ed_text);
        textView=findViewById(R.id.djs_tv);
        button=findViewById(R.id.st_btn);
    }
定义AsyncTask,在doInBackgroud中做耗时操作;
在onProgressUpdate中得到进度设置控件进度

    class MyAsyncTask extends AsyncTask<Integer,Integer,String> {


        @Override
        protected String doInBackground(Integer... params) {

            for (int i=params[0];i>0;i--){

                try {
                    Thread.sleep(1000);
                    publishProgress(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "计时结束";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            textView.setText(""+values[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            textView.setText(s);
        }
    }

这里写图片描述

四、如何使用AsyncTask做进度条?

使用AsyncTask做倒计时要先定义AsyncTask,
在UI线程中启动AsyncTask
初始化控件
在doInBackgroud中做耗时操作
在onProgressUpdate中得到进度设置控件进度
最后根据result设置控件,onPostExecute方法里更新UI

代码如下:

xml中的代码很简单,只需要一个进度条和按钮即可

<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="com.test.project.handlerapplication.Activityfour">


  <SeekBar
      android:id="@+id/probar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />

    <Button
        android:id="@+id/start_Btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="开始下载"

        />

</LinearLayout>

java代码:

使用for循环做耗时操作
在onProgressUpdate中更新进度条
最后返回doInBackgroud的结果
package com.test.project.handlerapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;

public class Activityfour extends AppCompatActivity implements View.OnClickListener {


    private Button startBtn;
    private ProgressBar progressBar;

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


    }

    private void BindId() {
        progressBar=findViewById(R.id.probar);
        startBtn = findViewById(R.id.start_Btn);
        startBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.start_Btn:

                new MyAsyncTask().execute();
                startBtn.setText("正在下载");
                startBtn.setEnabled(false);
                break;

        }
    }

    class MyAsyncTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... integers) {

            for (int i=0; i <=10; i++) {
                try {
                    Thread.sleep(1000);
                    publishProgress(i*10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "下载结束";
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            startBtn.setText(s);
            startBtn.setEnabled(true);

        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);

        }
    }
}

这里写图片描述

五、Execute和executeonExecutor的区别?

使用execute方法启动时,下载任务是串行的,即必须等第一个下载完成后才能下载第二个;
使用executeOnExecutor启动时,可以进行并行执行,所有任务可以同步进行。
首先布置XML布局:
这里较第四点多了一个按钮和进度条


  <SeekBar
      android:id="@+id/probar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
  <SeekBar
      android:id="@+id/probar1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />

    <Button
        android:id="@+id/start_Btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="开始下载"

        />
    <Button
        android:id="@+id/start_Btn1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="开始下载"

        />
布置java代码:
由于使用executeOnExecutor方法是用来启动多任务执行的,
所以用switch语句来分辨在onProgressUpdate里的进度条更新
在doInBackground做耗时操作里,定义一个动态参数whichpro,并返回这个参数,
让onPostExecute接收,更新UI。
再在按钮的点击事件中,使用executeOnExecutor方法。

package com.test.project.handlerapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;

public class Activityfour extends AppCompatActivity implements View.OnClickListener {


    private Button startBtn;
    private Button startBtn1;

    private ProgressBar progressBar;
    private ProgressBar progressBar1;


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


    }

    private void BindId() {
        progressBar=findViewById(R.id.probar);
        startBtn = findViewById(R.id.start_Btn);
        startBtn1 = findViewById(R.id.start_Btn1);
        progressBar1=findViewById(R.id.probar1);
        startBtn.setOnClickListener(this);
        startBtn1.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.start_Btn:
                new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,1);
                startBtn.setText("正在下载");
                startBtn.setEnabled(false);
                break;
                case R.id.start_Btn1:
                new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,2);
                startBtn1.setText("正在下载");
                startBtn1.setEnabled(false);
                break;
        }
    }

    class MyAsyncTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected Integer doInBackground(Integer... integers) {

            int whichpro=integers[0];
            for (int i=0; i <=100; i++) {
                try {
                    Thread.sleep(1000);
                    publishProgress(i,whichpro);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return whichpro;
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            switch (values[1]){
                case 1:
                    progressBar.setProgress(values[0]);
                    break;
                case 2:
                    progressBar1.setProgress(values[0]);
                    break;
            }

        }
        @Override
        protected void onPostExecute(Integer s) {
            super.onPostExecute(s);
            switch (s){
                case 1 :
                    startBtn.setText("下载完成");
                    startBtn.setEnabled(true);
                    break;
                case 2:
                    startBtn1.setText("下载完成");
                    startBtn1.setEnabled(true);
                    break;
            } ;


        }

    }
}

注意:同一时间只能同时进行5个任务

这里写图片描述

最后,对于Handler和AsyncTask我更喜欢使用AsyncTask。

因为AsyncTask只需要了解三个参数,几个方法,代码量小,结构清晰。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值