Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick fix for NetworkOnMainThreadException

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

like image 437
Alex F Avatar asked Sep 29 '12 07:09

Alex F


People also ask

How can I fix Android OS NetworkOnMainThreadException '?

This example demonstrates how do I fix the android. os. NetworkOnMainThreadException. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

How do you solve NetworkOnMainThreadException?

Simply extend AsyncTask and implement the doInBackground() method to perform the work.

What is a network on main thread exception?

android.os.NetworkOnMainThreadException. The exception that is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher.


1 Answers

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);
like image 99
Infinity Avatar answered Oct 20 '22 08:10

Infinity