通过URL获取网络图片报NetworkOnMainThreadException
首先通过url加载网络图片的方法为:
public static Bitmap getBitMBitmap(String urlpath) {
Bitmap map = null;
try {
URL url = new URL(urlpath);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in;
in = conn.getInputStream();
map = BitmapFactory.decodeStream(in);
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
但是出现了崩溃,查看日志,看到报错异常:NetworkOnMainThreadException;
突然醒悟过来,就是Android为了防止在主线程进行超时的操作类似于网络请求而导致的页面卡死现象而报异常
那么有两种办法解决:
1.强制执行:
就在OnCreate方法里加上一下代码:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
2.第二种方法就是使用Thread去操作。在Runnable中做HTTP请求,不用阻塞UI线程。
在onCreate方法里:
new Thread(runnable).start;
然后就是:
Runnable runnable = new Runnable() {
@Override
public void run() {
Message msg = new Message();
bitmaps = getBitMBitmap(piclink);
Bundle bundle = new Bundle();
bundle.putParcelable("bitmaps",bitmaps);
msg.setData(bundle);
handler.sendMessage(msg);
}
};
public Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
Bitmap bitmapss = data.getParcelable("bitmaps");
Log.i("請求結果"+bitmapss);
}
};