之前遇到过这样的问题,

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

最新文章

  1. 第三十八篇、给UITabBar按钮的动画效果
  2. Python中的引用的使用注意
  3. yaml 1.6 操作
  4. validatebox验证框架rules
  5. Eclipse中使用正则屏蔽Logcat中的某些Tag
  6. Eclipse Tips
  7. Realm数据库的简单介绍和使用
  8. android 适配器 ArrayAdapter,SimpleAdapter的学习
  9. Automatic Preferred Max Layout Width is not available on iOS versions prior to
  10. Git之(六)标签管理
  11. Windows10远程报错:由于CredSSP加密Oracle修正导致远程失败
  12. LR12中针对WebServices协议的三种脚本开发模式
  13. Go used as value问题
  14. day9 集合基础命令
  15. Camera2点击对焦实现
  16. 掌握Sed命令
  17. EF GroupBy 分组 取某条的 总数
  18. destoon调用方法汇总 ---转载
  19. Redis 单机和多实例部署
  20. 用iptables做代理

热门文章

  1. Spring源深和六系列 CreateBean过程
  2. Spring IOC 之Bean作用域
  3. .NET程序保护专家.NET Reactor发布4.7版本
  4. Asp.net Identity 系列之 怎样修改Microsoft.AspNet.Identity.EntityFramework.IdentityUser 的 Id 字段的数据类型
  5. 我的Android 4 学习系列
  6. Lamda Action Func Thread 实例
  7. ASP.NET Identity登录原理 - Claims-based认证和OWIN
  8. IOS UI 第五篇:基本UI
  9. Python网络爬虫
  10. 集群管理工具Salt