安卓下载网络图片显示进度
2016-07-10 11:00
471 查看
<?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(); } } } }
相关文章推荐
- Android网络知识总结
- 关于浏览器和网络的20项须知-HTML、JAVASCRIPT、CSS...
- 【网络基础】Mime Type
- 计算机网络结构
- 抓包工具charles for mac使用
- P2P(对等网络)、 PT 下载与 BT 下载
- MC-LAG及RTG在数据中心网络中的应用
- http://www.scaperow.com/323
- tinyhttpd源码详解 转载自 技术菌的blog
- CSP考试 2015年03月第4题 网络延时 C语言实现
- 卷积神经网络
- 卷积神经网络
- HTTP协议解析
- ping工作原理
- 网络安全书籍
- 虚拟机网络不通:
- python GTK+3 使用soup做一个http服务器
- 我见过的最脑残也是最好懂的人工神经网络算法教程
- ---servlet(三)HttpServletResponse对象和 HttpServletRequest对象
- 网络: SSL/TLS 握手优化详解(收藏已久,特推)