Dialog.java revision 558459fe85f56f29a6ed6a4d0adb4a0bd6665884
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import com.android.internal.app.ActionBarImpl;
20import com.android.internal.policy.PolicyManager;
21
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.ContextWrapper;
25import android.content.DialogInterface;
26import android.graphics.drawable.Drawable;
27import android.net.Uri;
28import android.os.Bundle;
29import android.os.Handler;
30import android.os.Message;
31import android.util.TypedValue;
32import android.view.ActionMode;
33import android.view.ContextMenu;
34import android.view.ContextMenu.ContextMenuInfo;
35import android.view.ContextThemeWrapper;
36import android.view.Gravity;
37import android.view.KeyEvent;
38import android.view.LayoutInflater;
39import android.view.Menu;
40import android.view.MenuItem;
41import android.view.MotionEvent;
42import android.view.View;
43import android.view.View.OnCreateContextMenuListener;
44import android.view.ViewGroup;
45import android.view.ViewGroup.LayoutParams;
46import android.view.Window;
47import android.view.WindowManager;
48import android.view.accessibility.AccessibilityEvent;
49
50import java.lang.ref.WeakReference;
51
52/**
53 * Base class for Dialogs.
54 *
55 * <p>Note: Activities provide a facility to manage the creation, saving and
56 * restoring of dialogs. See {@link Activity#onCreateDialog(int)},
57 * {@link Activity#onPrepareDialog(int, Dialog)},
58 * {@link Activity#showDialog(int)}, and {@link Activity#dismissDialog(int)}. If
59 * these methods are used, {@link #getOwnerActivity()} will return the Activity
60 * that managed this dialog.
61 *
62 * <p>Often you will want to have a Dialog display on top of the current
63 * input method, because there is no reason for it to accept text.  You can
64 * do this by setting the {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM
65 * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} window flag (assuming
66 * your Dialog takes input focus, as it the default) with the following code:
67 *
68 * <pre>
69 * getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
70 *         WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);</pre>
71 *
72 * <div class="special reference">
73 * <h3>Developer Guides</h3>
74 * <p>For more information about creating dialogs, read the
75 * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p>
76 * </div>
77 */
78public class Dialog implements DialogInterface, Window.Callback,
79        KeyEvent.Callback, OnCreateContextMenuListener {
80    private Activity mOwnerActivity;
81
82    final Context mContext;
83    final WindowManager mWindowManager;
84    Window mWindow;
85    View mDecor;
86    private ActionBarImpl mActionBar;
87    /**
88     * This field should be made private, so it is hidden from the SDK.
89     * {@hide}
90     */
91    protected boolean mCancelable = true;
92
93    private String mCancelAndDismissTaken;
94    private Message mCancelMessage;
95    private Message mDismissMessage;
96    private Message mShowMessage;
97
98    private OnKeyListener mOnKeyListener;
99
100    private boolean mCreated = false;
101    private boolean mShowing = false;
102    private boolean mCanceled = false;
103
104    private final Thread mUiThread;
105    private final Handler mHandler = new Handler();
106
107    private static final int DISMISS = 0x43;
108    private static final int CANCEL = 0x44;
109    private static final int SHOW = 0x45;
110
111    private Handler mListenersHandler;
112
113    private final Runnable mDismissAction = new Runnable() {
114        public void run() {
115            dismissDialog();
116        }
117    };
118
119    /**
120     * Create a Dialog window that uses the default dialog frame style.
121     *
122     * @param context The Context the Dialog is to run it.  In particular, it
123     *                uses the window manager and theme in this context to
124     *                present its UI.
125     */
126    public Dialog(Context context) {
127        this(context, 0, true);
128    }
129
130    /**
131     * Create a Dialog window that uses a custom dialog style.
132     *
133     * @param context The Context in which the Dialog should run. In particular, it
134     *                uses the window manager and theme from this context to
135     *                present its UI.
136     * @param theme A style resource describing the theme to use for the
137     * window. See <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">Style
138     * and Theme Resources</a> for more information about defining and using
139     * styles.  This theme is applied on top of the current theme in
140     * <var>context</var>.  If 0, the default dialog theme will be used.
141     */
142    public Dialog(Context context, int theme) {
143        this(context, theme, true);
144    }
145
146    Dialog(Context context, int theme, boolean createContextWrapper) {
147        if (theme == 0) {
148            TypedValue outValue = new TypedValue();
149            context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,
150                    outValue, true);
151            theme = outValue.resourceId;
152        }
153
154        mContext = createContextWrapper ? new ContextThemeWrapper(context, theme) : context;
155        mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
156        Window w = PolicyManager.makeNewWindow(mContext);
157        mWindow = w;
158        w.setCallback(this);
159        w.setWindowManager(mWindowManager, null, null);
160        w.setGravity(Gravity.CENTER);
161        mUiThread = Thread.currentThread();
162        mListenersHandler = new ListenersHandler(this);
163    }
164
165    /**
166     * @deprecated
167     * @hide
168     */
169    @Deprecated
170    protected Dialog(Context context, boolean cancelable,
171            Message cancelCallback) {
172        this(context);
173        mCancelable = cancelable;
174        mCancelMessage = cancelCallback;
175    }
176
177    protected Dialog(Context context, boolean cancelable,
178            OnCancelListener cancelListener) {
179        this(context);
180        mCancelable = cancelable;
181        setOnCancelListener(cancelListener);
182    }
183
184    /**
185     * Retrieve the Context this Dialog is running in.
186     *
187     * @return Context The Context used by the Dialog.
188     */
189    public final Context getContext() {
190        return mContext;
191    }
192
193    /**
194     * Retrieve the {@link ActionBar} attached to this dialog, if present.
195     *
196     * @return The ActionBar attached to the dialog or null if no ActionBar is present.
197     */
198    public ActionBar getActionBar() {
199        return mActionBar;
200    }
201
202    /**
203     * Sets the Activity that owns this dialog. An example use: This Dialog will
204     * use the suggested volume control stream of the Activity.
205     *
206     * @param activity The Activity that owns this dialog.
207     */
208    public final void setOwnerActivity(Activity activity) {
209        mOwnerActivity = activity;
210
211        getWindow().setVolumeControlStream(mOwnerActivity.getVolumeControlStream());
212    }
213
214    /**
215     * Returns the Activity that owns this Dialog. For example, if
216     * {@link Activity#showDialog(int)} is used to show this Dialog, that
217     * Activity will be the owner (by default). Depending on how this dialog was
218     * created, this may return null.
219     *
220     * @return The Activity that owns this Dialog.
221     */
222    public final Activity getOwnerActivity() {
223        return mOwnerActivity;
224    }
225
226    /**
227     * @return Whether the dialog is currently showing.
228     */
229    public boolean isShowing() {
230        return mShowing;
231    }
232
233    /**
234     * Start the dialog and display it on screen.  The window is placed in the
235     * application layer and opaque.  Note that you should not override this
236     * method to do initialization when the dialog is shown, instead implement
237     * that in {@link #onStart}.
238     */
239    public void show() {
240        if (mShowing) {
241            if (mDecor != null) {
242                if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
243                    mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
244                }
245                mDecor.setVisibility(View.VISIBLE);
246            }
247            return;
248        }
249
250        mCanceled = false;
251
252        if (!mCreated) {
253            dispatchOnCreate(null);
254        }
255
256        onStart();
257        mDecor = mWindow.getDecorView();
258
259        if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
260            mActionBar = new ActionBarImpl(this);
261        }
262
263        WindowManager.LayoutParams l = mWindow.getAttributes();
264        if ((l.softInputMode
265                & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
266            WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
267            nl.copyFrom(l);
268            nl.softInputMode |=
269                    WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
270            l = nl;
271        }
272
273        try {
274            mWindowManager.addView(mDecor, l);
275            mShowing = true;
276
277            sendShowMessage();
278        } finally {
279        }
280    }
281
282    /**
283     * Hide the dialog, but do not dismiss it.
284     */
285    public void hide() {
286        if (mDecor != null) {
287            mDecor.setVisibility(View.GONE);
288        }
289    }
290
291    /**
292     * Dismiss this dialog, removing it from the screen. This method can be
293     * invoked safely from any thread.  Note that you should not override this
294     * method to do cleanup when the dialog is dismissed, instead implement
295     * that in {@link #onStop}.
296     */
297    public void dismiss() {
298        if (Thread.currentThread() != mUiThread) {
299            mHandler.post(mDismissAction);
300        } else {
301            mDismissAction.run();
302        }
303    }
304
305    private void dismissDialog() {
306        if (mDecor == null || !mShowing) {
307            return;
308        }
309
310        try {
311            mWindowManager.removeView(mDecor);
312        } finally {
313            mDecor = null;
314            mWindow.closeAllPanels();
315            onStop();
316            mShowing = false;
317
318            sendDismissMessage();
319        }
320    }
321
322    private void sendDismissMessage() {
323        if (mDismissMessage != null) {
324            // Obtain a new message so this dialog can be re-used
325            Message.obtain(mDismissMessage).sendToTarget();
326        }
327    }
328
329    private void sendShowMessage() {
330        if (mShowMessage != null) {
331            // Obtain a new message so this dialog can be re-used
332            Message.obtain(mShowMessage).sendToTarget();
333        }
334    }
335
336    // internal method to make sure mcreated is set properly without requiring
337    // users to call through to super in onCreate
338    void dispatchOnCreate(Bundle savedInstanceState) {
339        if (!mCreated) {
340            onCreate(savedInstanceState);
341            mCreated = true;
342        }
343    }
344
345    /**
346     * Similar to {@link Activity#onCreate}, you should initialize your dialog
347     * in this method, including calling {@link #setContentView}.
348     * @param savedInstanceState If this dialog is being reinitalized after a
349     *     the hosting activity was previously shut down, holds the result from
350     *     the most recent call to {@link #onSaveInstanceState}, or null if this
351     *     is the first time.
352     */
353    protected void onCreate(Bundle savedInstanceState) {
354    }
355
356    /**
357     * Called when the dialog is starting.
358     */
359    protected void onStart() {
360        if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
361    }
362
363    /**
364     * Called to tell you that you're stopping.
365     */
366    protected void onStop() {
367        if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
368    }
369
370    private static final String DIALOG_SHOWING_TAG = "android:dialogShowing";
371    private static final String DIALOG_HIERARCHY_TAG = "android:dialogHierarchy";
372
373    /**
374     * Saves the state of the dialog into a bundle.
375     *
376     * The default implementation saves the state of its view hierarchy, so you'll
377     * likely want to call through to super if you override this to save additional
378     * state.
379     * @return A bundle with the state of the dialog.
380     */
381    public Bundle onSaveInstanceState() {
382        Bundle bundle = new Bundle();
383        bundle.putBoolean(DIALOG_SHOWING_TAG, mShowing);
384        if (mCreated) {
385            bundle.putBundle(DIALOG_HIERARCHY_TAG, mWindow.saveHierarchyState());
386        }
387        return bundle;
388    }
389
390    /**
391     * Restore the state of the dialog from a previously saved bundle.
392     *
393     * The default implementation restores the state of the dialog's view
394     * hierarchy that was saved in the default implementation of {@link #onSaveInstanceState()},
395     * so be sure to call through to super when overriding unless you want to
396     * do all restoring of state yourself.
397     * @param savedInstanceState The state of the dialog previously saved by
398     *     {@link #onSaveInstanceState()}.
399     */
400    public void onRestoreInstanceState(Bundle savedInstanceState) {
401        final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);
402        if (dialogHierarchyState == null) {
403            // dialog has never been shown, or onCreated, nothing to restore.
404            return;
405        }
406        dispatchOnCreate(savedInstanceState);
407        mWindow.restoreHierarchyState(dialogHierarchyState);
408        if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {
409            show();
410        }
411    }
412
413    /**
414     * Retrieve the current Window for the activity.  This can be used to
415     * directly access parts of the Window API that are not available
416     * through Activity/Screen.
417     *
418     * @return Window The current window, or null if the activity is not
419     *         visual.
420     */
421    public Window getWindow() {
422        return mWindow;
423    }
424
425    /**
426     * Call {@link android.view.Window#getCurrentFocus} on the
427     * Window if this Activity to return the currently focused view.
428     *
429     * @return View The current View with focus or null.
430     *
431     * @see #getWindow
432     * @see android.view.Window#getCurrentFocus
433     */
434    public View getCurrentFocus() {
435        return mWindow != null ? mWindow.getCurrentFocus() : null;
436    }
437
438    /**
439     * Finds a view that was identified by the id attribute from the XML that
440     * was processed in {@link #onStart}.
441     *
442     * @param id the identifier of the view to find
443     * @return The view if found or null otherwise.
444     */
445    public View findViewById(int id) {
446        return mWindow.findViewById(id);
447    }
448
449    /**
450     * Set the screen content from a layout resource.  The resource will be
451     * inflated, adding all top-level views to the screen.
452     *
453     * @param layoutResID Resource ID to be inflated.
454     */
455    public void setContentView(int layoutResID) {
456        mWindow.setContentView(layoutResID);
457    }
458
459    /**
460     * Set the screen content to an explicit view.  This view is placed
461     * directly into the screen's view hierarchy.  It can itself be a complex
462     * view hierarhcy.
463     *
464     * @param view The desired content to display.
465     */
466    public void setContentView(View view) {
467        mWindow.setContentView(view);
468    }
469
470    /**
471     * Set the screen content to an explicit view.  This view is placed
472     * directly into the screen's view hierarchy.  It can itself be a complex
473     * view hierarhcy.
474     *
475     * @param view The desired content to display.
476     * @param params Layout parameters for the view.
477     */
478    public void setContentView(View view, ViewGroup.LayoutParams params) {
479        mWindow.setContentView(view, params);
480    }
481
482    /**
483     * Add an additional content view to the screen.  Added after any existing
484     * ones in the screen -- existing views are NOT removed.
485     *
486     * @param view The desired content to display.
487     * @param params Layout parameters for the view.
488     */
489    public void addContentView(View view, ViewGroup.LayoutParams params) {
490        mWindow.addContentView(view, params);
491    }
492
493    /**
494     * Set the title text for this dialog's window.
495     *
496     * @param title The new text to display in the title.
497     */
498    public void setTitle(CharSequence title) {
499        mWindow.setTitle(title);
500        mWindow.getAttributes().setTitle(title);
501    }
502
503    /**
504     * Set the title text for this dialog's window. The text is retrieved
505     * from the resources with the supplied identifier.
506     *
507     * @param titleId the title's text resource identifier
508     */
509    public void setTitle(int titleId) {
510        setTitle(mContext.getText(titleId));
511    }
512
513    /**
514     * A key was pressed down.
515     *
516     * <p>If the focused view didn't want this event, this method is called.
517     *
518     * <p>The default implementation consumed the KEYCODE_BACK to later
519     * handle it in {@link #onKeyUp}.
520     *
521     * @see #onKeyUp
522     * @see android.view.KeyEvent
523     */
524    public boolean onKeyDown(int keyCode, KeyEvent event) {
525        if (keyCode == KeyEvent.KEYCODE_BACK) {
526            event.startTracking();
527            return true;
528        }
529
530        return false;
531    }
532
533    /**
534     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
535     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
536     * the event).
537     */
538    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
539        return false;
540    }
541
542    /**
543     * A key was released.
544     *
545     * <p>The default implementation handles KEYCODE_BACK to close the
546     * dialog.
547     *
548     * @see #onKeyDown
549     * @see KeyEvent
550     */
551    public boolean onKeyUp(int keyCode, KeyEvent event) {
552        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
553                && !event.isCanceled()) {
554            onBackPressed();
555            return true;
556        }
557        return false;
558    }
559
560    /**
561     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
562     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
563     * the event).
564     */
565    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
566        return false;
567    }
568
569    /**
570     * Called when the dialog has detected the user's press of the back
571     * key.  The default implementation simply cancels the dialog (only if
572     * it is cancelable), but you can override this to do whatever you want.
573     */
574    public void onBackPressed() {
575        if (mCancelable) {
576            cancel();
577        }
578    }
579
580    /**
581     * Called when an key shortcut event is not handled by any of the views in the Dialog.
582     * Override this method to implement global key shortcuts for the Dialog.
583     * Key shortcuts can also be implemented by setting the
584     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
585     *
586     * @param keyCode The value in event.getKeyCode().
587     * @param event Description of the key event.
588     * @return True if the key shortcut was handled.
589     */
590    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
591        return false;
592    }
593
594    /**
595     * Called when a touch screen event was not handled by any of the views
596     * under it. This is most useful to process touch events that happen outside
597     * of your window bounds, where there is no view to receive it.
598     *
599     * @param event The touch screen event being processed.
600     * @return Return true if you have consumed the event, false if you haven't.
601     *         The default implementation will cancel the dialog when a touch
602     *         happens outside of the window bounds.
603     */
604    public boolean onTouchEvent(MotionEvent event) {
605        if (mCancelable && mShowing && mWindow.shouldCloseOnTouch(mContext, event)) {
606            cancel();
607            return true;
608        }
609
610        return false;
611    }
612
613    /**
614     * Called when the trackball was moved and not handled by any of the
615     * views inside of the activity.  So, for example, if the trackball moves
616     * while focus is on a button, you will receive a call here because
617     * buttons do not normally do anything with trackball events.  The call
618     * here happens <em>before</em> trackball movements are converted to
619     * DPAD key events, which then get sent back to the view hierarchy, and
620     * will be processed at the point for things like focus navigation.
621     *
622     * @param event The trackball event being processed.
623     *
624     * @return Return true if you have consumed the event, false if you haven't.
625     * The default implementation always returns false.
626     */
627    public boolean onTrackballEvent(MotionEvent event) {
628        return false;
629    }
630
631    /**
632     * Called when a generic motion event was not handled by any of the
633     * views inside of the dialog.
634     * <p>
635     * Generic motion events describe joystick movements, mouse hovers, track pad
636     * touches, scroll wheel movements and other input events.  The
637     * {@link MotionEvent#getSource() source} of the motion event specifies
638     * the class of input that was received.  Implementations of this method
639     * must examine the bits in the source before processing the event.
640     * The following code example shows how this is done.
641     * </p><p>
642     * Generic motion events with source class
643     * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
644     * are delivered to the view under the pointer.  All other generic motion events are
645     * delivered to the focused view.
646     * </p><p>
647     * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
648     * handle this event.
649     * </p>
650     *
651     * @param event The generic motion event being processed.
652     *
653     * @return Return true if you have consumed the event, false if you haven't.
654     * The default implementation always returns false.
655     */
656    public boolean onGenericMotionEvent(MotionEvent event) {
657        return false;
658    }
659
660    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
661        if (mDecor != null) {
662            mWindowManager.updateViewLayout(mDecor, params);
663        }
664    }
665
666    public void onContentChanged() {
667    }
668
669    public void onWindowFocusChanged(boolean hasFocus) {
670    }
671
672    public void onAttachedToWindow() {
673    }
674
675    public void onDetachedFromWindow() {
676    }
677
678    /**
679     * Called to process key events.  You can override this to intercept all
680     * key events before they are dispatched to the window.  Be sure to call
681     * this implementation for key events that should be handled normally.
682     *
683     * @param event The key event.
684     *
685     * @return boolean Return true if this event was consumed.
686     */
687    public boolean dispatchKeyEvent(KeyEvent event) {
688        if ((mOnKeyListener != null) && (mOnKeyListener.onKey(this, event.getKeyCode(), event))) {
689            return true;
690        }
691        if (mWindow.superDispatchKeyEvent(event)) {
692            return true;
693        }
694        return event.dispatch(this, mDecor != null
695                ? mDecor.getKeyDispatcherState() : null, this);
696    }
697
698    /**
699     * Called to process a key shortcut event.
700     * You can override this to intercept all key shortcut events before they are
701     * dispatched to the window.  Be sure to call this implementation for key shortcut
702     * events that should be handled normally.
703     *
704     * @param event The key shortcut event.
705     * @return True if this event was consumed.
706     */
707    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
708        if (mWindow.superDispatchKeyShortcutEvent(event)) {
709            return true;
710        }
711        return onKeyShortcut(event.getKeyCode(), event);
712    }
713
714    /**
715     * Called to process touch screen events.  You can override this to
716     * intercept all touch screen events before they are dispatched to the
717     * window.  Be sure to call this implementation for touch screen events
718     * that should be handled normally.
719     *
720     * @param ev The touch screen event.
721     *
722     * @return boolean Return true if this event was consumed.
723     */
724    public boolean dispatchTouchEvent(MotionEvent ev) {
725        if (mWindow.superDispatchTouchEvent(ev)) {
726            return true;
727        }
728        return onTouchEvent(ev);
729    }
730
731    /**
732     * Called to process trackball events.  You can override this to
733     * intercept all trackball events before they are dispatched to the
734     * window.  Be sure to call this implementation for trackball events
735     * that should be handled normally.
736     *
737     * @param ev The trackball event.
738     *
739     * @return boolean Return true if this event was consumed.
740     */
741    public boolean dispatchTrackballEvent(MotionEvent ev) {
742        if (mWindow.superDispatchTrackballEvent(ev)) {
743            return true;
744        }
745        return onTrackballEvent(ev);
746    }
747
748    /**
749     * Called to process generic motion events.  You can override this to
750     * intercept all generic motion events before they are dispatched to the
751     * window.  Be sure to call this implementation for generic motion events
752     * that should be handled normally.
753     *
754     * @param ev The generic motion event.
755     *
756     * @return boolean Return true if this event was consumed.
757     */
758    public boolean dispatchGenericMotionEvent(MotionEvent ev) {
759        if (mWindow.superDispatchGenericMotionEvent(ev)) {
760            return true;
761        }
762        return onGenericMotionEvent(ev);
763    }
764
765    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
766        event.setClassName(getClass().getName());
767        event.setPackageName(mContext.getPackageName());
768
769        LayoutParams params = getWindow().getAttributes();
770        boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
771            (params.height == LayoutParams.MATCH_PARENT);
772        event.setFullScreen(isFullScreen);
773
774        return false;
775    }
776
777    /**
778     * @see Activity#onCreatePanelView(int)
779     */
780    public View onCreatePanelView(int featureId) {
781        return null;
782    }
783
784    /**
785     * @see Activity#onCreatePanelMenu(int, Menu)
786     */
787    public boolean onCreatePanelMenu(int featureId, Menu menu) {
788        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
789            return onCreateOptionsMenu(menu);
790        }
791
792        return false;
793    }
794
795    /**
796     * @see Activity#onPreparePanel(int, View, Menu)
797     */
798    public boolean onPreparePanel(int featureId, View view, Menu menu) {
799        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
800            boolean goforit = onPrepareOptionsMenu(menu);
801            return goforit && menu.hasVisibleItems();
802        }
803        return true;
804    }
805
806    /**
807     * @see Activity#onMenuOpened(int, Menu)
808     */
809    public boolean onMenuOpened(int featureId, Menu menu) {
810        if (featureId == Window.FEATURE_ACTION_BAR) {
811            mActionBar.dispatchMenuVisibilityChanged(true);
812        }
813        return true;
814    }
815
816    /**
817     * @see Activity#onMenuItemSelected(int, MenuItem)
818     */
819    public boolean onMenuItemSelected(int featureId, MenuItem item) {
820        return false;
821    }
822
823    /**
824     * @see Activity#onPanelClosed(int, Menu)
825     */
826    public void onPanelClosed(int featureId, Menu menu) {
827        if (featureId == Window.FEATURE_ACTION_BAR) {
828            mActionBar.dispatchMenuVisibilityChanged(false);
829        }
830    }
831
832    /**
833     * It is usually safe to proxy this call to the owner activity's
834     * {@link Activity#onCreateOptionsMenu(Menu)} if the client desires the same
835     * menu for this Dialog.
836     *
837     * @see Activity#onCreateOptionsMenu(Menu)
838     * @see #getOwnerActivity()
839     */
840    public boolean onCreateOptionsMenu(Menu menu) {
841        return true;
842    }
843
844    /**
845     * It is usually safe to proxy this call to the owner activity's
846     * {@link Activity#onPrepareOptionsMenu(Menu)} if the client desires the
847     * same menu for this Dialog.
848     *
849     * @see Activity#onPrepareOptionsMenu(Menu)
850     * @see #getOwnerActivity()
851     */
852    public boolean onPrepareOptionsMenu(Menu menu) {
853        return true;
854    }
855
856    /**
857     * @see Activity#onOptionsItemSelected(MenuItem)
858     */
859    public boolean onOptionsItemSelected(MenuItem item) {
860        return false;
861    }
862
863    /**
864     * @see Activity#onOptionsMenuClosed(Menu)
865     */
866    public void onOptionsMenuClosed(Menu menu) {
867    }
868
869    /**
870     * @see Activity#openOptionsMenu()
871     */
872    public void openOptionsMenu() {
873        mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
874    }
875
876    /**
877     * @see Activity#closeOptionsMenu()
878     */
879    public void closeOptionsMenu() {
880        mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
881    }
882
883    /**
884     * @see Activity#invalidateOptionsMenu()
885     */
886    public void invalidateOptionsMenu() {
887        mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
888    }
889
890    /**
891     * @see Activity#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)
892     */
893    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
894    }
895
896    /**
897     * @see Activity#registerForContextMenu(View)
898     */
899    public void registerForContextMenu(View view) {
900        view.setOnCreateContextMenuListener(this);
901    }
902
903    /**
904     * @see Activity#unregisterForContextMenu(View)
905     */
906    public void unregisterForContextMenu(View view) {
907        view.setOnCreateContextMenuListener(null);
908    }
909
910    /**
911     * @see Activity#openContextMenu(View)
912     */
913    public void openContextMenu(View view) {
914        view.showContextMenu();
915    }
916
917    /**
918     * @see Activity#onContextItemSelected(MenuItem)
919     */
920    public boolean onContextItemSelected(MenuItem item) {
921        return false;
922    }
923
924    /**
925     * @see Activity#onContextMenuClosed(Menu)
926     */
927    public void onContextMenuClosed(Menu menu) {
928    }
929
930    /**
931     * This hook is called when the user signals the desire to start a search.
932     */
933    public boolean onSearchRequested() {
934        final SearchManager searchManager = (SearchManager) mContext
935                .getSystemService(Context.SEARCH_SERVICE);
936
937        // associate search with owner activity
938        final ComponentName appName = getAssociatedActivity();
939        if (appName != null && searchManager.getSearchableInfo(appName) != null) {
940            searchManager.startSearch(null, false, appName, null, false);
941            dismiss();
942            return true;
943        } else {
944            return false;
945        }
946    }
947
948    public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
949        if (mActionBar != null) {
950            return mActionBar.startActionMode(callback);
951        }
952        return null;
953    }
954
955    public void onActionModeStarted(ActionMode mode) {
956    }
957
958    public void onActionModeFinished(ActionMode mode) {
959    }
960
961    /**
962     * @return The activity associated with this dialog, or null if there is no associated activity.
963     */
964    private ComponentName getAssociatedActivity() {
965        Activity activity = mOwnerActivity;
966        Context context = getContext();
967        while (activity == null && context != null) {
968            if (context instanceof Activity) {
969                activity = (Activity) context;  // found it!
970            } else {
971                context = (context instanceof ContextWrapper) ?
972                        ((ContextWrapper) context).getBaseContext() : // unwrap one level
973                        null;                                         // done
974            }
975        }
976        return activity == null ? null : activity.getComponentName();
977    }
978
979
980    /**
981     * Request that key events come to this dialog. Use this if your
982     * dialog has no views with focus, but the dialog still wants
983     * a chance to process key events.
984     *
985     * @param get true if the dialog should receive key events, false otherwise
986     * @see android.view.Window#takeKeyEvents
987     */
988    public void takeKeyEvents(boolean get) {
989        mWindow.takeKeyEvents(get);
990    }
991
992    /**
993     * Enable extended window features.  This is a convenience for calling
994     * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
995     *
996     * @param featureId The desired feature as defined in
997     *                  {@link android.view.Window}.
998     * @return Returns true if the requested feature is supported and now
999     *         enabled.
1000     *
1001     * @see android.view.Window#requestFeature
1002     */
1003    public final boolean requestWindowFeature(int featureId) {
1004        return getWindow().requestFeature(featureId);
1005    }
1006
1007    /**
1008     * Convenience for calling
1009     * {@link android.view.Window#setFeatureDrawableResource}.
1010     */
1011    public final void setFeatureDrawableResource(int featureId, int resId) {
1012        getWindow().setFeatureDrawableResource(featureId, resId);
1013    }
1014
1015    /**
1016     * Convenience for calling
1017     * {@link android.view.Window#setFeatureDrawableUri}.
1018     */
1019    public final void setFeatureDrawableUri(int featureId, Uri uri) {
1020        getWindow().setFeatureDrawableUri(featureId, uri);
1021    }
1022
1023    /**
1024     * Convenience for calling
1025     * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
1026     */
1027    public final void setFeatureDrawable(int featureId, Drawable drawable) {
1028        getWindow().setFeatureDrawable(featureId, drawable);
1029    }
1030
1031    /**
1032     * Convenience for calling
1033     * {@link android.view.Window#setFeatureDrawableAlpha}.
1034     */
1035    public final void setFeatureDrawableAlpha(int featureId, int alpha) {
1036        getWindow().setFeatureDrawableAlpha(featureId, alpha);
1037    }
1038
1039    public LayoutInflater getLayoutInflater() {
1040        return getWindow().getLayoutInflater();
1041    }
1042
1043    /**
1044     * Sets whether this dialog is cancelable with the
1045     * {@link KeyEvent#KEYCODE_BACK BACK} key.
1046     */
1047    public void setCancelable(boolean flag) {
1048        mCancelable = flag;
1049    }
1050
1051    /**
1052     * Sets whether this dialog is canceled when touched outside the window's
1053     * bounds. If setting to true, the dialog is set to be cancelable if not
1054     * already set.
1055     *
1056     * @param cancel Whether the dialog should be canceled when touched outside
1057     *            the window.
1058     */
1059    public void setCanceledOnTouchOutside(boolean cancel) {
1060        if (cancel && !mCancelable) {
1061            mCancelable = true;
1062        }
1063
1064        mWindow.setCloseOnTouchOutside(cancel);
1065    }
1066
1067    /**
1068     * Cancel the dialog.  This is essentially the same as calling {@link #dismiss()}, but it will
1069     * also call your {@link DialogInterface.OnCancelListener} (if registered).
1070     */
1071    public void cancel() {
1072        if (!mCanceled && mCancelMessage != null) {
1073            mCanceled = true;
1074            // Obtain a new message so this dialog can be re-used
1075            Message.obtain(mCancelMessage).sendToTarget();
1076        }
1077        dismiss();
1078    }
1079
1080    /**
1081     * Set a listener to be invoked when the dialog is canceled.
1082     * <p>
1083     * This will only be invoked when the dialog is canceled, if the creator
1084     * needs to know when it is dismissed in general, use
1085     * {@link #setOnDismissListener}.
1086     *
1087     * @param listener The {@link DialogInterface.OnCancelListener} to use.
1088     */
1089    public void setOnCancelListener(final OnCancelListener listener) {
1090        if (mCancelAndDismissTaken != null) {
1091            throw new IllegalStateException(
1092                    "OnCancelListener is already taken by "
1093                    + mCancelAndDismissTaken + " and can not be replaced.");
1094        }
1095        if (listener != null) {
1096            mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
1097        } else {
1098            mCancelMessage = null;
1099        }
1100    }
1101
1102    /**
1103     * Set a message to be sent when the dialog is canceled.
1104     * @param msg The msg to send when the dialog is canceled.
1105     * @see #setOnCancelListener(android.content.DialogInterface.OnCancelListener)
1106     */
1107    public void setCancelMessage(final Message msg) {
1108        mCancelMessage = msg;
1109    }
1110
1111    /**
1112     * Set a listener to be invoked when the dialog is dismissed.
1113     * @param listener The {@link DialogInterface.OnDismissListener} to use.
1114     */
1115    public void setOnDismissListener(final OnDismissListener listener) {
1116        if (mCancelAndDismissTaken != null) {
1117            throw new IllegalStateException(
1118                    "OnDismissListener is already taken by "
1119                    + mCancelAndDismissTaken + " and can not be replaced.");
1120        }
1121        if (listener != null) {
1122            mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);
1123        } else {
1124            mDismissMessage = null;
1125        }
1126    }
1127
1128    /**
1129     * Sets a listener to be invoked when the dialog is shown.
1130     * @param listener The {@link DialogInterface.OnShowListener} to use.
1131     */
1132    public void setOnShowListener(OnShowListener listener) {
1133        if (listener != null) {
1134            mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);
1135        } else {
1136            mShowMessage = null;
1137        }
1138    }
1139
1140    /**
1141     * Set a message to be sent when the dialog is dismissed.
1142     * @param msg The msg to send when the dialog is dismissed.
1143     */
1144    public void setDismissMessage(final Message msg) {
1145        mDismissMessage = msg;
1146    }
1147
1148    /** @hide */
1149    public boolean takeCancelAndDismissListeners(String msg, final OnCancelListener cancel,
1150            final OnDismissListener dismiss) {
1151        if (mCancelAndDismissTaken != null) {
1152            mCancelAndDismissTaken = null;
1153        } else if (mCancelMessage != null || mDismissMessage != null) {
1154            return false;
1155        }
1156
1157        setOnCancelListener(cancel);
1158        setOnDismissListener(dismiss);
1159        mCancelAndDismissTaken = msg;
1160
1161        return true;
1162    }
1163
1164    /**
1165     * By default, this will use the owner Activity's suggested stream type.
1166     *
1167     * @see Activity#setVolumeControlStream(int)
1168     * @see #setOwnerActivity(Activity)
1169     */
1170    public final void setVolumeControlStream(int streamType) {
1171        getWindow().setVolumeControlStream(streamType);
1172    }
1173
1174    /**
1175     * @see Activity#getVolumeControlStream()
1176     */
1177    public final int getVolumeControlStream() {
1178        return getWindow().getVolumeControlStream();
1179    }
1180
1181    /**
1182     * Sets the callback that will be called if a key is dispatched to the dialog.
1183     */
1184    public void setOnKeyListener(final OnKeyListener onKeyListener) {
1185        mOnKeyListener = onKeyListener;
1186    }
1187
1188    private static final class ListenersHandler extends Handler {
1189        private WeakReference<DialogInterface> mDialog;
1190
1191        public ListenersHandler(Dialog dialog) {
1192            mDialog = new WeakReference<DialogInterface>(dialog);
1193        }
1194
1195        @Override
1196        public void handleMessage(Message msg) {
1197            switch (msg.what) {
1198                case DISMISS:
1199                    ((OnDismissListener) msg.obj).onDismiss(mDialog.get());
1200                    break;
1201                case CANCEL:
1202                    ((OnCancelListener) msg.obj).onCancel(mDialog.get());
1203                    break;
1204                case SHOW:
1205                    ((OnShowListener) msg.obj).onShow(mDialog.get());
1206                    break;
1207            }
1208        }
1209    }
1210}
1211