Android异步操作AsyncTask

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wu_wxc/article/details/53706042

转载请标明出处: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中添加网络访问权限
运行结果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/wu_wxc/article/details/53706042