android.os.NetworkOnMainThreadException 解决办法
产生的原因:
在4.0之后在主线程里面执行Http请求都会报这个错,也许是怕Http请求时间太长造成程序假死的情况
解决办法:
1.在发起Http请求的Activity里面的onCreate函数里面添加如下代码
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
2.使用Thread、Runnable、Handler这三个类
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() { Message msg = new Message(); Bundle data = new Bundle(); data.putString("value","请求结果"); msg.setData(data); handler.sendMessage(msg); } }
相关推荐
86193952 2020-10-27
83911535 2020-11-13
87403867 2020-09-24
88550291 2020-08-21
88407710 2020-08-17
xvzhengyang 2020-07-30
knightwatch 2020-07-19
knightwatch 2020-07-04
hygbuaa 2020-06-26
sicceer 2020-06-21
88407013 2020-06-16
86447405 2020-06-16
zkwgpp 2020-06-14
DumbbellYang 2020-06-11
标题无所谓 2020-06-10
hygbuaa 2020-06-10
zkwgpp 2020-06-02
zhaolisha 2020-05-31