我试图在用户点击后退按钮时取消我的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