If you try to run network operations in the main activity which is rendering the UI components on Android, you get the android.os.networkonmainthreadexception in your application. The result will be that you won’t be able to execute network operations.

It is now officially recommended to use an AsyncTask so that the UI doesn’t get blocked till the response is received from the remote device/machine. This exception makes sense because the OS and user won’t want themselves to be blocked with one application only.

So the solution for android.os.networkonmainthreadexception is either use AsyncTask or disable StrictMode. Both these approached are described below:

1) Using AsyncTask in Android

An AsyncTask runs in a separate thread than the main thread, it allows the UI thread to be non-blocking which is recommended for all Android applications. As described above, if you don’t implement an AsyncTask for network operations, an exception android.os.networkonmainthreadexception is throws from the application by default.

The following source-code shows how to create an AsyncTask and call it from UI thread:

public class TaskExample extends AsyncTask {

	protected Integer doInBackground(String... url) {
       		URL url = new URL(myurl);
        	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        	conn.setReadTimeout(10000 /* milliseconds */);
        	conn.setConnectTimeout(15000 /* milliseconds */);
        	conn.setRequestMethod("GET");
        	conn.setDoInput(true);
        	// Starts the query
        	conn.connect();
        	
        	int response = conn.getResponseCode();
		return new Integer(response);
	}
}

The only requirement is that the implementation task should override the method:
protected Object doInBackground(Object… url) {…}

We can easily replace Object in the above code with any other Java class. The method is accepting variable arguments and hence it is up to the developer to pass as many arguments as required.

In order to invoke the AsyncTask from the main thread, use the following statement:

new TaskExample().execute();

  • Bonus Tip : AsyncTask is similar to Java threads with only difference being that AsyncTask can update the UI but can cause the UI to be sluggish. So if you don’t have to update the UI and a lot of processing is to be done, use Java threads else AsyncTask in your Android application.

2) Disable StrictMode in Android

Disabling strictmode is not the recommended way but still it will allow network operations from UI.

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

The strict mode was introduced with API level 9. Hence it is better to use the following check:

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

Related Posts

Create Non-Blocking User Interface in Android admin Android
If you try to run network operations in the main activity which is rendering the UI components on Android, you get the android.os.networkonmainthreadexception in your application. The result will be that you won't be able to execute network operations. It is now officially recommended to use an AsyncTask so...
<p>If you try to run network operations in the main activity which is rendering the UI components on Android, you get the android.os.networkonmainthreadexception in your application. The result will be that you won't be able to execute network operations. <strong>It is now officially recommended to use an AsyncTask</strong> so that the UI doesn't get blocked till the response is received from the remote device/machine. This exception makes sense because the OS and user won't want themselves to be blocked with one application only. So the solution for android.os.networkonmainthreadexception is <strong>either use AsyncTask or disable StrictMode</strong>. Both these approached are described below:</p> <h2>1) Using AsyncTask in Android</h2> <p>An AsyncTask runs in a separate thread than the main thread, it allows the UI thread to be non-blocking which is recommended for all Android applications. As described above, if you don't implement an AsyncTask for network operations, an exception android.os.networkonmainthreadexception is throws from the application by default. The following source-code shows how to create an AsyncTask and call it from UI thread:</p> 1 <p>The only requirement is that the implementation task should override the method: protected Object doInBackground(Object... url) {...} We can easily replace Object in the above code with any other Java class. The method is accepting variable arguments and hence it is up to the developer to pass as many arguments as required. In order to invoke the AsyncTask from the main thread, use the following statement: new TaskExample().execute(); </p> <p> <ul><li><strong>Bonus Tip :</strong> AsyncTask is similar to Java threads with only difference being that AsyncTask can update the UI but can cause the UI to be sluggish. So if you don't have to update the UI and a lot of processing is to be done, use Java threads else AsyncTask in your Android application.</li></ul></p> <h2>2) Disable StrictMode in Android</h2> <p>Disabling strictmode is not the recommended way but still it will allow network operations from UI.</p> 1 <p>The strict mode was introduced with API level 9. Hence it is better to use the following check:</p> 1
Android Hello World application tutorial with example
10 Easy steps to install Android emulator in windows
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Latest posts by admin (see all)

Comments

comments