http://byandby.iteye.com/blog/1133327
屏幕中央有一个ProgressDialog 提示正在验证账户,验证的过程是通过一个异步任务来完成的,但是如果这时我不停的点击Back键--》一定要不停的点,就会抛出一个异常,异常见下图。
![点击查看原始大小图片](http://dl.iteye.com/upload/attachment/525086/d2713fd6-fd09-39fa-8f74-c3ef1e0b22e8.png)
这个异常的意思就是说没有一个 id为0的dialog 已经通过 showDialog()方法显示了。出现这个异常的原因是:当我们点击Back键的时候ProgressDialog 其实已经被结束了,它在当前的那个 Activity已经不存在了,然而后台的AsyncTask任务其实还在继续执行 。。然后我们又在onPostExecute() 方法取消显示这个Dialog,但是 这个时候 这个dialog已经没了啊,因为当我们点击Back键的时候 就会结束那个Dialog!! 找不到它了 所以抛出了这个异常。
解决办法就是 设置那个Dialog的onCancel事件,并且在onCancel方法里边判断 如果那个AsyncTask任务对象不等于null ,就结束它,代码片段如下。
- private AccountVerifyAsyncTask mAccountVerifyTask;
- if(mAccountVerifyTask == null || mAccountVerifyTask.getStatus() == AsyncTask.Status.FINISHED || mAccountVerifyTask.isCancelled()){
- mAccountVerifyTask = (AccountVerifyAsyncTask) new AccountVerifyAsyncTask().execute(username,password);
- }
- class AccountVerifyAsyncTask extends AsyncTask<String ,Integer, Integer>{
- @Override
- protected void onPreExecute() {
- showDialog(VERIFY_DIALOG_KEY);
- }
- @Override
- protected Integer doInBackground(String... params) {
- String username = params[0];
- String password = params[1];
- int result = AccountManager.instance().accountVerify(username, password);
- return result;
- }
- @Override
- protected void onPostExecute(Integer result) {
- dismissDialog(VERIFY_DIALOG_KEY);
- int code = result;
- AccountManager.instance().handleVerifyResult(code);
- if(AccountManager.SUCCESS == code){
- AccountManager.QUERY_CANCELED = false;
- onAccountChanged();
- }
- }
- }
- switch(id){
- case VERIFY_DIALOG_KEY: {
- final ProgressDialog dialog = new ProgressDialog(this);
- dialog.setMessage(getResources().getString(R.string.account_verify_account));
- dialog.setIndeterminate(true);
- dialog.setCancelable(true);
- dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
- @Override
- public void onCancel(DialogInterface dialog) {
- if(mAccountVerifyTask != null){
- mAccountVerifyTask.cancel(true);
- }
- }
- });
- //mVerifyDialog = dialog;
- return dialog;
- }