对话投掷"无法添加窗口 - 令牌null不是与getApplication()为背景的应用程序“ [英] Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

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

问题描述

我的活动正在试图建立一个AlertDialog这需要一个上下文作为参数。这工作正常,如果我使用:

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);

不过,我是持怀疑态度用本为背景,由于内存泄漏的可能性,当活动被破坏,即使在像屏幕旋转一些简单的重建的。从在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()是可以接受的一个背景下,因为它引发异常:无法添加窗口 - 令牌null不是一个应用程序 每引用:<一href="http://stackoverflow.com/questions/1561803/android-progressdialog-show-crashes-with-getapplicationcontext">1, <一href="http://stackoverflow.com/questions/2634991/android-1-6-android-view-windowmanagerbadtokenexception-unable-to-add-window">2, <一href="http://groups.google.com/group/android-developers/browse_thread/thread/7a648edddccf6f7d">3,等等。

But for the AlertDialog() neither getApplicationContext() or getApplication() is acceptable as a Context, as it throws the exception: "Unable to add window — token null is not for an application" 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?

吉姆

推荐答案

而不是的getApplicationContext(),只需使用 ActivityName.this

这篇关于对话投掷&QUOT;无法添加窗口 - 令牌null不是与getApplication()为背景的应用程序“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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