Site icon Dipin Krishna

android.os.NetworkOnMainThreadException due to StrictMode.ThreadPolicy

android

StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11, which in short, does not allow network operation (eg: HttpClient and HttpUrlConnection) get executed on UI thread. if you do this, you get NetworkOnMainThreadException.

You can easily solve this error. The recommended way of solving this is by Using an AsyncTask so that the network request does not block the UI thread.

Alternatively, you can override this thread policy by adding the below code into your main activity’s onCreate() method.

if (android.os.Build.VERSION.SDK_INT > 9) {
	StrictMode.ThreadPolicy policy = 
		new StrictMode.ThreadPolicy.Builder().permitAll().build();
	StrictMode.setThreadPolicy(policy);
}

Exit mobile version