2014-08-29 89 views
0

我試圖實現異步訪問互聯網使用AsyncTask,但在日誌貓PIDTID我的日誌是相同的,因爲AsyncTask不創建並行隊列,所以我的應用程序崩潰與NetworkOnMainThreadExceptionAsyncTask Android主線程

這裏是我的子類代碼:

class BL_SimpleAsyncTask extends AsyncTask<Void, Void, Void> { 

     String requestServer; 
     HashMap<String, String> postRequestBody; 
     //------------------------// answer from http client 
     static DefaultHttpClient sharedClient = null; 

     boolean isPostRequest; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      System.out.println("bg started"); 

      if (sharedClient == null) { 
       sharedClient = new DefaultHttpClient(); 
      } 

      HttpPost post = new HttpPost(requestServer); 
      String postBody = new String(); 
      postBody += "{"; 
      for (String key : postRequestBody.keySet()) { 
       String result = String.format("\"%s\":\"%s\",", key, postRequestBody.get(key)); 
       postBody += result; 

      } 

      System.out.println("body initialized"); 


      postBody.substring(0, postBody.length() - 1); 
      postBody += "}"; 
      try { 
       post.setEntity(new StringEntity(postBody)); 
      } catch (UnsupportedEncodingException e) { 
       System.out.println(e.getMessage()); 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      System.out.println("entity set"); 


      try { 
       if (post != null) { 
        System.out.println("starting request...."); 
        HttpResponse response = sharedClient.execute(post); 
        System.out.println("responce recieved"); 
       } else { 
        System.out.println("null request"); 

       } 
       // System.out.println(response) ; 

      } catch (ClientProtocolException e) { 
       System.out.println(e.getMessage()); 

       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       System.out.println(e.getMessage()); 

       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
     } 
    } 

} 

因此,要發動請求後,我只需做到以下幾點:

BL_SimpleAsyncTask obj = new BL_SimpleAsyncTask() ; 
    obj.requestServer = "https://api.orbios.com/v1/auth/sign-in" ; 
    obj.postRequestBody = new HashMap<String, String>() ; 
    obj.postRequestBody.put ("password", password) ; 
    obj.postRequestBody.put("email", email) ; 
    obj.isPostRequest = true ; 
    System.out.println("start bg thread") ; 

    obj.doInBackground() ; 

我在做什麼錯?

回答

3

您不應該自己撥打doInBackground()。只需撥打​​並讓框架在後臺線程中調用您的doInBackground()

+0

謝謝,AsyncTask是一個界面,我忘了!謝謝! – 2014-08-29 13:46:06

3

而不是直接調用doInBackground()你應該調用execute方法。