Android AsyncTask詳解


Android AsyncTask是一個輕量級的異步任務處理類

常見的使用步驟->創建一個繼承自AsyncTask類的異步任務處理類

 (AsyncTask<Params,Progress,Result>

Params啟動任務執行的輸入參數,比如一組URL

Progress后台任務執行的百分比

Result執行完任務后的返回結果)

 

 

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

    @Override
    protected String doInBackground(Integer... params) {
        //運行在工作線程
        //在onPreExecute方法執行完成后馬上執行,負責執行
        //耗時的后台處理任務,可調用publishProgress方法實
        //時更新任務進度
    }

    @Override
    protected void onPreExecute() {
        //運行在UI線程
        //在執行后台耗時操作之前,通常用於一些初始化操作,比如進度條顯示
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        //運行在UI線程
        //在doBackground方法中,每次調用publishProgress方法都會觸發該方法
    }
}

 

 

 

 

 

->在UI線程創建MyAsyncTask實例

->在UI線程中調用mAsyncTask.execute()

 一個完整的例子

MainActivity

 

package com.example.myfirstapp;

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 android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView txttitle;
    private ProgressBar pgbar;
    private Button btnupdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txttitle = (TextView)findViewById(R.id.txttitle);
        pgbar = (ProgressBar)findViewById(R.id.pgbar);
        btnupdate = (Button)findViewById(R.id.btnupdate);
        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyAsyncTask myTask = new MyAsyncTask(txttitle,pgbar);
                myTask.execute(1000);
            }
        });
    }
}

class DelayOperator {
    //延時操作,用來模擬下載
    public void delay()
    {
        try {
            Thread.sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();;
        }
    }
}

class MyAsyncTask extends AsyncTask<Integer,Integer,String>
{
    private TextView txt;
    private ProgressBar pgbar;

    public MyAsyncTask(TextView txt,ProgressBar pgbar)
    {
        super();
        this.txt = txt;
        this.pgbar = pgbar;
    }


    //該方法不運行在UI線程中,主要用於異步操作,通過調用publishProgress()方法
    //觸發onProgressUpdate對UI進行操作
    @Override
    protected String doInBackground(Integer... params) {
        DelayOperator dop = new DelayOperator();
        int i = 0;
        for (i = 10;i <= 100;i+=10)
        {
            dop.delay();
            publishProgress(i);
        }
        //i + params[0].intValue()
        return  "";
    }

    //該方法運行在UI線程中,可對UI控件進行設置
    @Override
    protected void onPreExecute() {
        txt.setText("開始執行異步線程~");
    }


    //在doBackground方法中,每次調用publishProgress方法都會觸發該方法
    //運行在UI線程中,可對UI控件進行操作


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

 

布局代碼

activity_main

<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=".MyActivity">
    <TextView
        android:id="@+id/txttitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <!--設置一個進度條,並且設置為水平方向-->
    <ProgressBar
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/pgbar"
        style="?android:attr/progressBarStyleHorizontal"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnupdate"
        android:text="更新progressBar"/>
</LinearLayout>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM