Monday, 21 October 2013

StrictMode in Android

Within an Android application you should avoid performing long running operations on the user interface thread. This includes file and network access.

StrictMode allows to setup policies in your application to avoid doing incorrect things. As of Android 3.0 (Honeycomb) StrictMode is configured to crash with a NetworkOnMainThreadException exception, if network is accessed in the user interface thread.

While you should do network access in a background thread, this code will avoid this to allow the user to learn network access independent from background processing.

If you are targeting Android 3.0 or higher, you can turn this check off via the following code at the beginning of your onCreate() method of your activity.

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