Android - android.os.NetworkOnMainThreadException

后端 未结 8 1201
迷失自我
迷失自我 2020-11-22 08:15

I have this exception and I was reading a thread on this, and it seemed confusing:

How to fix android.os.NetworkOnMainThreadException?

I already added this l

8条回答
  •  攒了一身酷
    2020-11-22 08:51

     try 
        {  
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("myUrl");
    
            // no idea what this does :)
            httppost.setEntity(new UrlEncodedFormEntity(postParameters));
    
            // This is the line that send the request
            HttpResponse response = httpclient.execute(httppost);
    
            HttpEntity entity = response.getEntity();            
    
            InputStream is = entity.getContent();
        } 
        catch (Exception e) 
        {     
            Log.e("log_tag", "Error in http connection "+e.toString());
        }        
    

    Here is your problem. Since api 11, this exception will inform you that you are running long tasks on the ui thread (the http communication in your class), and according with the new StrictGuard policy this is not possibile. So you have two different choice

    1. Use thread or aynctask in order to execut yout long term task (better way)

提交回复
热议问题