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