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