AsyncTask下载图片、显示进度

转载请注明出处AsyncTask下载图片、显示进度_Mr_Leixiansheng的博客-CSDN博客

为何要引入AsyncTask?

在Android程序开始运行的时候会单独启动一个进程,默认情况下所有这个程序操作都在这个进程中进行。一个Android程序默认情况下只有一个进程,但一个进程中可以有多个线程。

在这些线程中,有一个线程叫做UI线程(也叫Main Thread),除了UI线程外的线程都叫子线程(Worker Thread)。UI线程主要负责控制UI界面的显示、更新、交互等。因此,UI线程中的操作延迟越短越好(流畅)。把一些耗时的操作(网络请求、数据库操作、逻辑计算等)放到单独的线程,可以避免主线程阻塞。

Android给我们提供了一种轻量级的异步任务类AsyncTask。该类中实现异步操作,并提供接口反馈当前异步执行结果及进度,这些接口中有直接运行在主线程中的(如 onPostExecute,onPreExecute等)。

内容:

1、异步下载图片更新UI

2、将下载进度显示到进度条

步骤:

1、继承并重写AsyncTask类,定义好需要传递的参数

2、所有耗时操作都放到 doInBackground中实现(例如:下载),onPostExecute中更新

3、主程序中实现功能 MyAsyncTask task = new MyAsyncTask();  task.execute();

代码如下:

1、主程序和主界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_1"
        android:text="下载图片"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <Button
        android:id="@+id/btn_2"
        android:text="带进度下载"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
package com.example.leixiansheng.myasynctask;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btn1;
    private Button btn2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1 = (Button) findViewById(R.id.btn_1);
        btn2 = (Button) findViewById(R.id.btn_2);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ImageLoade.class);
                startActivity(intent);
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, Progress.class));

            }
        });
    }
}

2、异步下载图片程序及界面

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:padding="16dp">

    <ImageView
        android:id="@+id/image_view"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <!-- GONE 可优化布局-->
    <ProgressBar
        android:id="@+id/pb"
        android:visibility="gone"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
package com.example.leixiansheng.myasynctask;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.io.InputStream;
import java.net.URLConnection;

/**
 * Created by Leixiansheng on 2017/3/21.
 */

public class ImageLoade extends AppCompatActivity {

    private ImageView imageView;
    private ProgressBar progressBar;

    private static String URL = "http://img.qqbody.com/uploads/allimg/201411/30-191145_774.jpg";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.imageloade);

        imageView = (ImageView) findViewById(R.id.image_view);
        progressBar = (ProgressBar) findViewById(R.id.pb);
        new MyAsyncTask().execute(URL);
    }

    class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            progressBar.setVisibility(View.GONE);
            imageView.setImageBitmap(bitmap);
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            //获取传递参数
            String url = strings[0];
            Bitmap bitmap = null;
            URLConnection connection;
            InputStream is;
            try {
                connection = new URL(url).openConnection();
                is = connection.getInputStream();
                //读取流
                BufferedInputStream bis = new BufferedInputStream(is);
                //模拟睡眠
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                bitmap = BitmapFactory.decodeStream(bis);
                is.close();
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
    }
}

3、获取异步下载进度(模拟下载)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ProgressBar
        android:id="@+id/progress"
        style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
package com.example.leixiansheng.myasynctask;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;

/**
 * Created by Leixiansheng on 2017/3/21.
 */

public class Progress extends AppCompatActivity {

    private ProgressBar progressBar;
    private MyAsyncTask task;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.progress);

        progressBar = (ProgressBar) findViewById(R.id.progress);
        task = new MyAsyncTask();
        //开启异步
        task.execute();

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
            //  没有取消线程
            task.cancel(true);
        }
    }

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

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (isCancelled()) {
                return;
            }
            //下载进度显示到进度条
            progressBar.setProgress(values[0]);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            //模拟下载
            for (int i = 0; i < 100; i++) {
                if (isCancelled()) {
                    break;
                }
                publishProgress(i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }

}

4、注册活动、声明权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.leixiansheng.myasynctask">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ImageLoade"/>
        <activity android:name=".Progress"/>
    </application>

</manifest>

Kotlin写法: 

class ImageLoadeActivity : AppCompatActivity() {

    private val mUrl = "http://img.qqbody.com/uploads/allimg/201411/30-191145_774.jpg"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.pb)

        MyAsyncTask().execute(mUrl)
    }

    private inner class MyAsyncTask: AsyncTask<String, Void, Bitmap>() {

        override fun onPreExecute() {
            super.onPreExecute()
            pb.visibility = View.VISIBLE
        }

         override fun doInBackground(vararg params: String?): Bitmap? {
             var bitmap: Bitmap? = null

             try {
                 val url = params[0];
                 val connection: URLConnection = URL(url).openConnection()
                 val inputSteam: InputStream

                 inputSteam = connection.getInputStream()
                 val bufferedInputStream = BufferedInputStream(inputSteam)
                 Thread.sleep(1000)
                 bitmap = BitmapFactory.decodeStream(bufferedInputStream)
             } catch (e: Exception) {
                 e.printStackTrace()
             }
             return bitmap
         }

        override fun onPostExecute(result: Bitmap?) {
            super.onPostExecute(result)
            image_view.setImageBitmap(result)
            pb.visibility = View.GONE
        }
     }
}
class ProgressActivity : AppCompatActivity() {

    private val task = MyAsyncTask()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.progress)
        task.execute()
    }

    override fun onPause() {
        super.onPause()
        if (task.getStatus() == AsyncTask.Status.RUNNING) {
            //  没有取消线程
            task.cancel(true);
        }
    }

    private inner class MyAsyncTask: AsyncTask<Void, Int, Void>() {

        override fun onProgressUpdate(vararg values: Int?) {
            super.onProgressUpdate(*values)
            if (isCancelled()) {
                return;
            }
            progress.progress = values[0] ?: 0
        }

        override fun doInBackground(vararg params: Void?): Void? {
            try {//模拟下载
                for (i in 0..100){
                    if (isCancelled()) {
                        break;
                    }
                    publishProgress(i);
                    Thread.sleep(100);
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return null
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值