Resolving NetworkOnMainThread Exception in Android

Today I am going to write how you can resolve NetworkOnMainThread Exception in Android.

So what isĀ android.os.NetworkOnMainThreadException ?

Before HoneyComb (i.e. API level 11) we were allowed to do Networking operations in our Android Application on main thread i.e we can do HTTP calls to server without creating a background thread if we want.

Though the above method was discouraged but the Android framework does not give any Exception if we do not create Thread or AsyncTask (both should be use while doing Network operations in Android Application) while doing Network operations in Main Thread.

But post Ginger Bread i.e in API level 11 whenever we do HTTP operation in Main Thread the Android Application crashes and gives android.os.NetworkOnMainThreadException.

To overcome this issue there are 3 methods to do so. We can choose any one method based on our convenience. But there is also the recommended method out of below three which I will write below:

1) Define a StrictMode Thread policy

The above policy tells the Android framework to ignore the Network operations on Main Thread in the activity.
But this should be only use when we are testing the application or when we want to test something on urgent basis, but should never be use in the Production Application.
The above code normally is written in onCreate() method of the Activity and should be removed in production application

2) Use Threads with Handlers

This method is used to do network operations in Thread and any UI change operation is done in Handlers since Thread does not have access to Main Thread.

In above code the Thread is used for doing background operations and handler is used to do the Main Thread operations. From background thread to Main Thread we can send message and handle it in import android.os.Handler ‘s handleMessage() method;

Though we can use this method but it will be tough to use when we want to handle cancelling of operation in the middle.

But there is the 3rd recommended method to avoid above issue i.e. Use of AsyncTask

3) AsyncTask

This method has its own life cycle methods which I will explain in other blog in detail.

AsyncTask has its own life cycle methods which execute one after the other based on their life cycle definitions
In the above code doInBackGround() method handles all the Network operation and preExecute() and postExecute() methods handle UI operation, but as name suggest they both are called before and after doInBackground() method respectively.

Thanks guys. Comment if you have any questions regarding the blog.

  1. Finlay

Leave a Reply

Your email address will not be published. Required fields are marked *