【Android-多线程】针对AsyncTask(三参数四步骤)的简单项目(附源码)

AsycnTask 的应用

https://developer.android.google.cn/reference/android/os/AsyncTask?hl=en.
根据官方的文档显示,这个对象class在api 30 中已经被废弃⚠️,不过还是需要好好学习接触一下;多线程编程一直算是我的一大短板。

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

三参数,四步骤

三参数:

参数,过程,结果;这个也好理解使用一般在线程工作的基本流程都是如这三个参数所命名一样,开始到结束。
在一个特殊的情况下,不需要参数的时候,例如进行固定的线程操作的时候可以采用void作为参数代替。这里的参数采用的是泛型。

四步骤

onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

在正式异步工作前应该要怎么做!

  • doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress…) step.

重点;在移步多线程进行一些需要耗时的操作,在这里可以将所需的Progress的相关数据通过publishProgreess传递到下一个方法onProgressUpdate

  • onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress…). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

在这里可以进行UI的变动,UI变动是牵扯到主线程的!

  • onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a para

整个的运行结果,在结束后可以在这个方法中进行相关UI的操作。

示例代码

mainActivity中

package com.chris.asynctask;

import static java.lang.Thread.sleep;

import androidx.appcompat.app.AppCompatActivity;

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

/**
 * 这个对象主要是用来学习检验AsyncTask的使用
 * 简单和ui交互,牢记三参数四步骤
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button;
    private TextView text;
    private ProgressBar progressBar;
    private Button cancel;

    // 测试对象
    MyAsyncTask MyAsyncTask = new MyAsyncTask();

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

    private void initView() {
        button = findViewById(R.id.button);
        text = findViewById(R.id.text);
        progressBar = findViewById(R.id.progress_bar);
        cancel = findViewById(R.id.cancel);
        cancel.setOnClickListener(this);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.button:
                MyAsyncTask.execute();
                break;
            case R.id.cancel:
                MyAsyncTask.cancel(true);
                break;
        }
    }

    private class MyAsyncTask extends AsyncTask<String,Integer,String>{
        //运行前
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            text.setText("Starting!");
        }
        //最重要的,在后台进行的相关操作
        @Override
        protected String doInBackground(String... strings) {
            int i = 0;
            while(i<100){
                i++;
                try {
                    sleep(100);
                    publishProgress(i);
                    Log.d("Test",String.valueOf(i));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "finished!";
        }

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

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

        @Override
        protected void onCancelled(String s) {
            super.onCancelled(s);
            text.setText("Cancelled!");
        }
    }
}

在应用视图的xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:gravity="center"
    tools:context="MainActivity">

    <Button
        android:layout_centerInParent="true"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点我加载"/>

    <TextView
        android:id="@+id/text"
        android:layout_below="@+id/button"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="还没开始加载!" />

    <ProgressBar
        android:layout_below="@+id/text"
        android:id="@+id/progress_bar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:progress="0"
        android:max="100"
        style="?android:attr/progressBarStyleHorizontal"/>

    <Button
        android:layout_below="@+id/progress_bar"
        android:layout_centerInParent="true"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="cancel"/>
</RelativeLayout>

点击加载进行后台线程运行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值