【问题标题】:android.view.WindowManager$BadTokenException related to Dialog and Context与 Dialog 和 Context 相关的 android.view.WindowManager$BadTokenException
【发布时间】:2013-06-11 22:36:32
【问题描述】:

我在崩溃报告中收到此错误android.view.WindowManager$BadTokenException。在某些设备上它只报告异常但不会使应用程序崩溃,其他设备会遇到崩溃。

这与应用程序如何显示对话框有关。

其他答案表明使用了错误的context,就像一个全局的,但在我的情况下,我没有这样做,我将我的活动的上下文传递给另一个对象的方法。

public class Utils {

包含一个方法

public static void noConnection(Context context){
    final CustomAlertDialog alert = new CustomAlertDialog(context, context.getString(R.string.ErrorPastTense), context.getString(R.string.ErrorInternet), context.getString(R.string.OkButton), null);

    View.OnClickListener listener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            switch(id){
                case R.id.alertConfirm:
                    alert.dismiss();
                    break;
                default:
                    break;
            }
        }
    };
    alert.setListener(listener);
    alert.show();
}

由我的活动中的方法调用,例如Utils.noConnection(myActivity.this);

错误日志显示异常发生在alert.show()

为什么?以及如何避免

【问题讨论】:

  • 在 onCreate() Utils.noConnection(context); 中使用 Context context=null 作为全局和 context=this;

标签: android android-activity android-context android-windowmanager


【解决方案1】:

您确定要显示来自 UI 线程的对话框吗?尝试类似:

Handler handler = new Handler();
handler.post(new Runnable() {
    @Override
    public void run() {
        alert.show()
    }
});

【讨论】:

  • hm,它在onPostExecute() 中运行,所以这绝对是 UI 线程,但可能还有另一个对话框仍然显示在某个条件下。我在调用Utils 类之前添加了另一个dialog.dismiss()
  • 您正在从异步任务中打开一个对话框?当您尝试打开它时,您的上下文可能无效?
  • 无效? asynctask 在同一个活动中运行,如果服务器没有正确返回,则会出现此消息,在这种情况下,我不会更改活动或任何 UI 元素等,只是弹出一个对话框。
  • 它不确定,我的一些用户能够得到异常,我不是
  • 所以你说你的用户仍然使用上面的代码得到异常?
猜你喜欢
  • 2016-11-26
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多