Last active
May 29, 2018 08:51
-
-
Save talosdev/16680e29be66d6755ed170916035fb61 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class RuntimePermissionRequestHandler implements PermissionRequestHandler { | |
| private final WeakReference<Activity> activityWeakReference; | |
| private final String permission; | |
| private final int requestCode; | |
| private AsyncSubject<PermissionRequestResult> subject; | |
| public RuntimePermissionRequestHandler(Activity activity, String permission, int requestCode) { | |
| this.activityWeakReference = new WeakReference<>(activity); | |
| this.permission = permission; | |
| this.requestCode = requestCode; | |
| } | |
| @Override | |
| public boolean checkHasPermission() { | |
| if (activityWeakReference.get() != null) { | |
| Activity activity = activityWeakReference.get(); | |
| return ContextCompat.checkSelfPermission(activity, permission) | |
| == PackageManager.PERMISSION_GRANTED; | |
| } | |
| return false; | |
| } | |
| @Override | |
| public Single<PermissionRequestResult> requestPermission() { | |
| subject = AsyncSubject.create(); | |
| if (activityWeakReference.get() != null) { | |
| ActivityCompat.requestPermissions( | |
| activityWeakReference.get(), | |
| new String[] {permission}, | |
| requestCode); | |
| } | |
| return subject.firstOrError(); | |
| } | |
| @RequiresApi(api = Build.VERSION_CODES.M) | |
| public void onPermissionRequestResult(boolean granted) { | |
| if (subject != null) { | |
| if (granted) { | |
| subject.onNext(PermissionRequestResult.GRANTED); | |
| } else { | |
| Activity activity = activityWeakReference.get(); | |
| if (activity != null) { | |
| subject.onNext( | |
| activity.shouldShowRequestPermissionRationale(permission) | |
| ? PermissionRequestResult.DENIED_SOFT | |
| : PermissionRequestResult.DENIED_HARD | |
| ); | |
| } | |
| } | |
| subject.onComplete(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment