There are some other operations that jelly bean, ICS, HoneyComb won't allow to perform on the UI thread like:
- HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
- Opening a Socket connection (i.e. new Socket()).
- Attempting to connect to a remote MySQL database.
- Downloading a file (i.e. Downloader.downloadFile()).
Solution:
There are three ways to solve the problem of NetworkOnMainThreadException.
- If you look at android document you will find that from Honeycomb (3.0) they have introduced StrictMode which will not allow network operations on UI thread. So one simple solution is disabling the StrictMode.
StrictMode.setThreadPolicy(policy);
But I will not recommend this solution as it will increase load on UI thread with expensive operations like network operation which may freeze your app's UI and freezing UI or lagging in UI will give bad user experience.
- Second solution is to use AsyncTask<Params, Progress, Result> , using async task you can do all the long running operations which may result in UI lagging if you do those operations on UI thread.
- Third solution is to use Service. for network operations. Where you required to download data once only when user starts the app in that case I recommend IntentService.