2014-08-29 2 views
0

Я пытаюсь реализовать асинхронный доступ к Интернету с помощью AsyncTask, но в журнале кошка PID и TID моего протоколирование одинакова, потому что AsyncTask не создает параллельную очередь, поэтому мои приложение аварии с NetworkOnMainThreadException.AsyncTask 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(). Просто позвоните execute() и позвольте фреймворку назвать ваш doInBackground() в фоновом потоке.

+0

Спасибо, AsyncTask - это интерфейс, я забыл! благодаря! –

3

Вместо прямого вызова doInBackground() вы должны позвонить по телефону execute.

Смежные вопросы