AsyncTask 按下后退按钮时终止任务
我在使用 AsyncTask 时遇到了一些问题。
我的实现如下
private class MakeConnection extends AsyncTask<String, Void, String> implements OnDismissListener{
Context context;
ProgressDialog myDialog;
public MakeConnection(Context conetext)
{
this.context = conetext;
myDialog = new ProgressDialog(this.context);
myDialog.setCancelable(true);
myDialog.setOnDismissListener(this);
}
@Override
protected String doInBackground(String... urls) {
//do stuff
}
@Override
protected void onPostExecute(String result) {
try {
myDialog.dismiss();
success(result);
}catch(JSONException e)
{
data = e.toString();
}
}
@Override
protected void onProgressUpdate(Void... values) {
myDialog = ProgressDialog.show(context, "Please wait...", "Loading the data", true);
}
@Override
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
}
但是当我按下后退按钮时什么也没有发生,它只是完成任务,就像我没有按后退按钮
一样知道为什么吗?
I am having a little problems with AsyncTask.
I have it implemented as follows
private class MakeConnection extends AsyncTask<String, Void, String> implements OnDismissListener{
Context context;
ProgressDialog myDialog;
public MakeConnection(Context conetext)
{
this.context = conetext;
myDialog = new ProgressDialog(this.context);
myDialog.setCancelable(true);
myDialog.setOnDismissListener(this);
}
@Override
protected String doInBackground(String... urls) {
//do stuff
}
@Override
protected void onPostExecute(String result) {
try {
myDialog.dismiss();
success(result);
}catch(JSONException e)
{
data = e.toString();
}
}
@Override
protected void onProgressUpdate(Void... values) {
myDialog = ProgressDialog.show(context, "Please wait...", "Loading the data", true);
}
@Override
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
}
But when ever I press the back button nothing happens, it just completes the task as if I didn't press the back button
Any idea why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个问题有两个部分:
1)以这种方式实现你的
doInBackground()
,所以它检查AsyncTask
是否被取消。2) 您应该在 Activity 的
onDestroy()
中调用asynTask.cancel(true)
。There are two parts of this problem:
1) Implement your
doInBackground()
in such a way, so it checks whetherAsyncTask
is cancelled.2) You should call
asynTask.cancel(true)
in your Activity'sonDestroy()
.这解决了我的问题
This fixes my problem
也可以在活动中使用以下方法
it is also possible to use follwing method in activity