android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an applic

转载地址:http://blog.csdn.net/androidyue/article/details/9219883#
之前遇到过这样的问题
[java] view plaincopyprint?
04-12 10:40:33.302: E/AndroidRuntime(17213): Caused by: android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application  
04-12 10:40:33.302: E/AndroidRuntime(17213): at android.view.ViewRoot.setView(ViewRoot.java:509)  
04-12 10:40:33.302: E/AndroidRuntime(17213): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)  
Google了很多,然后在StackOverflow中看了很多回答,发现基本上都是给出了解决方法,没有解释出什么太详细的原因。
后来找到了一篇文章,地址是 http://tech.shantanugoel.com/2010/07/08/badtokenexception-android-dialog-getapplicationcontext.html
关于错误的解释是这样的:
Solution: Just replace “getApplicationContext()” with “this” (i.e. “Context mContext = this;” ) and it will work fine.
解决方法:使用this替换掉getApplicationContext()即可正常使用。
Explanation: As to why this is exactly an issue, I’m a bit fuzzy about it myself but this much I’m sure that the contexts that you get with getApplicationContext and this are different. On reading about this function from Android SDK help:


Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.


getApplicationContext() 返回当前进程中单一的全部Application对象的上下文。该方法仅在你需要一个生命周期与当前上下文分离,并关联进程的生命周期而不是当前的部件。


I think this would mean is that getApplicationContext returns a context which is for the application itself and not the activity, while “this” would give you the context of the activity in which you are creating the dialog. I think since it is the activity which is associated with the UI (and for whom the window has been created), using the application context would have caused the crash here.


我认为上面的意思是getApplicationContext()返回一个针对与自身Application的上下文对象,而不是当前的Activity的上下文对象,而”this”,会返回一个你创建Dialog的Activity的上下文。因为Actvity是和UI相关的(并且窗口为它而创建),所以使用Application的上下文会直接崩溃。


更多参考 http://code.google.com/p/android/issues/detail?id=11199
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值