一次测试的时候,直接在MainActivity的Oncreate方法中,也就是主线程中进行了http请求的发起。
现象
报错如下:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxx.xxx, PID: 32523
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxx.xxx/com.xxxx.xxx.ui.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3271)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3410)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2017)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7397)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
原因
因为Http请求写在了主线程里,在4.0之后在主线程里面执行Http请求都会报这个错
解决方法
新开一个线程,直接new一个Thread或者如下 都可以解决
App.getInstance().getThreadPool().execute(()->{
});
转载务必注明出处:程序员潇然,疯狂的字节X,https://crazybytex.com/thread-142-1-1.html |