Quick fix for NetworkOnMainThreadException

I need to run a third-party open source program that raises a NetworkOnMainThreadException. According to the SDK link, this is done only for applications targeting the Honeycomb SDK or higher. Applications targeting earlier versions of the SDK can create networks in their main event loop threads.

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

     android: targetSdkVersion = "15"

in

     android: targetSdkVersion = "10"

However, this does not help, and the program throws a NetworkOnMainThreadException anyway. How can I make this work? I am trying to run a program on the Google API Android emulation (level 16).

+8
android networkonmainthread network-programming
source share
3 answers

You can change it to:

android:targetSdkVersion="9" 

API 10 is honeycomb and 9 is gingerbread. This behavior is observed only in API 10 and higher.

However, I would advise doing this. Instead, you should move any lengthy operations or operations with the possibility of long-term operation in the background thread, such as AsyncTask .

You can also try disabling Strict Mode using:

  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); 
+20
source share

Perform a network task in your user interface thread. The best way to do networking is to use AsyncTask or just create another thread. However, if you need a quick and dirty way to get rid of the error; you can also use this

 ThreadPolicy tp = ThreadPolicy.LAX; StrictMode.setThreadPolicy(tp); 
+3
source share

This is not a solution, you just say that tatelar sleep and sit! android decides not to allow you to perform network operations in the main thread (user interface thread) because of the β€œstops” that this operation can perform (ui answer responds). So when I read, they say that you are not shooting at your foot, and you will find a way to do this.

solution: split thread, or Async ...

0
source share

All Articles