Android HttpClient : NetworkOnMainThreadException

后端 未结 4 1016
离开以前
离开以前 2020-11-29 12:45

I have some code below:

protected void testConnection(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new Htt         


        
相关标签:
4条回答
  • 2020-11-29 13:28

    On ICS and later you cannot do network operations on the UI thread anymore. Instead you are forced to create a new thread and do your networking stuff there.

    Possible tools are Android's AsyncTask and the normal Java Thread.

    A good tutorial can be found here: Android Threads, Handlers and AsyncTask - Tutorial

    0 讨论(0)
  • 2020-11-29 13:31

    You cant perform network operations in event thread, since android Api Level 11. Instead you should do network operation in another thread than event thread, and use Handler or Asynctask to do so.

    0 讨论(0)
  • 2020-11-29 13:35

    I you run your code in android 2.x and its lower version, i think this code will run perfectly. But if you run this in 3.x and it's upper version then you get an Exception. The problem is the you need to call the web service from your worker thread(AsyncTask<>) . You can not call the web service from the main thread.

    0 讨论(0)
  • 2020-11-29 13:36

    Starting from API 11, you can not manipulate network (time-consuming) operations on main thread. Use AsyncTask or Thread to perform such operations.

    0 讨论(0)
提交回复
热议问题