以前做项目的时候经常会碰到问题,现在特写一篇关于这方面的问题的解答:
解决android.os.NetworkOnMainThreadException
Caused by: android.os.NetworkOnMainThreadException
解决方法有两种方法:
1、直接忽视,强制使用(强烈不推荐,但是修改简单)
在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码
1 2 3 4 |
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
|
2、使用Thread、Runnable、Handler (推荐使用)
在Runnable中做HTTP请求,不用阻塞UI线程~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.share_mblog_view);
new Thread(runnable).start();
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString("value");
Log.i("mylog","请求结果-->" + val);
}
}
Runnable runnable = new Runnable(){
@Override
public void run() {
//
// TODO: http request.
//
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value","请求结果");
msg.setData(data);
handler.sendMessage(msg);
}
}
|
原文作者: iceskysl