使用 Progress Dialog As Singleton 是好习惯吗 Class

Is it good practice use Progress Dialog As Singleton Class

我有进度对话框 Class,它是单例的

public class ProgressDialogManager {

private static ProgressDialogManager manager = null;

private Context context;

private ProgressDialog pDialog = null;

private ProgressDialogManager(Context context) {
    this.context = context;

}

public static ProgressDialogManager getInstance(Context context) {
    if (manager == null)
        manager = new ProgressDialogManager(context);
    return manager;
}

public void showDialog(String msg) {
    if (pDialog == null)
        pDialog = new ProgressDialog(this.context);
    pDialog.setMessage(msg);
    pDialog.show();
}

public void closeDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
    }
 }
}

当 getInstance(this) 方法多个时 activity 我得到错误

android.view.WindowManager$BadTokenException: Unable to add window — token android.os.BinderProxy@447a6748 is not valid; is your activity running?

我的问题是 Progress Dialog As Singleton 是一个好习惯 Class 错误的原因是什么

android.view.WindowManager$BadTokenException: Unable to add window

当您尝试在已完成的 Activity 上显示 dialog 并且您正在传递其 context 以在另一个中显示 dialog 时,会发生此异常Activity.

您的代码创建了该场景:

假设您在 Activity 中创建了一个 ProgressDialogManager 的实例,并在 Activity 中显示了 dialog,这样就可以正常工作。

现在你销毁了那个Activity并移动到另一个Activity但是你之前创建的ProgressDialogManager实例没有被销毁因为你创造了它单例。现在,如果您尝试获取 ProgressDialogManager 的实例,它将 return 之前创建的 ProgressDialogManager 并且它包含已被销毁的 Previous Activitycontext

现在,如果您尝试显示对话框,那么它会抛出此异常,因为您正尝试使用 dead context.

显示对话框

要解决此问题,还要在 showDialog 中传递 context,并在 showDialog 中删除 dialog 上的 null 检查。

public void showDialog(String msg, Context context) {
    pDialog = new ProgressDialog(context);
    pDialog.setMessage(msg);
    pDialog.show();
}

Note : Don't make Context as a singleton member of any class because context keeps changing all the time