安卓下载网络图片显示进度

<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    >

  <Button
      android:id="@+id/download"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="DownLoadIMG"/>
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载进度为"/>

  <ProgressBar
      style="?android:attr/progressBarStyleHorizontal"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/progressBar" />

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</LinearLayout>


package com.baidu.downloadyellowimg;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private Button mdownload;
    private ProgressBar progressBar;
    private ImageView mimageView;
    private TextView textView;
    private String imageUrl="这里放图片URL";
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mdownload = (Button) findViewById(R.id.download);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        mimageView = (ImageView) findViewById(R.id.img);
        textView= (TextView) findViewById(R.id.textview);
        mdownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "开始下载文件", Toast.LENGTH_SHORT).show();
                new DownLoadTask().execute(imageUrl);
            }
        });
    }

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

        private long time;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            time=0;
            progressBar.setMax(100);
            progressBar.setProgress(0);
            textView.setText("开始下载");
            mdownload.setEnabled(false);
//            这个方法是清理ImageView  释放内存
            mimageView.setImageDrawable(new Drawable() {
                @Override
                public void draw(Canvas canvas) {

                }

                @Override
                public void setAlpha(int i) {

                }

                @Override
                public void setColorFilter(ColorFilter colorFilter) {

                }

                @Override
                public int getOpacity() {
                    return 0;
                }
            });
            if (bitmap!=null){
                bitmap.recycle();
                bitmap=null;
                System.gc();
            }
        }

        @Override
        protected String doInBackground(String... urls) {
            String imagePath=null;
            URL url;
            InputStream inputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                //获取URL
                url=new URL(urls[0]);
                //开启连接
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                //设置超时的时间,5000毫秒即5秒
                httpURLConnection.setConnectTimeout(5000);
                //设置获取图片的方式为GET
                httpURLConnection.setRequestMethod("GET");
                //响应码为200,则访问成功
                if (httpURLConnection.getResponseCode() == 200) {
                    //获取连接的输入流,这个输入流就是图片的输入流
                    inputStream = httpURLConnection.getInputStream();
                    //构建一个file对象用于存储图片
                    //这里我使用了一个生成目录的工具类,不清楚有没有可以直接生成文件目录的方法
                    String fileName=Util.getDefaultStoragePath(MainActivity.this)+File.separator+ System.currentTimeMillis()+".jpg";
                    File file = new File(fileName);
                    //获取输出流
                    fileOutputStream = new FileOutputStream(file);
                    //图片总共的长度
                    int total=httpURLConnection.getContentLength();
                    Log.e("xxxx","total:"+total);
                    //当前下载的长度
                    int length;
                    int length_count=0;
                    byte[] buffer = new byte[1024];
                    //将输入流写入到我们定义好的文件中
                    while ((length = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, length);
                        length_count=length_count+length;
                        Log.e("xxxx","length_count:"+length_count);
                        int progress= (int)((float)length_count/total*100);
                        publishProgress(progress);
                    }
                    //将缓冲刷入文件
                    fileOutputStream.flush();
                    imagePath=file.getAbsolutePath();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //在最后,将各种流关闭
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return imagePath;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            mdownload.setEnabled(true);
            if (s==null){
                textView.setText("下載失败");
                return;
            }
            bitmap= BitmapFactory.decodeFile(s);
            mimageView.setImageBitmap(bitmap);
            textView.setText("下載完成");
//            下载完成置为100
            progressBar.setProgress(100);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
//            保持两次更新时差500ms
            if ((System.currentTimeMillis()-time)>500){
                progressBar.setProgress(values[0]);
                textView.setText("已下载 "+ values[0]+"%");
                time=System.currentTimeMillis();
            }
        }
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值