网络图片查看器
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.getResponseCode();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
ImageView iv = (ImageView) findViewById(R.id.iv)
iv.setImageBitmap(bm)
主线程不能被阻塞
- 在Android中,主线程被阻塞会导致应用不能刷新ui界面,不能响应用户操作,用户体验将非常差
- 主线程阻塞时间过长,系统会抛出ANR异常
- ANR:Application Not Response;应用无响应
- 任何耗时操作都不可以写在主线程
- 因为网络交互属于耗时操作,如果网速很慢,代码会阻塞,所以网络交互的代码不能运行在主线程
只有主线程能刷新ui
- 刷新ui的代码只能运行在主线程,运行在子线程是没有任何效果的
- 如果需要在子线程中刷新ui,使用消息队列机制
消息队列
- Looper一旦发现Message Queue中有消息,就会把消息取出,然后把消息扔给Handler对象,Handler会调用自己的handleMessage方法来处理这条消息
- handleMessage方法运行在主线程
- 主线程创建时,消息队列和轮询器对象就会被创建,但是消息处理器对象,需要使用时,自行创建
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
}
};
Message msg = new Message();
msg.obj = bm;
msg.what = 1;
handler.sendMessage(msg);
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
//如果是1,说明属于请求成功的消息
case 1:
ImageView iv = (ImageView) findViewById(R.id.iv)
Bitmap bm = (Bitmap) msg.obj
iv.setImageBitmap(bm)
break
case 2:
Toast.makeText(MainActivity.this, "请求失败", 0).show()
break
}
}
加入缓存图片的功能
- 把服务器返回的流里的数据读取出来,然后通过文件输入流写至本地文件
InputStream is = conn.getInputStream();
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 bm = BitmapFactory.decodeFile(file.getAbsolutePath())
- 每次发送请求前检测一下在缓存中是否存在同名图片,如果存在,则读取缓存
获取开源代码的网站
- code.google.com
- github.com
- 在github搜索smart-image-view
- 下载开源项目smart-image-view
- 使用自定义组件时,标签名字要写包名
<com.loopj.android.image.SmartImageView/>
SmartImageView siv = (SmartImageView) findViewById(R.id.siv)
siv.setImageUrl("http://192.168.1.102:8080/dd.jpg")