• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 androidx.core.app;
18 
19 import android.app.Activity;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentSender;
23 import android.content.pm.PackageManager;
24 import android.graphics.Matrix;
25 import android.graphics.RectF;
26 import android.net.Uri;
27 import android.os.Build;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.os.Looper;
31 import android.os.Parcelable;
32 import android.view.DragEvent;
33 import android.view.View;
34 
35 import androidx.annotation.IdRes;
36 import androidx.annotation.IntRange;
37 import androidx.annotation.NonNull;
38 import androidx.annotation.Nullable;
39 import androidx.annotation.RequiresApi;
40 import androidx.annotation.RestrictTo;
41 import androidx.core.content.ContextCompat;
42 import androidx.core.view.DragAndDropPermissionsCompat;
43 
44 import java.util.List;
45 import java.util.Map;
46 
47 /**
48  * Helper for accessing features in {@link android.app.Activity}.
49  */
50 public class ActivityCompat extends ContextCompat {
51 
52     /**
53      * This interface is the contract for receiving the results for permission requests.
54      */
55     public interface OnRequestPermissionsResultCallback {
56 
57         /**
58          * Callback for the result from requesting permissions. This method
59          * is invoked for every call on {@link #requestPermissions(android.app.Activity,
60          * String[], int)}.
61          * <p>
62          * <strong>Note:</strong> It is possible that the permissions request interaction
63          * with the user is interrupted. In this case you will receive empty permissions
64          * and results arrays which should be treated as a cancellation.
65          * </p>
66          *
67          * @param requestCode The request code passed in {@link #requestPermissions(
68          * android.app.Activity, String[], int)}
69          * @param permissions The requested permissions. Never null.
70          * @param grantResults The grant results for the corresponding permissions
71          *     which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
72          *     or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
73          *
74          * @see #requestPermissions(android.app.Activity, String[], int)
75          */
onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)76         void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
77                 @NonNull int[] grantResults);
78     }
79 
80     /**
81      * Customizable delegate that allows delegating permission compatibility methods to a custom
82      * implementation.
83      *
84      * <p>
85      *     To delegate permission compatibility methods to a custom class, implement this interface,
86      *     and call {@code ActivityCompat.setPermissionCompatDelegate(delegate);}. All future calls
87      *     to the permission compatibility methods in this class will first check whether the
88      *     delegate can handle the method call, and invoke the corresponding method if it can.
89      * </p>
90      */
91     public interface PermissionCompatDelegate {
92 
93         /**
94          * Determines whether the delegate should handle
95          * {@link ActivityCompat#requestPermissions(Activity, String[], int)}, and request
96          * permissions if applicable. If this method returns true, it means that permission
97          * request is successfully handled by the delegate, and platform should not perform any
98          * further requests for permission.
99          *
100          * @param activity The target activity.
101          * @param permissions The requested permissions. Must me non-null and not empty.
102          * @param requestCode Application specific request code to match with a result reported to
103          *    {@link
104          *    OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}.
105          *    Should be >= 0.
106          *
107          * @return Whether the delegate has handled the permission request.
108          * @see ActivityCompat#requestPermissions(Activity, String[], int)
109          */
requestPermissions(@onNull Activity activity, @NonNull String[] permissions, @IntRange(from = 0) int requestCode)110         boolean requestPermissions(@NonNull Activity activity,
111                 @NonNull String[] permissions, @IntRange(from = 0) int requestCode);
112 
113         /**
114          * Determines whether the delegate should handle the permission request as part of
115          * {@code FragmentActivity#onActivityResult(int, int, Intent)}. If this method returns true,
116          * it means that activity result is successfully handled by the delegate, and no further
117          * action is needed on this activity result.
118          *
119          * @param activity    The target Activity.
120          * @param requestCode The integer request code originally supplied to
121          *                    {@code startActivityForResult()}, allowing you to identify who this
122          *                    result came from.
123          * @param resultCode  The integer result code returned by the child activity
124          *                    through its {@code }setResult()}.
125          * @param data        An Intent, which can return result data to the caller
126          *                    (various data can be attached to Intent "extras").
127          *
128          * @return Whether the delegate has handled the activity result.
129          * @see ActivityCompat#requestPermissions(Activity, String[], int)
130          */
onActivityResult(@onNull Activity activity, @IntRange(from = 0) int requestCode, int resultCode, @Nullable Intent data)131         boolean onActivityResult(@NonNull Activity activity,
132                 @IntRange(from = 0) int requestCode, int resultCode, @Nullable Intent data);
133     }
134 
135     /**
136      * @hide
137      */
138     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
139     public interface RequestPermissionsRequestCodeValidator {
validateRequestPermissionsRequestCode(int requestCode)140         void validateRequestPermissionsRequestCode(int requestCode);
141     }
142 
143     private static PermissionCompatDelegate sDelegate;
144 
145     /**
146      * This class should not be instantiated, but the constructor must be
147      * visible for the class to be extended (as in support-v13).
148      */
ActivityCompat()149     protected ActivityCompat() {
150         // Not publicly instantiable, but may be extended.
151     }
152 
153     /**
154      * Sets the permission delegate for {@code ActivityCompat}. Replaces the previously set
155      * delegate.
156      *
157      * @param delegate The delegate to be set. {@code null} to clear the set delegate.
158      */
setPermissionCompatDelegate( @ullable PermissionCompatDelegate delegate)159     public static void setPermissionCompatDelegate(
160             @Nullable PermissionCompatDelegate delegate) {
161         sDelegate = delegate;
162     }
163 
164     /**
165      * @hide
166      */
167     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
getPermissionCompatDelegate()168     public static PermissionCompatDelegate getPermissionCompatDelegate() {
169         return sDelegate;
170     }
171 
172     /**
173      * Invalidate the activity's options menu, if able.
174      *
175      * <p>Before API level 11 (Android 3.0/Honeycomb) the lifecycle of the
176      * options menu was controlled primarily by the user's operation of
177      * the hardware menu key. When the user presses down on the menu key
178      * for the first time the menu was created and prepared by calls
179      * to {@link Activity#onCreateOptionsMenu(android.view.Menu)} and
180      * {@link Activity#onPrepareOptionsMenu(android.view.Menu)} respectively.
181      * Subsequent presses of the menu key kept the existing instance of the
182      * Menu itself and called {@link Activity#onPrepareOptionsMenu(android.view.Menu)}
183      * to give the activity an opportunity to contextually alter the menu
184      * before the menu panel was shown.</p>
185      *
186      * <p>In Android 3.0+ the Action Bar forces the options menu to be built early
187      * so that items chosen to show as actions may be displayed when the activity
188      * first becomes visible. The Activity method invalidateOptionsMenu forces
189      * the entire menu to be destroyed and recreated from
190      * {@link Activity#onCreateOptionsMenu(android.view.Menu)}, offering a similar
191      * though heavier-weight opportunity to change the menu's contents. Normally
192      * this functionality is used to support a changing configuration of Fragments.</p>
193      *
194      * <p>Applications may use this support helper to signal a significant change in
195      * activity state that should cause the options menu to be rebuilt. If the app
196      * is running on an older platform version that does not support menu invalidation
197      * the app will still receive {@link Activity#onPrepareOptionsMenu(android.view.Menu)}
198      * the next time the user presses the menu key and this method will return false.
199      * If this method returns true the options menu was successfully invalidated.</p>
200      *
201      * @param activity Invalidate the options menu of this activity
202      * @return true if this operation was supported and it completed; false if it was not available.
203      * @deprecated Use {@link Activity#invalidateOptionsMenu()} directly.
204      */
205     @Deprecated
invalidateOptionsMenu(Activity activity)206     public static boolean invalidateOptionsMenu(Activity activity) {
207         activity.invalidateOptionsMenu();
208         return true;
209     }
210 
211     /**
212      * Start new activity with options, if able, for which you would like a
213      * result when it finished.
214      *
215      * <p>In Android 4.1+ additional options were introduced to allow for more
216      * control on activity launch animations. Applications can use this method
217      * along with {@link ActivityOptionsCompat} to use these animations when
218      * available. When run on versions of the platform where this feature does
219      * not exist the activity will be launched normally.</p>
220      *
221      * @param activity Origin activity to launch from.
222      * @param intent The description of the activity to start.
223      * @param requestCode If >= 0, this code will be returned in
224      *                   onActivityResult() when the activity exits.
225      * @param options Additional options for how the Activity should be started.
226      *                May be null if there are no options. See
227      *                {@link ActivityOptionsCompat} for how to build the Bundle
228      *                supplied here; there are no supported definitions for
229      *                building it manually.
230      */
startActivityForResult(@onNull Activity activity, @NonNull Intent intent, int requestCode, @Nullable Bundle options)231     public static void startActivityForResult(@NonNull Activity activity, @NonNull Intent intent,
232             int requestCode, @Nullable Bundle options) {
233         if (Build.VERSION.SDK_INT >= 16) {
234             activity.startActivityForResult(intent, requestCode, options);
235         } else {
236             activity.startActivityForResult(intent, requestCode);
237         }
238     }
239 
240     /**
241      * Start new IntentSender with options, if able, for which you would like a
242      * result when it finished.
243      *
244      * <p>In Android 4.1+ additional options were introduced to allow for more
245      * control on activity launch animations. Applications can use this method
246      * along with {@link ActivityOptionsCompat} to use these animations when
247      * available. When run on versions of the platform where this feature does
248      * not exist the activity will be launched normally.</p>
249      *
250      * @param activity Origin activity to launch from.
251      * @param intent The IntentSender to launch.
252      * @param requestCode If >= 0, this code will be returned in
253      *                   onActivityResult() when the activity exits.
254      * @param fillInIntent If non-null, this will be provided as the
255      *                     intent parameter to {@link IntentSender#sendIntent}.
256      * @param flagsMask Intent flags in the original IntentSender that you
257      *                  would like to change.
258      * @param flagsValues Desired values for any bits set in <var>flagsMask</var>
259      * @param extraFlags Always set to 0.
260      * @param options Additional options for how the Activity should be started.
261      *                May be null if there are no options. See
262      *                {@link ActivityOptionsCompat} for how to build the Bundle
263      *                supplied here; there are no supported definitions for
264      *                building it manually.
265      */
startIntentSenderForResult(@onNull Activity activity, @NonNull IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options)266     public static void startIntentSenderForResult(@NonNull Activity activity,
267             @NonNull IntentSender intent, int requestCode, @Nullable Intent fillInIntent,
268             int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options)
269             throws IntentSender.SendIntentException {
270         if (Build.VERSION.SDK_INT >= 16) {
271             activity.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
272                     flagsValues, extraFlags, options);
273         } else {
274             activity.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
275                     flagsValues, extraFlags);
276         }
277     }
278 
279     /**
280      * Finish this activity, and tries to finish all activities immediately below it
281      * in the current task that have the same affinity.
282      *
283      * <p>On Android 4.1+ calling this method will call through to the native version of this
284      * method. For other platforms {@link Activity#finish()} will be called instead.</p>
285      */
finishAffinity(@onNull Activity activity)286     public static void finishAffinity(@NonNull Activity activity) {
287         if (Build.VERSION.SDK_INT >= 16) {
288             activity.finishAffinity();
289         } else {
290             activity.finish();
291         }
292     }
293 
294     /**
295      * Reverses the Activity Scene entry Transition and triggers the calling Activity
296      * to reverse its exit Transition. When the exit Transition completes,
297      * {@link Activity#finish()} is called. If no entry Transition was used, finish() is called
298      * immediately and the Activity exit Transition is run.
299      *
300      * <p>On Android 4.4 or lower, this method only finishes the Activity with no
301      * special exit transition.</p>
302      */
finishAfterTransition(@onNull Activity activity)303     public static void finishAfterTransition(@NonNull Activity activity) {
304         if (Build.VERSION.SDK_INT >= 21) {
305             activity.finishAfterTransition();
306         } else {
307             activity.finish();
308         }
309     }
310 
311     /**
312      * Return information about who launched this activity.  If the launching Intent
313      * contains an {@link Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
314      * that will be returned as-is; otherwise, if known, an
315      * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
316      * package name that started the Intent will be returned.  This may return null if no
317      * referrer can be identified -- it is neither explicitly specified, nor is it known which
318      * application package was involved.
319      *
320      * <p>If called while inside the handling of {@link Activity#onNewIntent}, this function will
321      * return the referrer that submitted that new intent to the activity.  Otherwise, it
322      * always returns the referrer of the original Intent.</p>
323      *
324      * <p>Note that this is <em>not</em> a security feature -- you can not trust the
325      * referrer information, applications can spoof it.</p>
326      */
327     @Nullable
getReferrer(@onNull Activity activity)328     public static Uri getReferrer(@NonNull Activity activity) {
329         if (Build.VERSION.SDK_INT >= 22) {
330             return activity.getReferrer();
331         }
332         Intent intent = activity.getIntent();
333         Uri referrer = intent.getParcelableExtra("android.intent.extra.REFERRER");
334         if (referrer != null) {
335             return referrer;
336         }
337         String referrerName = intent.getStringExtra("android.intent.extra.REFERRER_NAME");
338         if (referrerName != null) {
339             return Uri.parse(referrerName);
340         }
341         return null;
342     }
343 
344     /**
345      * Finds a view that was identified by the {@code android:id} XML attribute that was processed
346      * in {@link Activity#onCreate}, or throws an IllegalArgumentException if the ID is invalid, or
347      * there is no matching view in the hierarchy.
348      * <p>
349      * <strong>Note:</strong> In most cases -- depending on compiler support --
350      * the resulting view is automatically cast to the target class type. If
351      * the target class type is unconstrained, an explicit cast may be
352      * necessary.
353      *
354      * @param id the ID to search for
355      * @return a view with given ID
356      * @see Activity#findViewById(int)
357      * @see androidx.core.view.ViewCompat#requireViewById(View, int)
358      */
359     @SuppressWarnings("TypeParameterUnusedInFormals")
360     @NonNull
requireViewById(@onNull Activity activity, @IdRes int id)361     public static <T extends View> T requireViewById(@NonNull Activity activity, @IdRes int id) {
362         // TODO: use and link to Activity#requireViewById() directly, once available
363         T view = activity.findViewById(id);
364         if (view == null) {
365             throw new IllegalArgumentException("ID does not reference a View inside this Activity");
366         }
367         return view;
368     }
369 
370     /**
371      * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
372      * android.view.View, String)} was used to start an Activity, <var>callback</var>
373      * will be called to handle shared elements on the <i>launched</i> Activity. This requires
374      * {@link android.view.Window#FEATURE_CONTENT_TRANSITIONS}.
375      *
376      * @param callback Used to manipulate shared element transitions on the launched Activity.
377      */
setEnterSharedElementCallback(@onNull Activity activity, @Nullable SharedElementCallback callback)378     public static void setEnterSharedElementCallback(@NonNull Activity activity,
379             @Nullable SharedElementCallback callback) {
380         if (Build.VERSION.SDK_INT >= 23) {
381             android.app.SharedElementCallback frameworkCallback = callback != null
382                     ? new SharedElementCallback23Impl(callback)
383                     : null;
384             activity.setEnterSharedElementCallback(frameworkCallback);
385         } else if (Build.VERSION.SDK_INT >= 21) {
386             android.app.SharedElementCallback frameworkCallback = callback != null
387                     ? new SharedElementCallback21Impl(callback)
388                     : null;
389             activity.setEnterSharedElementCallback(frameworkCallback);
390         }
391     }
392 
393     /**
394      * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
395      * android.view.View, String)} was used to start an Activity, <var>callback</var>
396      * will be called to handle shared elements on the <i>launching</i> Activity. Most
397      * calls will only come when returning from the started Activity.
398      * This requires {@link android.view.Window#FEATURE_CONTENT_TRANSITIONS}.
399      *
400      * @param callback Used to manipulate shared element transitions on the launching Activity.
401      */
setExitSharedElementCallback(@onNull Activity activity, @Nullable SharedElementCallback callback)402     public static void setExitSharedElementCallback(@NonNull Activity activity,
403             @Nullable SharedElementCallback callback) {
404         if (Build.VERSION.SDK_INT >= 23) {
405             android.app.SharedElementCallback frameworkCallback = callback != null
406                     ? new SharedElementCallback23Impl(callback)
407                     : null;
408             activity.setExitSharedElementCallback(frameworkCallback);
409         } else if (Build.VERSION.SDK_INT >= 21) {
410             android.app.SharedElementCallback frameworkCallback = callback != null
411                     ? new SharedElementCallback21Impl(callback)
412                     : null;
413             activity.setExitSharedElementCallback(frameworkCallback);
414         }
415     }
416 
postponeEnterTransition(@onNull Activity activity)417     public static void postponeEnterTransition(@NonNull Activity activity) {
418         if (Build.VERSION.SDK_INT >= 21) {
419             activity.postponeEnterTransition();
420         }
421     }
422 
startPostponedEnterTransition(@onNull Activity activity)423     public static void startPostponedEnterTransition(@NonNull Activity activity) {
424         if (Build.VERSION.SDK_INT >= 21) {
425             activity.startPostponedEnterTransition();
426         }
427     }
428 
429     /**
430      * Requests permissions to be granted to this application. These permissions
431      * must be requested in your manifest, they should not be granted to your app,
432      * and they should have protection level {@link android.content.pm.PermissionInfo
433      * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
434      * the platform or a third-party app.
435      * <p>
436      * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
437      * are granted at install time if requested in the manifest. Signature permissions
438      * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
439      * install time if requested in the manifest and the signature of your app matches
440      * the signature of the app declaring the permissions.
441      * </p>
442      * <p>
443      * If your app does not have the requested permissions the user will be presented
444      * with UI for accepting them. After the user has accepted or rejected the
445      * requested permissions you will receive a callback reporting whether the
446      * permissions were granted or not. Your activity has to implement {@link
447      * androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback}
448      * and the results of permission requests will be delivered to its {@link
449      * androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(
450      * int, String[], int[])} method.
451      * </p>
452      * <p>
453      * Note that requesting a permission does not guarantee it will be granted and
454      * your app should be able to run without having this permission.
455      * </p>
456      * <p>
457      * This method may start an activity allowing the user to choose which permissions
458      * to grant and which to reject. Hence, you should be prepared that your activity
459      * may be paused and resumed. Further, granting some permissions may require
460      * a restart of you application. In such a case, the system will recreate the
461      * activity stack before delivering the result to your
462      * {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}.
463      * </p>
464      * <p>
465      * When checking whether you have a permission you should use {@link
466      * #checkSelfPermission(android.content.Context, String)}.
467      * </p>
468      * <p>
469      * Calling this API for permissions already granted to your app would show UI
470      * to the user to decided whether the app can still hold these permissions. This
471      * can be useful if the way your app uses the data guarded by the permissions
472      * changes significantly.
473      * </p>
474      * <p>
475      * You cannot request a permission if your activity sets {@link
476      * android.R.attr#noHistory noHistory} to <code>true</code> in the manifest
477      * because in this case the activity would not receive result callbacks including
478      * {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}.
479      * </p>
480      * <p>
481      * The <a href="http://developer.android.com/samples/RuntimePermissions/index.html">
482      * RuntimePermissions</a> sample app demonstrates how to use this method to
483      * request permissions at run time.
484      * </p>
485      *
486      * @param activity The target activity.
487      * @param permissions The requested permissions. Must me non-null and not empty.
488      * @param requestCode Application specific request code to match with a result
489      *    reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}.
490      *    Should be >= 0.
491      *
492      * @see OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])
493      * @see #checkSelfPermission(android.content.Context, String)
494      * @see #shouldShowRequestPermissionRationale(android.app.Activity, String)
495      */
requestPermissions(final @NonNull Activity activity, final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode)496     public static void requestPermissions(final @NonNull Activity activity,
497             final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode) {
498         if (sDelegate != null
499                 && sDelegate.requestPermissions(activity, permissions, requestCode)) {
500             // Delegate has handled the permission request.
501             return;
502         }
503 
504         if (Build.VERSION.SDK_INT >= 23) {
505             if (activity instanceof RequestPermissionsRequestCodeValidator) {
506                 ((RequestPermissionsRequestCodeValidator) activity)
507                         .validateRequestPermissionsRequestCode(requestCode);
508             }
509             activity.requestPermissions(permissions, requestCode);
510         } else if (activity instanceof OnRequestPermissionsResultCallback) {
511             Handler handler = new Handler(Looper.getMainLooper());
512             handler.post(new Runnable() {
513                 @Override
514                 public void run() {
515                     final int[] grantResults = new int[permissions.length];
516 
517                     PackageManager packageManager = activity.getPackageManager();
518                     String packageName = activity.getPackageName();
519 
520                     final int permissionCount = permissions.length;
521                     for (int i = 0; i < permissionCount; i++) {
522                         grantResults[i] = packageManager.checkPermission(
523                                 permissions[i], packageName);
524                     }
525 
526                     ((OnRequestPermissionsResultCallback) activity).onRequestPermissionsResult(
527                             requestCode, permissions, grantResults);
528                 }
529             });
530         }
531     }
532 
533     /**
534      * Gets whether you should show UI with rationale for requesting a permission.
535      * You should do this only if you do not have the permission and the context in
536      * which the permission is requested does not clearly communicate to the user
537      * what would be the benefit from granting this permission.
538      * <p>
539      * For example, if you write a camera app, requesting the camera permission
540      * would be expected by the user and no rationale for why it is requested is
541      * needed. If however, the app needs location for tagging photos then a non-tech
542      * savvy user may wonder how location is related to taking photos. In this case
543      * you may choose to show UI with rationale of requesting this permission.
544      * </p>
545      *
546      * @param activity The target activity.
547      * @param permission A permission your app wants to request.
548      * @return Whether you can show permission rationale UI.
549      *
550      * @see #checkSelfPermission(android.content.Context, String)
551      * @see #requestPermissions(android.app.Activity, String[], int)
552      */
shouldShowRequestPermissionRationale(@onNull Activity activity, @NonNull String permission)553     public static boolean shouldShowRequestPermissionRationale(@NonNull Activity activity,
554             @NonNull String permission) {
555         if (Build.VERSION.SDK_INT >= 23) {
556             return activity.shouldShowRequestPermissionRationale(permission);
557         }
558         return false;
559     }
560 
561     /**
562      * Create {@link DragAndDropPermissionsCompat} object bound to this activity and controlling
563      * the access permissions for content URIs associated with the {@link android.view.DragEvent}.
564      * @param dragEvent Drag event to request permission for
565      * @return The {@link DragAndDropPermissionsCompat} object used to control access to the content
566      * URIs. {@code null} if no content URIs are associated with the event or if permissions could
567      * not be granted.
568      */
569     @Nullable
requestDragAndDropPermissions(Activity activity, DragEvent dragEvent)570     public static DragAndDropPermissionsCompat requestDragAndDropPermissions(Activity activity,
571             DragEvent dragEvent) {
572         return DragAndDropPermissionsCompat.request(activity, dragEvent);
573     }
574 
575     @RequiresApi(21)
576     private static class SharedElementCallback21Impl extends android.app.SharedElementCallback {
577 
578         protected SharedElementCallback mCallback;
579 
SharedElementCallback21Impl(SharedElementCallback callback)580         SharedElementCallback21Impl(SharedElementCallback callback) {
581             mCallback = callback;
582         }
583 
584         @Override
onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots)585         public void onSharedElementStart(List<String> sharedElementNames,
586                 List<View> sharedElements, List<View> sharedElementSnapshots) {
587             mCallback.onSharedElementStart(sharedElementNames, sharedElements,
588                     sharedElementSnapshots);
589         }
590 
591         @Override
onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots)592         public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements,
593                 List<View> sharedElementSnapshots) {
594             mCallback.onSharedElementEnd(sharedElementNames, sharedElements,
595                     sharedElementSnapshots);
596         }
597 
598         @Override
onRejectSharedElements(List<View> rejectedSharedElements)599         public void onRejectSharedElements(List<View> rejectedSharedElements) {
600             mCallback.onRejectSharedElements(rejectedSharedElements);
601         }
602 
603         @Override
onMapSharedElements(List<String> names, Map<String, View> sharedElements)604         public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
605             mCallback.onMapSharedElements(names, sharedElements);
606         }
607 
608         @Override
onCaptureSharedElementSnapshot(View sharedElement, Matrix viewToGlobalMatrix, RectF screenBounds)609         public Parcelable onCaptureSharedElementSnapshot(View sharedElement,
610                 Matrix viewToGlobalMatrix, RectF screenBounds) {
611             return mCallback.onCaptureSharedElementSnapshot(sharedElement, viewToGlobalMatrix,
612                     screenBounds);
613         }
614 
615         @Override
onCreateSnapshotView(Context context, Parcelable snapshot)616         public View onCreateSnapshotView(Context context, Parcelable snapshot) {
617             return mCallback.onCreateSnapshotView(context, snapshot);
618         }
619     }
620 
621     @RequiresApi(23)
622     private static class SharedElementCallback23Impl extends SharedElementCallback21Impl {
SharedElementCallback23Impl(SharedElementCallback callback)623         SharedElementCallback23Impl(SharedElementCallback callback) {
624             super(callback);
625         }
626 
627         @Override
onSharedElementsArrived(List<String> sharedElementNames, List<View> sharedElements, final OnSharedElementsReadyListener listener)628         public void onSharedElementsArrived(List<String> sharedElementNames,
629                 List<View> sharedElements, final OnSharedElementsReadyListener listener) {
630             mCallback.onSharedElementsArrived(sharedElementNames, sharedElements,
631                     new SharedElementCallback.OnSharedElementsReadyListener() {
632                         @Override
633                         public void onSharedElementsReady() {
634                             listener.onSharedElementsReady();
635                         }
636                     });
637         }
638     }
639 }
640