android os network on main thread exception

你离开我真会死。 提交于 2019-11-28 14:08:00

You need to run internet activities on a thread separate from main (UI) thread, you can do that by wrapping your code in the following block:

new Thread() {
    @Override
    public void run() {
       //your code here
    }
}.start();

Execute your Network related operation in AsyncTask

You can also refer here Android AsyncTask

public class ExcuteNetworkOperation extends AsyncTask<Void, Void, String>{

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            /**
             * show dialog
             */
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            /**
             * Do network related stuff
             * return string response.
             */
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            /**
             * update ui thread and remove dialog
             */
            super.onPostExecute(result);
        }
    }
first method 

you can create an AsynTask .. Your code should run in background in order to be responsive.. otherwise it will show Not Responding ..

Second Method

You can create a seperate thread for it .. using multitasking.

Third 

Right the code in the onCreate after setContentView

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

While all of the answers posted in this thread is correct, asynctasks are not really considering to be a good tool to user for network transactions anymore. The main reasons for this is that the asynctasks are very closely tied to activities so alot issues arise like..."what happens if the activity is destroyed before the network call returns?".

If you really want to implement android best practices (and not to mention impress your fellow Android devs) then why not perform a network task in a service?

I would suggest looking at the Path FOSS project android-prioriy-queue. They make it ridiculously easy to perform task in a service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!