Android異步操作AsyncTask

轉載請標明出處:http://blog.csdn.net/wu_wxc/article/details/53706042
本文出自【吳孝城的CSDN博客】

官網地址:https://developer.android.com/guide/components/processes-and-threads.html
創建繼承AsyncTask的類,三個參數
1、Params:執行任務時發送給任務的參數類型
2、Progress:在後臺計算時發佈的進度單位元的類型
3、Result:返回的結果類型
異步操作的執行:
調用:execute()
先執行:onPreExecute()
然後執行:doInBackground,會有一個返回值
再執行:onPostExecute。doInBackground的返回值在傳到這裏
要更新進度條,在doInBackground中調用publishProgress()
更新進度條的UI操作在onProgressUpdate中執行

下面以加載一張圖片爲例

這裏寫圖片描述
activity_main.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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="cn.wuxiaocheng.asynctask.MainActivity">
    <ImageView
        android:id="@+id/iv_down"
        android:layout_width="280dp"
        android:layout_height="280dp"
        android:layout_gravity="center_horizontal" />
    <ProgressBar
        android:visibility="gone"
        android:id="@+id/id_pb"
        style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="AsyncTask"
        android:textSize="30sp" />
</LinearLayout>

MainActivity.java

package cn.wuxiaocheng.asynctask;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
    private ImageView mImageView;
    private ProgressBar mProgressBar;
    private static final String url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView = (ImageView) findViewById(R.id.iv_down);
        mProgressBar = (ProgressBar) findViewById(R.id.id_pb);
    }
    public void click(View v) {
        new MyAsyncTask().execute(url);
    }
    class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
        // doInBackground 用於執行較爲耗時的操作
        // String... params表示可以傳入多個String類型參數
        @Override
        protected Bitmap doInBackground(String... params) {
            String url = params[0];
            Bitmap bitmap = null;
            InputStream in;
            try {
                URLConnection conn = new URL(url).openConnection();
                in = conn.getInputStream();
                //文件長度
                int fileLength = conn.getContentLength();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                int total = 0;
                while ((len = in.read(buffer)) != -1) {
                    total += len;
                    //調用publishProgress(),以在UI中執行onProgressUpdate
                    publishProgress((total * 100) / fileLength);
                    baos.write(buffer, 0, len);
                    byte[] result = baos.toByteArray();
                    // 用decodeByteArray將輸入流轉爲圖片
                    bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 將bitmap返回到onPostExecute
            return bitmap;
        }
        // 執行前,UI線程調用
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // 將進度條顯示出來
            mProgressBar.setVisibility(View.VISIBLE);
        }
        // doInBackground執行之後運行,UI線程調用
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            // 將進度條隱藏
            mProgressBar.setVisibility(View.GONE);
            // 設置顯示圖片
            mImageView.setImageBitmap(bitmap);
        }
        // 更新進度條
        @Override
        protected void onProgressUpdate(Integer... values) {
            mProgressBar.setProgress(values[0]);
        }
    }
}

AndroidManifest.xml中添加網絡訪問權限
運行結果
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章