安卓笔记之从网络下载图片
---恢复内容开始---
package com.example.picturecheck; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { static ImageView iv; static MainActivity ma; Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: iv.setImageBitmap((Bitmap) msg.obj); break; case 0: Toast.makeText(ma, "失败", 0).show(); break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView) findViewById(R.id.iv); ma=this; } public void click(View v){ //获取图片路径 final String path = "http://i01.pictn.sogoucdn.com/5002862e5fdd6bf7"; //写到SD卡上,这里没有判断SD是否可用,开发中必须判断 final File file = new File(getFilesDir(), "dog.png"); //判断如果文件存在,就直接拿来用,不用重新从网上下载 if(file.exists()){ Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); //把图片显示到imageView上 iv.setImageBitmap(bitmap); }else{ //开启子线程,因为主线程不能刷新UI Thread t = new Thread(){ //在run方法中执行操作 public void run() { try { //把网址封装成一个URL对象 URL url = new URL(path); //打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //获取请求方式,这里是GET请求 connection.setRequestMethod("GET"); //设置连接超时 connection.setConnectTimeout(8000); //设置读取超时 connection.setReadTimeout(8000); //可以写可以不写,因为下面获取响应码的时候就会建立连接 connection.connect(); //判断响应码是否为200 if (connection.getResponseCode()==200) { //获取连接流数据并返回一个InputStream流对象 InputStream is = connection.getInputStream(); //Bitmap bitmap =BitmapFactory.decodeStream(is); /*ImageView iv = (ImageView) findViewById(R.id.iv); iv.setImageBitmap(bitmap);*/ //获取一个FileOutputStream,用来把is流里的数据写到本地文件 ,下次想下载的时候就可以直接拿来用 //不用在重新从网上下载,相当把之前的缓存起来 FileOutputStream fos = new FileOutputStream(file); //下面就是读取流操作了 byte[] bys = new byte[1024]; int len =0; while((len=is.read(bys))!=-1){ fos.write(bys, 0, len); } //关流 fos.close(); //从file获取流数据并把它构造成一个位图对象(因为我们知道下载的就只是一张图片) Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); //主线程不能刷新UI,因此通过消息轮询器把消息队列里面的信息发送到主线程里面的handler来刷新UI Message msg = new Message(); //携带数据 msg.obj=bitmap; //用于判断是成功还是失败的消息 msg.what=1; //发送消息 handler.sendMessage(msg); } else{ //发送失败消息 Message msg = handler.obtainMessage(); msg.what=0; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; //启动子线程 t.start(); } } }
---恢复内容结束---