使用 getApplication() 作为上下文的对话框抛出“无法添加窗口 - 令牌 null 不适用于应用程序" [英] Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

查看:28
本文介绍了使用 getApplication() 作为上下文的对话框抛出“无法添加窗口 - 令牌 null 不适用于应用程序"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Activity 正在尝试创建一个 AlertDialog,它需要一个 Context 作为参数.如果我使用:

My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

但是,我对使用this"作为上下文持怀疑态度,因为即使在像屏幕旋转这样的简单操作期间,Activity 被销毁和重新创建时也可能发生内存泄漏.来自 Android 开发者博客上的相关帖子:

However, I am leery of using "this" as a context due to the potential for memory leaks when Activity is destroyed and recreated even during something simple like a screen rotation. From a related post on the Android developer's blog:

有两种简单的方法可以避免与上下文相关的内存泄漏.最明显的一个是避免将上下文转义到其自身范围之外.上面的示例显示了静态引用的情况,但内部类及其对外部类的隐式引用可能同样危险.第二种解决方案是使用应用程序上下文.只要您的应用程序处于活动状态并且不依赖于活动生命周期,此上下文就会存在.如果您打算保留需要上下文的长期对象,请记住应用程序对象.您可以通过调用 Context.getApplicationContext() 或 Activity.getApplication() 轻松获取它.

There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().

但是对于 AlertDialog() 来说,getApplicationContext()getApplication() 都不能作为上下文接受,因为它会抛出异常:

But for the AlertDialog() neither getApplicationContext() or getApplication() is acceptable as a Context, as it throws the exception:

无法添加窗口 - 令牌 null 不适用于应用程序"

"Unable to add window — token null is not for an application"

每个参考文献:123

per references: 1, 2, 3, etc.

那么,这真的应该被认为是一个错误"吗,因为我们被官方建议使用 Activity.getApplication() 但它并没有像宣传的那样运行?

So, should this really be considered a "bug", since we are officially advised to use Activity.getApplication() and yet it doesn't function as advertised?

吉姆

推荐答案

使用 ActivityName.this 代替 getApplicationContext().

这篇关于使用 getApplication() 作为上下文的对话框抛出“无法添加窗口 - 令牌 null 不适用于应用程序"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆