Quick fix for NetworkOnMainThreadException

天大地大妈咪最大 提交于 2019-11-26 17:13:42

问题


I need to execute third-party open source program, which throws NetworkOnMainThreadException. According to SDK reference, this is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads.

On the first stage I just want to run the program, without changing the source. So, I changed the line in AndroidManifesr.xml from:

    android:targetSdkVersion="15"

to:

    android:targetSdkVersion="10"

However, this doesn't help, and program still throws NetworkOnMainThreadException. How can I make this to work? I am trying to execute the program on Android Emulation Google APIs (level 16).


回答1:


You could change it to:

android:targetSdkVersion="9"

API 10 corresponds to honeycomb, while 9 is gingerbread. This behavior is only seen in APIs 10 and above.

However, I would advise against this. Instead, you should move any long running operations, or operations with the possibility of running for long into a background thread, like an AsyncTask.

You could also try to set Strict Mode off using:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);



回答2:


You are performing network task on your UI Thread. The best way to perform network operation is to use AsyncTask or simply create another thread. However, if you want a quick and dirty way to get rid of the error; you can also use this

ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);



回答3:


These are not solutions, you Just tell the tutelar to sleep and sill!!! the android decide not to let you make network operations in the main thread (UI thread), because of the "halts" that these operation can make (the ui stop respond). So, as I read, they tell you to not shoot your leg, and you find the way to do!!!

the solution : separated thread, Or Async ...



来源:https://stackoverflow.com/questions/12650921/quick-fix-for-networkonmainthreadexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!