即使在Volley onResponse内的对话框上调用了.dismiss(),窗口也会泄漏

问题描述 投票:0回答:1

我正在重构旧版Android应用。我创建了一个名为UxUtil的util类,并创建了一个可以从活动中调用的函数,以显示成功响应对话框。

    private static AlertDialog simpleAlertDialog(final Context targetContext, String title, String message) {
        AlertDialog alertDialog = new AlertDialog.Builder(targetContext).create();
        alertDialog.setCanceledOnTouchOutside(false)
        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.cslogo_icon_small);
        // Setting Dialog Title
        alertDialog.setTitle(title);
        // Setting Dialog Message
        alertDialog.setMessage(message);
        alertDialog.dismiss();

        // Setting OK Button
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", (dialog, which) -> {
            dialog.dismiss();
            // Write your code here to execute after dialog closed
            ((Activity) targetContext).finish();
            ((Activity) targetContext).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        });
        return alertDialog;
    }

您可以看到,我取消了关于正面按钮onclick的对话框,甚至一般而言。

从一个活动中,我像这样从截击响应中调用此函数

btn_save.setOnClickListener(v -> performSave());

private void performSave(){
   // get data from UI for sending to server in a bean object called parcelObject.
 ServiceCall.saveGeneralDetail(parcelObject, username,
                        new VolleyResponseListener() {
                            @Override
                            public void onResponse(Object response) throws JSONException {
                                if (response != null) {
                                    JSONObject jb = new JSONObject(response.toString());
                                    UxUtil.simpleAlertDialog(context, jb.optString("ResponseMessage")).show();
                                }
                            }
                        }

                            @Override
                            public void onError(String message) {
                                UxUtil.simpleAlertDialog(context, message).show();
                            }
                        });

将AlertDialog提取到函数中的代码在尚未升级到凌空的部分代码中正常工作,即,遗留代码的一部分,该代码创建了一个新线程来执行网络调用,然后运行OnUiThread来显示对话框。

但是当我在凌空上升级它以清理线程,并从onResponse回调运行它时,Windows正在泄漏。即使我在单击按钮时调用dismiss()。为什么会这样?

android android-volley android-alertdialog
1个回答
0
投票

正如我可以向您展示的代码,如果对话框是在本地使用或定义为本地的,则还必须定义Dilaog的范围和上下文,因此您需要全局和公共使用它,以便其他类可以大量使用它。

© www.soinside.com 2019 - 2024. All rights reserved.