后台打印“从网络获取图片” 但是在ImageView的UI界面未显示图片
如图
代码:
public class MainActivity extends Activity {
Handler handler = new Handler(){
//只要消息列队里面有消息,此方法就调用
public void handleMessage(android.os.Message msg) {
//8,显示
ImageView iv = (ImageView) findViewById(R.id.iv);
//把图片设置进ListView
iv.setImageBitmap((Bitmap) msg.obj);
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
final String path = "http://192.168.0.102:8080/mm.jpg";
//判断缓存是否存在
final File file = new File(getCacheDir(), getFileName(path));
if(file.exists()){
System.out.println("从缓存中读取图片");
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bm);
}else{
System.out.println("从网络获取图片");
Thread t = new Thread(){
@Override
public void run() {
//请求网址,获取图片
//1,确认网址
try {
//2,获取URL对象
URL url = new URL(path);
//3,获取连接对象,此时还未建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//4,初始化连接对象
conn.setRequestMethod("GET"); //设置请求方法
conn.setReadTimeout(5000); //设置读取超时
conn.setConnectTimeout(5000); //设置连接超时
//5,与服务器建立连接
conn.connect();
//判断是否请求成功,通过请求码对比
if(conn.getResponseCode() == 200){
//6,拿到服务器返回的流,客户请求的数据就保存在流中
InputStream is = conn.getInputStream();
//7,开始文件输出流,把读取的字节写到本地
FileOutputStream fos = new FileOutputStream(file);
//从流中读数据的同时将数据写到内存
int len = 0;
byte[]b = new byte[1024];
while((len = is.read()) != -1){
fos.write(b, 0, len);
}
fos.close();
//将图片显示到屏幕
//通过图片的绝对路径构造出一个Bitmap对象
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
//创建消息对象
Message msg = new Message();
//将bm放入消息中
msg.obj = bm;
//子线程向列队消息发送消息
handler.sendMessage(msg);
}else{
Looper.prepare();
Toast.makeText(MainActivity.this, "请求失败", 0).show();
Looper.loop();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
}
public String getFileName(String path){
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
}