栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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;


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{
        //运行前
        @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中




    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/678080.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号