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

时间:2021-09-20 11:48:33

之前遇到过这样的问题,

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了很多,然后在*中看了很多回答,发现基本上都是给出了解决方法,没有解释出什么太详细的原因。

后来找到了一篇文章,地址是 
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