2012-12-08 68 views
0

我有一個簡單的程序,aks問題,然後調用一個PHP文件,說如果答案是一個是或否。Android:試圖顯示文本說,當HttpClient發送消息時,發送服務器

現在它可以工作,但信息發送時會有輕微的停頓。我希望有一些信息或指示顯示計算機正忙。

現在,當我chnage一個textvue的文字,我才發送數據,TextView的不改變,我allso試圖調用它的更新基法

代碼

case R.id.butYes: 
       mSend .setText("Sending your vote to server"); 
       mSend.invalidate(); 
       TalkToServer(mYes[mPes-1]); 
       UpdateScreen(); 
       mSend .setText(""); 
       break; 

     String TalkToServer(String addr) 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(addr); 

      HttpResponse response; 
      String responseBody=new String(""); 
      try { 
       response = httpclient.execute(httppost); 



responseBody = EntityUtils.toString(response.getEntity()); 
      } catch (ParseException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      return responseBody; 
     } 

回答

0

使用AsyncTask避免將數據發送到服務器時掛起UI只是將您的代碼更改爲:

case R.id.butYes: 
    new SendTextOperation().execute(""); 
    break; 

private class SendTextOperation extends AsyncTask<String, Void, String> { 

     @Override 
     protected void onPreExecute() { 

     //Update UI here 
     mSend.setText("Sending your vote to server"); 
     mSend.invalidate(); 
     } 

     @Override 
     protected String doInBackground(String... params) { 
      // Talk to server here to avoid Ui hanging 
      TalkToServer(mYes[mPes-1]); 
      return null; 
     }  

     @Override 
     protected void onPostExecute(String result) { 
      // Update screen here after talk to server end 
       UpdateScreen(); 
       mSend .setText(""); 
     } 

}