为什么加载不出图片?
public class HttpThread extends Thread {
private String url;
private Handler handler;
private ImageView imageView;
public HttpThread( String url,Handler handler,ImageView imageView){
this.url = url;
this.handler = handler;
this.imageView = imageView;
}
@Override
public void run() {
//创建URL资源标识符,用来标识唯一的网址信息,传递网址参数
try {
URL httpUrl = new URL(url);
//通过URL去打开一个HttpURLConnection
try {
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
//设置请求超时等待的时间
conn.setReadTimeout(5000);
//设置网络请求的方式
conn.setRequestMethod("GET");
//设置可以得到输入流
conn.setDoInput(true);
//获取输入流
InputStream inputStream = conn.getInputStream();
/**
* 将图片下载到本地
*/
FileOutputStream fileOutputStream = null;
File file = null;
String name = String.valueOf(System.currentTimeMillis());
//判断SD卡是否能加载(存在),并且是否具有读写权限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//获取SD卡根目录
File parent = Environment.getExternalStorageDirectory();
Log.e("dd",""+parent);
//创建文件名,参数1:夫目录,参数2:文件名
file = new File(parent,name);
//FileOutputStream文件输出流,用于将文件写入File
fileOutputStream = new FileOutputStream(file);
}
//创建缓冲区,存储数据用的
final byte[] b = new byte[2*1024];
int len;
//如果SD卡不等于null
if(null != fileOutputStream){
//lengh不等于-1认为一直有数据
while ((len = inputStream.read(b))!=-1){
//往文件中写数据
fileOutputStream.write(b,0,len);
}
}
//通过Handler去更新UI,读取图片
final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}