Android AsyncTask使用心得及錯誤處理-只能在主線程改變UI組件

來源:互聯網
上載者:User

Android AsyncTask使用心得及錯誤處理-只能在主線程改變UI組件

大家肯定都會經常使用AsyncTask這個類,特別是在網路處理中,先看改正後的代碼:這是正常的代碼:

 

class sendKeyTask extends AsyncTask{@Overrideprotected void onPostExecute(Integer resultCode) {// TODO Auto-generated method stubsuper.onPostExecute(resultCode);switch (resultCode) {case 6000:NotifyHelper.popNotifyInfo(InnerQuestionActivity.this, "使用者資訊異常", "");break;case 6001:NotifyHelper.popNotifyInfo(InnerQuestionActivity.this, "其他異常", "");break;case 6002:break;default:break;}// 隱藏IMEInputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);// 顯示或者隱藏IMEimm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);innerQuestionEdit.setText("");//從新重新整理new getQuestionDetailTack().execute(1);}@Overrideprotected Integer doInBackground(String... data) {// TODO Auto-generated method stubint resultCode=4001;HttpClient client= new DefaultHttpClient();HttpPost post = new HttpPost("http://diandianapp.sinaapp.com/add_key.php");StringBuilder builder = new StringBuilder(); List paramsList=new ArrayList();paramsList.add(new BasicNameValuePair("access_token", data[0]));paramsList.add(new BasicNameValuePair("user_name", data[1]));paramsList.add(new BasicNameValuePair("key_detail", data[2]));paramsList.add(new BasicNameValuePair("question_id", data[3]));for(int i=0;i可能有人會說,我讓doInBackground返回一個參數,再在onPostExecute裡面處理不是多次一舉嗎?但是,當你真的將兩部分合成後,會發現,竟然報錯了!報錯內容大體為UI內容只能在主線程更改;這是為什麼呢!

 

NotifyHelper.popNotifyInfo(InnerQuestionActivity.this, "其他異常", "");是對對話提示框的一個彈出方法封裝,這是對UI介面的操作,問題應該就出在這兒了!

我們翻開google的說明看下:

 

protected abstract Result doInBackground (Params... params)Added in API level 3

Override this method to perform a computation on a background thread. The specified parameters are the parameters passed toexecute(Params...) by the caller of this task. This method can callpublishProgress(Progress...) to publish updates on the UI thread.

Parameters
   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.