Debian Codegraph @

core/java/android/app/Dialog.java

raw symbols SCIP
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 */
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 */
189 public Dialog(@UiContext @NonNull Context context, @StyleRes int themeResId) {
190 this(context, themeResId, true);
191 }
192
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
228 protected Dialog(@NonNull Context context, boolean cancelable,
229 @Nullable Message cancelCallback) {
230 this(context);
231 mCancelable = cancelable;
232 mCancelMessage = cancelCallback;
233 }
234
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
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 */
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 */
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 */
282 public final @Nullable Activity getOwnerActivity() {
283 return mOwnerActivity;
284 }
285
286 /**
287 * @return Whether the dialog is currently showing.
288 */
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 */
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 */
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 */
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
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
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
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
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
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 */
449 protected void onCreate(Bundle savedInstanceState) {
450 }
451
452 /**
453 * Called when the dialog is starting.
454 */
455 protected void onStart() {
456 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
457 if (mContext != null
458 && WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) {
459 // Add onBackPressed as default back behavior.
460 mDefaultBackCallback = this::onBackPressed;
461 getOnBackInvokedDispatcher().registerSystemOnBackInvokedCallback(mDefaultBackCallback);
462 mDefaultBackCallback = null;
463 }
464 }
465
466 /**
467 * Called to tell you that you're stopping.
468 */
469 protected void onStop() {
470 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
471 if (mDefaultBackCallback != null) {
472 getOnBackInvokedDispatcher().unregisterOnBackInvokedCallback(mDefaultBackCallback);
473 }
474 }
475
476 private static final String DIALOG_SHOWING_TAG = "android:dialogShowing";
477 private static final String DIALOG_HIERARCHY_TAG = "android:dialogHierarchy";
478
479 /**
480 * Saves the state of the dialog into a bundle.
481 *
482 * The default implementation saves the state of its view hierarchy, so you'll
483 * likely want to call through to super if you override this to save additional
484 * state.
485 * @return A bundle with the state of the dialog.
486 */
487 public @NonNull Bundle onSaveInstanceState() {
488 Bundle bundle = new Bundle();
489 bundle.putBoolean(DIALOG_SHOWING_TAG, mShowing);
490 if (mCreated) {
491 bundle.putBundle(DIALOG_HIERARCHY_TAG, mWindow.saveHierarchyState());
492 }
493 return bundle;
494 }
495
496 /**
497 * Restore the state of the dialog from a previously saved bundle.
498 *
499 * The default implementation restores the state of the dialog's view
500 * hierarchy that was saved in the default implementation of {@link #onSaveInstanceState()},
501 * so be sure to call through to super when overriding unless you want to
502 * do all restoring of state yourself.
503 * @param savedInstanceState The state of the dialog previously saved by
504 * {@link #onSaveInstanceState()}.
505 */
506 public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
507 final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);
508 if (dialogHierarchyState == null) {
509 // dialog has never been shown, or onCreated, nothing to restore.
510 return;
511 }
512 dispatchOnCreate(savedInstanceState);
513 mWindow.restoreHierarchyState(dialogHierarchyState);
514 if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {
515 show();
516 }
517 }
518
519 /**
520 * Retrieve the current Window for the activity. This can be used to
521 * directly access parts of the Window API that are not available
522 * through Activity/Screen.
523 *
524 * @return Window The current window, or null if the activity is not
525 * visual.
526 */
527 public @Nullable Window getWindow() {
528 return mWindow;
529 }
530
531 /**
532 * Call {@link android.view.Window#getCurrentFocus} on the
533 * Window if this Activity to return the currently focused view.
534 *
535 * @return View The current View with focus or null.
536 *
537 * @see #getWindow
538 * @see android.view.Window#getCurrentFocus
539 */
540 public @Nullable View getCurrentFocus() {
541 return mWindow != null ? mWindow.getCurrentFocus() : null;
542 }
543
544 /**
545 * Finds the first descendant view with the given ID or {@code null} if the
546 * ID is invalid (< 0), there is no matching view in the hierarchy, or the
547 * dialog has not yet been fully created (for example, via {@link #show()}
548 * or {@link #create()}).
549 * <p>
550 * <strong>Note:</strong> In most cases -- depending on compiler support --
551 * the resulting view is automatically cast to the target class type. If
552 * the target class type is unconstrained, an explicit cast may be
553 * necessary.
554 *
555 * @param id the ID to search for
556 * @return a view with given ID if found, or {@code null} otherwise
557 * @see View#findViewById(int)
558 * @see Dialog#requireViewById(int)
559 */
560 @Nullable
561 public <T extends View> T findViewById(@IdRes int id) {
562 return mWindow.findViewById(id);
563 }
564
565 /**
566 * Finds the first descendant view with the given ID or throws an IllegalArgumentException if
567 * the ID is invalid (< 0), there is no matching view in the hierarchy, or the dialog has not
568 * yet been fully created (for example, via {@link #show()} or {@link #create()}).
569 * <p>
570 * <strong>Note:</strong> In most cases -- depending on compiler support --
571 * the resulting view is automatically cast to the target class type. If
572 * the target class type is unconstrained, an explicit cast may be
573 * necessary.
574 *
575 * @param id the ID to search for
576 * @return a view with given ID
577 * @see View#requireViewById(int)
578 * @see Dialog#findViewById(int)
579 */
580 @NonNull
581 public final <T extends View> T requireViewById(@IdRes int id) {
582 T view = findViewById(id);
583 if (view == null) {
584 throw new IllegalArgumentException("ID does not reference a View inside this Dialog");
585 }
586 return view;
587 }
588
589 /**
590 * Set the screen content from a layout resource. The resource will be
591 * inflated, adding all top-level views to the screen.
592 *
593 * @param layoutResID Resource ID to be inflated.
594 */
595 public void setContentView(@LayoutRes int layoutResID) {
596 mWindow.setContentView(layoutResID);
597 }
598
599 /**
600 * Set the screen content to an explicit view. This view is placed
601 * directly into the screen's view hierarchy. It can itself be a complex
602 * view hierarchy.
603 *
604 * @param view The desired content to display.
605 */
606 public void setContentView(@NonNull View view) {
607 mWindow.setContentView(view);
608 }
609
610 /**
611 * Set the screen content to an explicit view. This view is placed
612 * directly into the screen's view hierarchy. It can itself be a complex
613 * view hierarchy.
614 *
615 * @param view The desired content to display.
616 * @param params Layout parameters for the view.
617 */
618 public void setContentView(@NonNull View view, @Nullable ViewGroup.LayoutParams params) {
619 mWindow.setContentView(view, params);
620 }
621
622 /**
623 * Add an additional content view to the screen. Added after any existing
624 * ones in the screen -- existing views are NOT removed.
625 *
626 * @param view The desired content to display.
627 * @param params Layout parameters for the view.
628 */
629 public void addContentView(@NonNull View view, @Nullable ViewGroup.LayoutParams params) {
630 mWindow.addContentView(view, params);
631 }
632
633 /**
634 * Set the title text for this dialog's window.
635 *
636 * @param title The new text to display in the title.
637 */
638 public void setTitle(@Nullable CharSequence title) {
639 mWindow.setTitle(title);
640 mWindow.getAttributes().setTitle(title);
641 }
642
643 /**
644 * Set the title text for this dialog's window. The text is retrieved
645 * from the resources with the supplied identifier.
646 *
647 * @param titleId the title's text resource identifier
648 */
649 public void setTitle(@StringRes int titleId) {
650 setTitle(mContext.getText(titleId));
651 }
652
653 /**
654 * A key was pressed down.
655 * <p>
656 * If the focused view didn't want this event, this method is called.
657 * <p>
658 * Default implementation consumes {@link KeyEvent#KEYCODE_BACK KEYCODE_BACK}
659 * and, as of {@link android.os.Build.VERSION_CODES#P P}, {@link KeyEvent#KEYCODE_ESCAPE
660 * KEYCODE_ESCAPE} to later handle them in {@link #onKeyUp}.
661 *
662 * @see #onKeyUp
663 * @see android.view.KeyEvent
664 */
665 @Override
666 public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
667 if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) {
668 event.startTracking();
669 return true;
670 }
671
672 return false;
673 }
674
675 /**
676 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
677 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
678 * the event).
679 */
680 @Override
681 public boolean onKeyLongPress(int keyCode, @NonNull KeyEvent event) {
682 return false;
683 }
684
685 /**
686 * A key was released.
687 * <p>
688 * Default implementation consumes {@link KeyEvent#KEYCODE_BACK KEYCODE_BACK}
689 * and, as of {@link android.os.Build.VERSION_CODES#P P}, {@link KeyEvent#KEYCODE_ESCAPE
690 * KEYCODE_ESCAPE} to close the dialog.
691 *
692 * @see #onKeyDown
693 * @see android.view.KeyEvent
694 */
695 @Override
696 public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
697 if ((keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE)
698 && event.isTracking()
699 && !event.isCanceled()
700 && !WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) {
701 onBackPressed();
702 return true;
703 }
704 return false;
705 }
706
707 /**
708 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
709 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
710 * the event).
711 */
712 @Override
713 public boolean onKeyMultiple(int keyCode, int repeatCount, @NonNull KeyEvent event) {
714 return false;
715 }
716
717 /**
718 * Called when the dialog has detected the user's press of the back
719 * key. The default implementation simply cancels the dialog (only if
720 * it is cancelable), but you can override this to do whatever you want.
721 *
722 * <p>
723 * If you target version {@link android.os.Build.VERSION_CODES#TIRAMISU} or later, you
724 * should not use this method but register an {@link OnBackInvokedCallback} on an
725 * {@link OnBackInvokedDispatcher} that you can retrieve using
726 * {@link #getOnBackInvokedDispatcher()}. You should also set
727 * {@code android:enableOnBackInvokedCallback="true"} in the application manifest.
728 *
729 * <p>Alternatively, you
730 * can use {@code androidx.activity.ComponentDialog#getOnBackPressedDispatcher()}
731 * for backward compatibility.
732 *
733 * @deprecated Use {@link OnBackInvokedCallback} or
734 * {@code androidx.activity.OnBackPressedCallback} to handle back navigation instead.
735 * <p>
736 * Starting from Android 13 (API level 33), back event handling is
737 * moving to an ahead-of-time model and {@link #onBackPressed()} and
738 * {@link KeyEvent#KEYCODE_BACK} should not be used to handle back events (back gesture or
739 * back button click). Instead, an {@link OnBackInvokedCallback} should be registered using
740 * {@link Dialog#getOnBackInvokedDispatcher()}
741 * {@link OnBackInvokedDispatcher#registerOnBackInvokedCallback(int, OnBackInvokedCallback)
742 * .registerOnBackInvokedCallback(priority, callback)}.
743 */
744 @Deprecated
745 public void onBackPressed() {
746 if (mCancelable) {
747 cancel();
748 }
749 }
750
751 /**
752 * Called when a key shortcut event is not handled by any of the views in the Dialog.
753 * Override this method to implement global key shortcuts for the Dialog.
754 * Key shortcuts can also be implemented by setting the
755 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
756 *
757 * @param keyCode The value in event.getKeyCode().
758 * @param event Description of the key event.
759 * @return True if the key shortcut was handled.
760 */
761 public boolean onKeyShortcut(int keyCode, @NonNull KeyEvent event) {
762 return false;
763 }
764
765 /**
766 * Called when a touch screen event was not handled by any of the views
767 * under it. This is most useful to process touch events that happen outside
768 * of your window bounds, where there is no view to receive it.
769 *
770 * @param event The touch screen event being processed.
771 * @return Return true if you have consumed the event, false if you haven't.
772 * The default implementation will cancel the dialog when a touch
773 * happens outside of the window bounds.
774 */
775 public boolean onTouchEvent(@NonNull MotionEvent event) {
776 if (mCancelable && mShowing && mWindow.shouldCloseOnTouch(mContext, event)) {
777 cancel();
778 return true;
779 }
780
781 return false;
782 }
783
784 /**
785 * Called when the trackball was moved and not handled by any of the
786 * views inside of the activity. So, for example, if the trackball moves
787 * while focus is on a button, you will receive a call here because
788 * buttons do not normally do anything with trackball events. The call
789 * here happens <em>before</em> trackball movements are converted to
790 * DPAD key events, which then get sent back to the view hierarchy, and
791 * will be processed at the point for things like focus navigation.
792 *
793 * @param event The trackball event being processed.
794 *
795 * @return Return true if you have consumed the event, false if you haven't.
796 * The default implementation always returns false.
797 */
798 public boolean onTrackballEvent(@NonNull MotionEvent event) {
799 return false;
800 }
801
802 /**
803 * Called when a generic motion event was not handled by any of the
804 * views inside of the dialog.
805 * <p>
806 * Generic motion events describe joystick movements, mouse hovers, track pad
807 * touches, scroll wheel movements and other input events. The
808 * {@link MotionEvent#getSource() source} of the motion event specifies
809 * the class of input that was received. Implementations of this method
810 * must examine the bits in the source before processing the event.
811 * The following code example shows how this is done.
812 * </p><p>
813 * Generic motion events with source class
814 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
815 * are delivered to the view under the pointer. All other generic motion events are
816 * delivered to the focused view.
817 * </p><p>
818 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
819 * handle this event.
820 * </p>
821 *
822 * @param event The generic motion event being processed.
823 *
824 * @return Return true if you have consumed the event, false if you haven't.
825 * The default implementation always returns false.
826 */
827 public boolean onGenericMotionEvent(@NonNull MotionEvent event) {
828 return false;
829 }
830
831 @Override
832 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
833 if (mDecor != null) {
834 mWindowManager.updateViewLayout(mDecor, params);
835 }
836 }
837
838 @Override
839 public void onContentChanged() {
840 }
841
842 @Override
843 public void onWindowFocusChanged(boolean hasFocus) {
844 }
845
846 @Override
847 public void onAttachedToWindow() {
848 }
849
850 @Override
851 public void onDetachedFromWindow() {
852 }
853
854 /** @hide */
855 @Override
856 public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
857 dismiss();
858 }
859
860 /**
861 * Called to process key events. You can override this to intercept all
862 * key events before they are dispatched to the window. Be sure to call
863 * this implementation for key events that should be handled normally.
864 *
865 * @param event The key event.
866 *
867 * @return boolean Return true if this event was consumed.
868 */
869 @Override
870 public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
871 if ((mOnKeyListener != null) && (mOnKeyListener.onKey(this, event.getKeyCode(), event))) {
872 return true;
873 }
874 if (mWindow.superDispatchKeyEvent(event)) {
875 return true;
876 }
877 return event.dispatch(this, mDecor != null
878 ? mDecor.getKeyDispatcherState() : null, this);
879 }
880
881 /**
882 * Called to process a key shortcut event.
883 * You can override this to intercept all key shortcut events before they are
884 * dispatched to the window. Be sure to call this implementation for key shortcut
885 * events that should be handled normally.
886 *
887 * @param event The key shortcut event.
888 * @return True if this event was consumed.
889 */
890 @Override
891 public boolean dispatchKeyShortcutEvent(@NonNull KeyEvent event) {
892 if (mWindow.superDispatchKeyShortcutEvent(event)) {
893 return true;
894 }
895 return onKeyShortcut(event.getKeyCode(), event);
896 }
897
898 /**
899 * Called to process touch screen events. You can override this to
900 * intercept all touch screen events before they are dispatched to the
901 * window. Be sure to call this implementation for touch screen events
902 * that should be handled normally.
903 *
904 * @param ev The touch screen event.
905 *
906 * @return boolean Return true if this event was consumed.
907 */
908 @Override
909 public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
910 if (mWindow.superDispatchTouchEvent(ev)) {
911 return true;
912 }
913 return onTouchEvent(ev);
914 }
915
916 /**
917 * Called to process trackball events. You can override this to
918 * intercept all trackball events before they are dispatched to the
919 * window. Be sure to call this implementation for trackball events
920 * that should be handled normally.
921 *
922 * @param ev The trackball event.
923 *
924 * @return boolean Return true if this event was consumed.
925 */
926 @Override
927 public boolean dispatchTrackballEvent(@NonNull MotionEvent ev) {
928 if (mWindow.superDispatchTrackballEvent(ev)) {
929 return true;
930 }
931 return onTrackballEvent(ev);
932 }
933
934 /**
935 * Called to process generic motion events. You can override this to
936 * intercept all generic motion events before they are dispatched to the
937 * window. Be sure to call this implementation for generic motion events
938 * that should be handled normally.
939 *
940 * @param ev The generic motion event.
941 *
942 * @return boolean Return true if this event was consumed.
943 */
944 @Override
945 public boolean dispatchGenericMotionEvent(@NonNull MotionEvent ev) {
946 if (mWindow.superDispatchGenericMotionEvent(ev)) {
947 return true;
948 }
949 return onGenericMotionEvent(ev);
950 }
951
952 @Override
953 public boolean dispatchPopulateAccessibilityEvent(@NonNull AccessibilityEvent event) {
954 event.setClassName(getClass().getName());
955 event.setPackageName(mContext.getPackageName());
956
957 LayoutParams params = getWindow().getAttributes();
958 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
959 (params.height == LayoutParams.MATCH_PARENT);
960 event.setFullScreen(isFullScreen);
961
962 return false;
963 }
964
965 /**
966 * @see Activity#onCreatePanelView(int)
967 */
968 @Override
969 public View onCreatePanelView(int featureId) {
970 return null;
971 }
972
973 /**
974 * @see Activity#onCreatePanelMenu(int, Menu)
975 */
976 @Override
977 public boolean onCreatePanelMenu(int featureId, @NonNull Menu menu) {
978 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
979 return onCreateOptionsMenu(menu);
980 }
981
982 return false;
983 }
984
985 /**
986 * @see Activity#onPreparePanel(int, View, Menu)
987 */
988 @Override
989 public boolean onPreparePanel(int featureId, @Nullable View view, @NonNull Menu menu) {
990 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
991 return onPrepareOptionsMenu(menu) && menu.hasVisibleItems();
992 }
993 return true;
994 }
995
996 /**
997 * @see Activity#onMenuOpened(int, Menu)
998 */
999 @Override
1000 public boolean onMenuOpened(int featureId, @NonNull Menu menu) {
1001 if (featureId == Window.FEATURE_ACTION_BAR) {
1002 mActionBar.dispatchMenuVisibilityChanged(true);
1003 }
1004 return true;
1005 }
1006
1007 /**
1008 * @see Activity#onMenuItemSelected(int, MenuItem)
1009 */
1010 @Override
1011 public boolean onMenuItemSelected(int featureId, @NonNull MenuItem item) {
1012 return false;
1013 }
1014
1015 /**
1016 * @see Activity#onPanelClosed(int, Menu)
1017 */
1018 @Override
1019 public void onPanelClosed(int featureId, @NonNull Menu menu) {
1020 if (featureId == Window.FEATURE_ACTION_BAR) {
1021 mActionBar.dispatchMenuVisibilityChanged(false);
1022 }
1023 }
1024
1025 /**
1026 * It is usually safe to proxy this call to the owner activity's
1027 * {@link Activity#onCreateOptionsMenu(Menu)} if the client desires the same
1028 * menu for this Dialog.
1029 *
1030 * @see Activity#onCreateOptionsMenu(Menu)
1031 * @see #getOwnerActivity()
1032 */
1033 public boolean onCreateOptionsMenu(@NonNull Menu menu) {
1034 return true;
1035 }
1036
1037 /**
1038 * It is usually safe to proxy this call to the owner activity's
1039 * {@link Activity#onPrepareOptionsMenu(Menu)} if the client desires the
1040 * same menu for this Dialog.
1041 *
1042 * @see Activity#onPrepareOptionsMenu(Menu)
1043 * @see #getOwnerActivity()
1044 */
1045 public boolean onPrepareOptionsMenu(@NonNull Menu menu) {
1046 return true;
1047 }
1048
1049 /**
1050 * @see Activity#onOptionsItemSelected(MenuItem)
1051 */
1052 public boolean onOptionsItemSelected(@NonNull MenuItem item) {
1053 return false;
1054 }
1055
1056 /**
1057 * @see Activity#onOptionsMenuClosed(Menu)
1058 */
1059 public void onOptionsMenuClosed(@NonNull Menu menu) {
1060 }
1061
1062 /**
1063 * @see Activity#openOptionsMenu()
1064 */
1065 public void openOptionsMenu() {
1066 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
1067 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
1068 }
1069 }
1070
1071 /**
1072 * @see Activity#closeOptionsMenu()
1073 */
1074 public void closeOptionsMenu() {
1075 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
1076 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
1077 }
1078 }
1079
1080 /**
1081 * @see Activity#invalidateOptionsMenu()
1082 */
1083 public void invalidateOptionsMenu() {
1084 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
1085 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
1086 }
1087 }
1088
1089 /**
1090 * @see Activity#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)
1091 */
1092 @Override
1093 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1094 }
1095
1096 /**
1097 * @see Activity#registerForContextMenu(View)
1098 */
1099 public void registerForContextMenu(@NonNull View view) {
1100 view.setOnCreateContextMenuListener(this);
1101 }
1102
1103 /**
1104 * @see Activity#unregisterForContextMenu(View)
1105 */
1106 public void unregisterForContextMenu(@NonNull View view) {
1107 view.setOnCreateContextMenuListener(null);
1108 }
1109
1110 /**
1111 * @see Activity#openContextMenu(View)
1112 */
1113 public void openContextMenu(@NonNull View view) {
1114 view.showContextMenu();
1115 }
1116
1117 /**
1118 * @see Activity#onContextItemSelected(MenuItem)
1119 */
1120 public boolean onContextItemSelected(@NonNull MenuItem item) {
1121 return false;
1122 }
1123
1124 /**
1125 * @see Activity#onContextMenuClosed(Menu)
1126 */
1127 public void onContextMenuClosed(@NonNull Menu menu) {
1128 }
1129
1130 /**
1131 * This hook is called when the user signals the desire to start a search.
1132 */
1133 @Override
1134 public boolean onSearchRequested(@NonNull SearchEvent searchEvent) {
1135 mSearchEvent = searchEvent;
1136 return onSearchRequested();
1137 }
1138
1139 /**
1140 * This hook is called when the user signals the desire to start a search.
1141 */
1142 @Override
1143 public boolean onSearchRequested() {
1144 final SearchManager searchManager = (SearchManager) mContext
1145 .getSystemService(Context.SEARCH_SERVICE);
1146
1147 // associate search with owner activity
1148 final ComponentName appName = getAssociatedActivity();
1149 if (appName != null && searchManager.getSearchableInfo(appName) != null) {
1150 searchManager.startSearch(null, false, appName, null, false);
1151 dismiss();
1152 return true;
1153 } else {
1154 return false;
1155 }
1156 }
1157
1158 /**
1159 * During the onSearchRequested() callbacks, this function will return the
1160 * {@link SearchEvent} that triggered the callback, if it exists.
1161 *
1162 * @return SearchEvent The SearchEvent that triggered the {@link
1163 * #onSearchRequested} callback.
1164 */
1165 public final @Nullable SearchEvent getSearchEvent() {
1166 return mSearchEvent;
1167 }
1168
1169 @Override
1170 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
1171 if (mActionBar != null && mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
1172 return mActionBar.startActionMode(callback);
1173 }
1174 return null;
1175 }
1176
1177 @Override
1178 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
1179 try {
1180 mActionModeTypeStarting = type;
1181 return onWindowStartingActionMode(callback);
1182 } finally {
1183 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
1184 }
1185 }
1186
1187 /**
1188 * {@inheritDoc}
1189 *
1190 * Note that if you override this method you should always call through
1191 * to the superclass implementation by calling super.onActionModeStarted(mode).
1192 */
1193 @Override
1194 @CallSuper
1195 public void onActionModeStarted(ActionMode mode) {
1196 mActionMode = mode;
1197 }
1198
1199 /**
1200 * {@inheritDoc}
1201 *
1202 * Note that if you override this method you should always call through
1203 * to the superclass implementation by calling super.onActionModeFinished(mode).
1204 */
1205 @Override
1206 @CallSuper
1207 public void onActionModeFinished(ActionMode mode) {
1208 if (mode == mActionMode) {
1209 mActionMode = null;
1210 }
1211 }
1212
1213 /**
1214 * @return The activity associated with this dialog, or null if there is no associated activity.
1215 */
1216 private ComponentName getAssociatedActivity() {
1217 Activity activity = mOwnerActivity;
1218 Context context = getContext();
1219 while (activity == null && context != null) {
1220 if (context instanceof Activity) {
1221 activity = (Activity) context; // found it!
1222 } else {
1223 context = (context instanceof ContextWrapper) ?
1224 ((ContextWrapper) context).getBaseContext() : // unwrap one level
1225 null; // done
1226 }
1227 }
1228 return activity == null ? null : activity.getComponentName();
1229 }
1230
1231
1232 /**
1233 * Request that key events come to this dialog. Use this if your
1234 * dialog has no views with focus, but the dialog still wants
1235 * a chance to process key events.
1236 *
1237 * @param get true if the dialog should receive key events, false otherwise
1238 * @see android.view.Window#takeKeyEvents
1239 */
1240 public void takeKeyEvents(boolean get) {
1241 mWindow.takeKeyEvents(get);
1242 }
1243
1244 /**
1245 * Enable extended window features. This is a convenience for calling
1246 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
1247 *
1248 * @param featureId The desired feature as defined in
1249 * {@link android.view.Window}.
1250 * @return Returns true if the requested feature is supported and now
1251 * enabled.
1252 *
1253 * @see android.view.Window#requestFeature
1254 */
1255 public final boolean requestWindowFeature(int featureId) {
1256 return getWindow().requestFeature(featureId);
1257 }
1258
1259 /**
1260 * Convenience for calling
1261 * {@link android.view.Window#setFeatureDrawableResource}.
1262 */
1263 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
1264 getWindow().setFeatureDrawableResource(featureId, resId);
1265 }
1266
1267 /**
1268 * Convenience for calling
1269 * {@link android.view.Window#setFeatureDrawableUri}.
1270 */
1271 public final void setFeatureDrawableUri(int featureId, @Nullable Uri uri) {
1272 getWindow().setFeatureDrawableUri(featureId, uri);
1273 }
1274
1275 /**
1276 * Convenience for calling
1277 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
1278 */
1279 public final void setFeatureDrawable(int featureId, @Nullable Drawable drawable) {
1280 getWindow().setFeatureDrawable(featureId, drawable);
1281 }
1282
1283 /**
1284 * Convenience for calling
1285 * {@link android.view.Window#setFeatureDrawableAlpha}.
1286 */
1287 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
1288 getWindow().setFeatureDrawableAlpha(featureId, alpha);
1289 }
1290
1291 public @NonNull LayoutInflater getLayoutInflater() {
1292 return getWindow().getLayoutInflater();
1293 }
1294
1295 /**
1296 * Sets whether this dialog is cancelable with the
1297 * {@link KeyEvent#KEYCODE_BACK BACK} key.
1298 */
1299 public void setCancelable(boolean flag) {
1300 mCancelable = flag;
1301 }
1302
1303 /**
1304 * Sets whether this dialog is canceled when touched outside the window's
1305 * bounds. If setting to true, the dialog is set to be cancelable if not
1306 * already set.
1307 *
1308 * @param cancel Whether the dialog should be canceled when touched outside
1309 * the window.
1310 */
1311 public void setCanceledOnTouchOutside(boolean cancel) {
1312 if (cancel && !mCancelable) {
1313 mCancelable = true;
1314 }
1315
1316 mWindow.setCloseOnTouchOutside(cancel);
1317 }
1318
1319 /**
1320 * Cancel the dialog. This is essentially the same as calling {@link #dismiss()}, but it will
1321 * also call your {@link DialogInterface.OnCancelListener} (if registered).
1322 */
1323 @Override
1324 public void cancel() {
1325 if (!mCanceled && mCancelMessage != null) {
1326 mCanceled = true;
1327 // Obtain a new message so this dialog can be re-used
1328 Message.obtain(mCancelMessage).sendToTarget();
1329 }
1330 dismiss();
1331 }
1332
1333 /**
1334 * Set a listener to be invoked when the dialog is canceled.
1335 *
1336 * <p>This will only be invoked when the dialog is canceled.
1337 * Cancel events alone will not capture all ways that
1338 * the dialog might be dismissed. If the creator needs
1339 * to know when a dialog is dismissed in general, use
1340 * {@link #setOnDismissListener}.</p>
1341 *
1342 * @param listener The {@link DialogInterface.OnCancelListener} to use.
1343 */
1344 public void setOnCancelListener(@Nullable OnCancelListener listener) {
1345 if (mCancelAndDismissTaken != null) {
1346 throw new IllegalStateException(
1347 "OnCancelListener is already taken by "
1348 + mCancelAndDismissTaken + " and can not be replaced.");
1349 }
1350 if (listener != null) {
1351 mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
1352 } else {
1353 mCancelMessage = null;
1354 }
1355 }
1356
1357 /**
1358 * Set a message to be sent when the dialog is canceled.
1359 * @param msg The msg to send when the dialog is canceled.
1360 * @see #setOnCancelListener(android.content.DialogInterface.OnCancelListener)
1361 */
1362 public void setCancelMessage(@Nullable Message msg) {
1363 mCancelMessage = msg;
1364 }
1365
1366 /**
1367 * Set a listener to be invoked when the dialog is dismissed.
1368 * @param listener The {@link DialogInterface.OnDismissListener} to use.
1369 */
1370 public void setOnDismissListener(@Nullable OnDismissListener listener) {
1371 if (mCancelAndDismissTaken != null) {
1372 throw new IllegalStateException(
1373 "OnDismissListener is already taken by "
1374 + mCancelAndDismissTaken + " and can not be replaced.");
1375 }
1376 if (listener != null) {
1377 mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);
1378 } else {
1379 mDismissMessage = null;
1380 }
1381 }
1382
1383 /**
1384 * Sets a listener to be invoked when the dialog is shown.
1385 * @param listener The {@link DialogInterface.OnShowListener} to use.
1386 */
1387 public void setOnShowListener(@Nullable OnShowListener listener) {
1388 if (listener != null) {
1389 mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);
1390 } else {
1391 mShowMessage = null;
1392 }
1393 }
1394
1395 /**
1396 * Set a message to be sent when the dialog is dismissed.
1397 * @param msg The msg to send when the dialog is dismissed.
1398 */
1399 public void setDismissMessage(@Nullable Message msg) {
1400 mDismissMessage = msg;
1401 }
1402
1403 /**
1404 * Set a {@link Runnable} to run when this dialog is dismissed instead of directly dismissing
1405 * it. This allows to animate the dialog in its window before dismissing it.
1406 *
1407 * Note that {@code override} should always end up calling this method with {@code null}
1408 * followed by a call to {@link #dismiss() dismiss} to actually dismiss the dialog.
1409 *
1410 * @see #dismiss()
1411 *
1412 * @hide
1413 */
1414 public void setDismissOverride(@Nullable Runnable override) {
1415 mDismissOverride = override;
1416 }
1417
1418 /** @hide */
1419 public boolean takeCancelAndDismissListeners(@Nullable String msg,
1420 @Nullable OnCancelListener cancel, @Nullable OnDismissListener dismiss) {
1421 if (mCancelAndDismissTaken != null) {
1422 mCancelAndDismissTaken = null;
1423 } else if (mCancelMessage != null || mDismissMessage != null) {
1424 return false;
1425 }
1426
1427 setOnCancelListener(cancel);
1428 setOnDismissListener(dismiss);
1429 mCancelAndDismissTaken = msg;
1430
1431 return true;
1432 }
1433
1434 /**
1435 * By default, this will use the owner Activity's suggested stream type.
1436 *
1437 * @see Activity#setVolumeControlStream(int)
1438 * @see #setOwnerActivity(Activity)
1439 */
1440 public final void setVolumeControlStream(int streamType) {
1441 getWindow().setVolumeControlStream(streamType);
1442 }
1443
1444 /**
1445 * @see Activity#getVolumeControlStream()
1446 */
1447 public final int getVolumeControlStream() {
1448 return getWindow().getVolumeControlStream();
1449 }
1450
1451 /**
1452 * Sets the callback that will be called if a key is dispatched to the dialog.
1453 */
1454 public void setOnKeyListener(@Nullable OnKeyListener onKeyListener) {
1455 mOnKeyListener = onKeyListener;
1456 }
1457
1458 private static final class ListenersHandler extends Handler {
1459 private final WeakReference<DialogInterface> mDialog;
1460
1461 public ListenersHandler(Dialog dialog) {
1462 mDialog = new WeakReference<>(dialog);
1463 }
1464
1465 @Override
1466 public void handleMessage(Message msg) {
1467 switch (msg.what) {
1468 case DISMISS:
1469 ((OnDismissListener) msg.obj).onDismiss(mDialog.get());
1470 break;
1471 case CANCEL:
1472 ((OnCancelListener) msg.obj).onCancel(mDialog.get());
1473 break;
1474 case SHOW:
1475 ((OnShowListener) msg.obj).onShow(mDialog.get());
1476 break;
1477 }
1478 }
1479 }
1480
1481 /**
1482 * Returns the {@link OnBackInvokedDispatcher} instance associated with the window that this
1483 * dialog is attached to.
1484 */
1485 @NonNull
1486 public OnBackInvokedDispatcher getOnBackInvokedDispatcher() {
1487 return mWindow.getOnBackInvokedDispatcher();
1488 }
1489 }