IllegalArgumentException: View not attached to window manager 解决方法

在抛出该问题之前,一般会抛出如下异常:

android.view.WindowLeaked: Activity ... that was originally added here

这种问题一般是由于 dialog 仍在运行时,创建该 dialog 的 Activity 却在进行 finishing 操作导致的。

出了问题之后,如何复现问题呢?方法如下:
1.打开手机“设置 —— 开发者选项 —— 不保留活动”的开关;
2.关闭待测试的应用,并在应用管理器中杀死该应用;
3.重新启动该应用;
4.将正显示进度对话框的应用通过按下 Home 键,切到后台。

如何解决这个问题
1.在 onPostExecute 方法中检测 Activity 的状态,如果是 isDestroyed 为 true 就不再调用 dialog 的 dismiss 方法;
2.在 Activity 的 onDestroy 方法中调用 dialog 的 dismiss 方法。

解决该问题的伪代码如下:

public class YourActivity extends Activity {

    <...>

    private void showProgressDialog() {
        if (pDialog == null) {
            pDialog = new ProgressDialog(StartActivity.this);
            pDialog.setMessage("Loading. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
        }
        pDialog.show();
    }

    private void dismissProgressDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        dismissProgressDialog();
        super.onDestroy();
    }

    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args)
        {
            doMoreStuff("internet");
            return null;
        }


        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url)
        {
            if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
                return;
            }
            dismissProgressDialog();
            something(note);
        }
    }
}

参考 stackoverflow View not attached to window manager crash 的链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容