Quick fix for NetworkOnMainThreadException

Alex F picture Alex F · Sep 29, 2012 · Viewed 20.2k times · Source

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).

Answer

Raghav Sood picture Raghav Sood · Sep 29, 2012

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);