在创建各种Dialog时,通过重写Activity其类的方法 protected Dialog onCreateDialog(int id) 来创建Dialog,在需要显示的地方调用showDialog(int id),显示即可。在其中创建Dialog时,总是失败,究其原因:[ERROR/AndroidRuntime(7716): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application] AlertDialog.Builder build = new AlertDialog.Builder(getApplicationContext());这一句遇到问题,后改成 AlertDialog.Builder build = new AlertDialog.Builder(this);问题解决!
Context context = getApplicationContext();
Context context = **Activity.this;
其差别:
getApplicationContext()(SKD 文档):
/**
* 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.
*
* <p>Consider for example how this interacts with
* {@ #registerReceiver(BroadcastReceiver, IntentFilter)}:
* <ul>
* <li> <p>If used from an Activity context, the receiver is being registered
* within that activity. This means that you are expected to unregister
* before the activity is done being destroyed; in fact if you do not do
* so, the framework will clean up your leaked registration as it removes
* the activity and log an error. Thus, if you use the Activity context
* to register a receiver that is static (global to the process, not
* associated with an Activity instance) then that registration will be
* removed on you at whatever point the activity you used is destroyed.
* <li> <p>If used from the Context returned here, the receiver is being
* registered with the global state associated with your application. Thus
* it will never be unregistered for you. This is necessary if the receiver
* is associated with static data, not a particular component. However
* using the ApplicationContext elsewhere can easily lead to serious leaks
* if you forget to unregister, unbind, etc.
getApplicationContext() 生命周期是整个应用,应用摧毁它才摧毁
Activity.this的context属于activity ,activity 摧毁他就摧毁
因为只有一个Activity才能添加一个窗体。