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

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

 

class sendKeyTask extends AsyncTask
	{

		@Override
		protected void onPostExecute(Integer resultCode) {
			// TODO Auto-generated method stub
			super.onPostExecute(resultCode);
			switch (resultCode) {
			case 6000:
				NotifyHelper.popNotifyInfo(InnerQuestionActivity.this, "用戶信息異常", "");
				break;
			case 6001:
				NotifyHelper.popNotifyInfo(InnerQuestionActivity.this, "其他異常", "");
				break;
			case 6002:
				
				break;
			default:
				break;
			}
			// 隱藏輸入法
			InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			// 顯示或者隱藏輸入法
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			innerQuestionEdit.setText("");
			//從新刷新
			new getQuestionDetailTack().execute(1);
			
		}

		@Override
		protected Integer doInBackground(String... data) {
			// TODO Auto-generated method stub
			int resultCode=4001;
			HttpClient client= new DefaultHttpClient();
			HttpPost post = new HttpPost("https://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 to execute(Params...) by the caller of this task. This method can call publishProgress(Progress...) to publish updates on the UI thread.

Parameters
  

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *