我試圖在用戶點擊後退按鈕時取消我的aynctask。我已經完成了關於使用哪種方法進行此項操作的研究,並且發現很難弄清楚爲什麼有多種方法。我找到了一種方法並嘗試了它,但它僅解散了我的ProgressDialog,而我的aynctassk仍然執行。那麼有人可以幫助我解決這個問題,讓我的asynctask忽略正確的方法。後退按鈕只關閉進度對話框而不是AsyncTask
@Override
public void onBackPressed()
{
/** If user Pressed BackButton While Running Asynctask
this will close the ASynctask.
*/
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onBackPressed();
finish();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
/** If Activity is Destroyed While Running Asynctask
this will close the ASynctask. */
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
if (pDialog != null)
{
if(pDialog.isShowing())
{
pDialog.dismiss();
}
super.onPause();
}
}
並請讓我知道如果我需要後我doInBackGround
方法的問題
protected String doInBackground(String... args) {
try {
Intent in = getIntent();
String searchTerm = in.getStringExtra("TAG_SEARCH");
String query = URLEncoder.encode(searchTerm, "utf-8");
String URL = "http://example.com";
JSONParsser jParser = new JSONParsser();
JSONObject json = jParser.readJSONFeed(URL);
try {
JSONArray questions = json.getJSONObject("all").getJSONArray("questions");
for(int i = 0; i < questions.length(); i++) {
JSONObject question = questions.getJSONObject(i);
String Subject = question.getString(TAG_QUESTION_SUBJECT);
String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
String Content = question.getString(TAG_QUESTION_CONTENT);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QUESTION_SUBJECT, Subject);
map.put(TAG_QUESTION_CONTENT, Content);
map.put(TAG_QUESTION_CHOSENANSWER, ChosenAnswer);
questionList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
您應該添加一個監聽到你的進度對話框(例如,[OnDismissListener](http://developer.android.com/reference/android/ content/DialogInterface.OnDismissListener.html))並取消那裏的任務。 – ozbek