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