Android targetSdkVersion and NetworkOnMainThread Exception

04/09/19 Permalink

I've just come across a runtime exception NetworkOnMainThreadException when upgrading the targetSdkVersion of an Android app. Basically what happens is Android will stop an app by refusing to load a class if it senses networking code is in the main app thread. I guess it's a way of preventing ANRs (App Not Responding).

To avoid having to redesign large portions of your app you can call this in onCreate:

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

From here. This will prevent NetworkOnMainThreadException from being thrown. Only do this if you're sure your network connection is reliable.

Share It: Digg | del.icio.us | Furl | reddit | Facebook | Yahoo! | Send to Phone

mobile-utopia.com | Feedback