现在Android下载网络图片的开源框架有很多,而且使用起来也非常方便,只要一两句代码就能解决问题,但是我们仿佛并不懂其里面的实现机制。
private String path = "http://7xlwlf.com1.z0.glb.clouddn.com/%40%2Ftt%2Fupload%2Fimages%2F(null)%2F2015%2F12%2F11%2F1449818979-1.jpg";
1.首先需要先获得一个连接,通过url.openConnection()方法来获得,设置这个连接的属性(比如请求的方式,连接超时,读取超时等)
url = new URL(path);
connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
2.请求成功可以获得所请求的图片资源的一个流,将这个流缓存到手机本地的文件中
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection
.getInputStream();
File file = new File(getCacheDir(),
"%40%2Ftt%2Fupload%2Fimages%2F(null)%2F2015%2F12%2F11%2F1449818979-1.jpg");
FileOutputStream out = new FileOutputStream(
file);
int len;
byte[] data = new byte[1024];
while ((len = is.read(data)) != -1) {
out.write(data, 0, len);
}
3.使用Handler机制来刷新UI
(1)Handler机制的简单理解
1)消息队列(MessageQueue):存储从Handler对象发送过来的消息
2)轮询器(Looper):不断从消息队列里去消息,发送给Handler对象处理
3)消息处理器(Handler):处理从Looper对象传送过来的消息
有些同学可能有点疑惑:Handler对象既是发送消息的,又是处理消息,为什么还要去MessageQueue转一下然后通过Looper对象来取直接处理了不久得了?我们可以设想一个场景:假如你是一个很有钱的老板,有很多人找你借钱,作为大老板的你当然不能当面答复他们,所以就让他们先去你的小秘那边登记一下,然后你一个一个在考虑到底借不借钱给某人。
(2)Handler对象的定义(对各类消息的处理)
private Handler mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
Bitmap bmp = (Bitmap) msg.obj;
iv.setImageBitmap(bmp);
break;
default:
break;
}
}
};
(3)Handler对象向消息队列发送消息
Message msg = new Message();
msg.what = 1;
msg.obj = bmp;
mhandler.sendMessage(msg);
4.是否有缓存判断,如果本地有缓存,直接加载本地文件(这里直接用的是File文件,当然Android提供了非常好用LruCache)
File file = new File(getCacheDir(),
"%40%2Ftt%2Fupload%2Fimages%2F(null)%2F2015%2F12%2F11%2F1449818979-1.jpg");
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(file
.getAbsolutePath());
iv.setImageBitmap(bmp);
}
5.完整代码
1)XML文件
<?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" >
<Button
android:id="@+id/btn_load"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载图片" />
<ImageView
android:id="@+id/iv"
android:layout_width="200dp"
android:layout_height="200dp" />
</LinearLayout>
2)java代码
package com.example.androidpictureloaddemo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.PublicKey;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private ImageView iv;
private Button btn;
private String path = "http://7xlwlf.com1.z0.glb.clouddn.com/%40%2Ftt%2Fupload%2Fimages%2F(null)%2F2015%2F12%2F11%2F1449818979-1.jpg";
private Handler mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
Bitmap bmp = (Bitmap) msg.obj;
iv.setImageBitmap(bmp);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.iv);
btn = (Button) findViewById(R.id.btn_load);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
File file = new File(getCacheDir(),
"%40%2Ftt%2Fupload%2Fimages%2F(null)%2F2015%2F12%2F11%2F1449818979-1.jpg");
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(file
.getAbsolutePath());
iv.setImageBitmap(bmp);
} else {
new Thread() {
@Override
public void run() {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(path);
connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection
.getInputStream();
File file = new File(getCacheDir(),
"%40%2Ftt%2Fupload%2Fimages%2F(null)%2F2015%2F12%2F11%2F1449818979-1.jpg");
FileOutputStream out = new FileOutputStream(
file);
int len;
byte[] data = new byte[1024];
while ((len = is.read(data)) != -1) {
out.write(data, 0, len);
}
Bitmap bmp = BitmapFactory.decodeFile(file
.getAbsolutePath());
Message msg = new Message();
msg.what = 1;
msg.obj = bmp;
mhandler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
});
}
}