最近学习安卓,今天看下安卓异步加载图片的坑。。。
//按钮的点击事件中,创建新线程,调用 getImage()方法获得图片回调,若不为空利用Handler发送消息更新UI
@Override
public void onClick(View v) {
final String url = editText.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
bitmap = getImage(url);
if (bitmap != null) {
Message msg = new Message();
msg.obj = bitmap;
msg.what = 1;
handler.sendMessage(msg);
}
}
}).start();
}
坑1
handler.sendMessage();
此方法一直爆红,查看API,发现有 android.os.Handler java.util.logging.Handler 两个包,导错了包。
坑2
private Bitmap getImage(String url) {
HttpURLConnection connection = null;
try {
URL myurl = new URL(url);
connection = (HttpURLConnection) myurl.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);//根据读数据创建位图对象
// Toast.makeText(this, "success" + responseCode, Toast.LENGTH_LONG).show();
return bitmap;
} else {
//Toast.makeText(this, "NONONO" + responseCode, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(this, "NONONO" + e, Toast.LENGTH_LONG).show();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
点击获取图片就崩溃,原因,
Toast.makeText(this, "success" + responseCode, Toast.LENGTH_LONG).show();
Toast 属于UI操作,放在了子线程导致崩溃。
总结下来就是,刷新UI必须在主线程,网络请求必须在子线程。安卓的包是坑。。。。