今天在子线程中使用glide加载本地图片,失效!
分析:
glide显示图片应该放在主线程,耗时操作放在子线程!
new Thread(){
@Override
public void run() {
//需要在子线程中处理的逻辑
try {
URL httpUrl = new URL("https://hailabtest.haierbiomedical.com/profile/"+userInfo.getAvatar());
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
saveFile("123",btImg);
Log.e("wy", "91saveFile: "+filepath );
String s = filepath;
Bitmap bitmap = BitmapFactory.decodeFile(s);
// ivIcon.setImageBitmap(bitmap);
runOnUiThread(new Runnable() {
@Override
public void run() {
//加载图片
File file = new File(getExternalFilesDir(null), "123.jpg");
Glide.with(UserInfoActivity.this).load(file)
.apply(com.bumptech.glide.request.RequestOptions.circleCropTransform())
.into(ivIcon);
}
});
//加载图片
// File file = new File(getExternalFilesDir(null), "123.jpg");
// Glide.with(UserInfoActivity.this).load(file).into(ivIcon);
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
用到的方法
/**
* 从输入流中获取数据
* @param inStream 输入流
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
public void saveFile(String filename, byte[] data)throws Exception{
if(data != null){
// filepath = Environment.getDataDirectory().getPath()+"/" + filename+".jpg";
filepath = getExternalFilesDir(null)+"/" + filename+".jpg";
// Log.e("wy", "saveFile: "+filepath );
File file = new File(filepath);
if(file.exists()){
file.delete();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(data,0,data.length);
fos.flush();
fos.close();
}
}