标签:
从网络中下载的图片放到本地,然后在用bitmap获取本地的图片,通过消息队列发送到主线程去执行,
最后一步我们要判断一下,如果这个文件存在,直接从本地来读取,如果不存在就从网络中获取。
package com.example.getimg; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Message; import android.view.View; import android.widget.ImageView; 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 MyActivity extends Activity { /** * Called when the activity is first created. */ private ImageView img; android.os.Handler handler = new android.os.Handler(){ //用handlemessage来更新ui线程 @Override public void handleMessage(Message msg) { switch (msg.what){ case 0: img.setImageBitmap((Bitmap) msg.obj); break; case 1: Toast.makeText(MyActivity.this,"没有响应",Toast.LENGTH_SHORT).show(); break; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); img = (ImageView) findViewById(R.id.img); findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() { final String path = "http://192.168.21.1:8080/ok/point_one.png"; final File file = new File(getCacheDir(),getFeilName(path)); @Override public void onClick(View view) { //判断缓存是否存在,因为这个是在主线程里,可以直接设置 if(file.exists()){ Toast.makeText(MyActivity.this,"从缓存读取",Toast.LENGTH_SHORT).show(); Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); img.setImageBitmap(bitmap); } else{ System.out.print("从网络中读取"); //创建子线程来链接网络,并且使用get方法下载图片 Thread thread = new Thread(){ @Override public void run() { { //uri try { URL url = new URL(path); //获得链接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置参数 conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //正式链接 conn.connect(); if(conn.getResponseCode()==200){ InputStream is = conn.getInputStream(); //把InputStream通过bitmap转化成图片 // Bitmap bitmap = BitmapFactory.decodeStream(is); //把从网络中读取的图片放到缓存中 FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024]; int len = 0; while((len=is.read(b))!=-1){ fos.write(b,0,len); } //从本地读取bitmap Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); //创建消息对象 Message msg = new Message(); msg.what = 0; //传递bitmap所需要的数据,如果是多个数据可以传递数组啊! msg.obj = bitmap; //给消息队列发送消息 handler.sendMessage(msg); }else{ //一般不会new,这样会节省内存 Message msg = handler.obtainMessage(); //传递参数为了判断是谁发送的message msg.what = 1; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } } }; thread.start(); } } }); } private String getFeilName(String path){ int index = path.lastIndexOf("/"); return path.substring(index + 1); } }
标签:
原文地址:http://www.cnblogs.com/84126858jmz/p/4929665.html