使用异步任务-AsyncTask下载远程图片

AsyncTask是“Handler+多线程”的综合体。使用它来完成非UI线程操作更为方便。
这里,我下载的是远程的图片,并将它渲染在手机界面中。

布局如下:

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

    <ProgressBar
        android:id="@+id/pb"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="invisible" />

    <Button
        android:id="@+id/btn_test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerInside" />
</LinearLayout>

主界面如下:

package com.jackie.app_test;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

/**
 * Created by Administrator on 2016/11/6.
 */
public class TestActivity2 extends Activity {

    private Button button;
    private ProgressBar progressBar;
    private ImageView imageView;
    private MyAsyncTask myAsyncTask;


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

        button = (Button) findViewById(R.id.btn_test);
        progressBar = (ProgressBar) findViewById(R.id.pb);
        imageView = (ImageView) findViewById(R.id.iv);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String src = "http://pic1.win4000.com/wallpaper/2/568f86fcb6d7a.jpg";
                myAsyncTask = new MyAsyncTask();
                myAsyncTask.execute(src);
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        myAsyncTask.onCancelled();
    }

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

        //UI线程中执行。在子线程之前调用,一般用来完成UI组件的准备操作。
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setMax(100);
            progressBar.setVisibility(View.VISIBLE);
        }

        //异步任务的抽象方法。在子线程中运行。
        @Override
        protected Bitmap doInBackground(String... params) {
            URL url = null;
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            File destFile = new File(Environment.getExternalStorageDirectory().getPath(),
                    System.currentTimeMillis() + ".jpg");
            try {
                url = new URL(params[0]);
                bis = new BufferedInputStream(url.openStream());
                int total = bis.available();
                bos = new BufferedOutputStream(new FileOutputStream(destFile));

                byte[] bytes = new byte[1024];
                int currSize = 0;
                for (int count = 0; (count = bis.read(bytes)) != -1; ) {
                    bos.write(bytes, 0, count);
                    currSize += count;
                    int progress = (int) (currSize / total) * 100;
                    publishProgress(progress);
                }
                bos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(destFile.getPath(), opts);

            //原始图片的宽高
            int bitmap_w = opts.outWidth;
            int bitmap_h = opts.outHeight;

            //获取屏幕信息
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            display.getMetrics(displayMetrics);
            //获取屏幕宽高
            int sw = displayMetrics.widthPixels;
            int sh = displayMetrics.heightPixels;

            //计算各宽高比例
            int sampleW = bitmap_w / sw;
            int sampleH = bitmap_h / sh;

            //计算采样因子
            int sampleSize = (sampleH > sampleW) ? sampleH : sampleW;

            opts.inJustDecodeBounds = false;
            opts.inSampleSize = sampleSize;
            Bitmap bitmap_later = BitmapFactory.decodeFile(destFile.getPath(), opts);

            return bitmap_later;
        }

        //在UI线程中执行,更新进度值。一般是在doInBackground()中的publishProgress()方法被调用后执行。
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Integer progressValues = values[0];
            progressBar.setProgress(progressValues);
        }

        //在UI线程中执行,在子线程之后调用。一般是对UI组件的后期处理。
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            imageView.setImageBitmap(bitmap);
            progressBar.setVisibility(View.INVISIBLE);
        }

        //在UI线程中执行。当取消这个后台线程时被调用。
        @Override
        protected void onCancelled() {
            super.onCancelled();
            progressBar.setProgress(0);
            progressBar.setVisibility(View.INVISIBLE);
        }
    }

}

不要忘了加权限:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值