Repository: tbruyelle/RxPermissions Branch: master Commit: fd2b50fe8c11 Files: 29 Total size: 88.3 KB Directory structure: gitextract_uf1_amf6/ ├── .github/ │ └── ISSUE_TEMPLATE/ │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── lib/ │ ├── bintray.gradle │ ├── build.gradle │ ├── install.gradle │ ├── jitpack.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── tbruyelle/ │ │ └── rxpermissions3/ │ │ ├── Permission.java │ │ ├── RxPermissions.java │ │ └── RxPermissionsFragment.java │ └── test/ │ └── java/ │ └── com/ │ └── tbruyelle/ │ └── rxpermissions3/ │ └── RxPermissionsTest.java ├── sample/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── tbruyelle/ │ │ │ └── rxpermissions3/ │ │ │ └── sample/ │ │ │ └── MainActivity.java │ │ └── res/ │ │ ├── layout/ │ │ │ └── act_main.xml │ │ └── values/ │ │ └── strings.xml │ └── test/ │ └── java/ │ └── com/ │ └── tbruyelle/ │ └── rxpermissions/ │ └── sample/ │ └── RxPermissionsSampleTest.java └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: 'Create a bug report. ' title: Bug labels: '' assignees: '' --- ### Prerequisites * [] Put an X between the brackets on this line if you have done all of the following: * Read carefully README: https://github.com/tbruyelle/RxPermissions#rxpermissions * Checked that your issue isn't already filed: https://github.com/tbruyelle/RxPermissions/issues ### Issue description [A clear and concise description of what the bug is.] ### Actual behavior [A clear and concise description of what actually happened.] ### Expected behavior [A clear and concise description of what you expected to happen.] ### Steps To Reproduce Steps to reproduce the behavior: 1. [First Step] 2. [Second Step] 3. [and so on...] ### RxPermission usage code **(extremely Required)** Give a comprehensive example of how exactly RxPermission is used (Use [gists](https://gist.github.com/) or style code with styling markdown). Provide all info from the beginning that includes: - How and where RxPermission was instantiated. - In what lifecycle method. Activity or fragment. Give info about screen view hierarchy if it really complicated and has many nested Fragments. - Some additional info or important context if needed. ### Lib Version Give info about what lib version do you use **Screenshots** Add screenshots to help explain your problem only If it will be handy for your use case. If issued only with particular device provide device info - Device: [e.g. Nexus 5] - OS version: [Android 5.1] ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .gitignore ================================================ local.properties .idea *.iml .gradle build .DS_STORE ================================================ FILE: .travis.yml ================================================ language: android dist: trusty android: components: - tools - build-tools-29.0.3 - android-29 - extra-android-m2repository jdk: oraclejdk8 notifications: email: false sudo: false before_script: - mkdir "$ANDROID_HOME/licenses" || true - echo "24333f8a63b6825ea9c5514f83c2829b004d1fee" > "$ANDROID_HOME/licenses/android-sdk-license" cache: directories: - $HOME/.gradle script: ./gradlew test ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # RxPermissions [![](https://jitpack.io/v/tbruyelle/RxPermissions.svg)](https://jitpack.io/#tbruyelle/RxPermissions) [![BuildVersion](https://buildstats.info/nuget/RxPermissions)](https://www.nuget.org/packages/RxPermissions/) [![Build Status](https://api.travis-ci.org/tbruyelle/RxPermissions.svg?branch=master)](https://travis-ci.org/tbruyelle/RxPermissions) This library allows the usage of RxJava with the new Android M permission model. ## Setup To use this library your `minSdkVersion` must be >= 14. ```gradle allprojects { repositories { ... maven { url 'https://jitpack.io' } } } dependencies { implementation 'com.github.tbruyelle:rxpermissions:0.12' } ``` ## Usage Create a `RxPermissions` instance : ```java final RxPermissions rxPermissions = new RxPermissions(this); // where this is an Activity or Fragment instance ``` **NOTE:** `new RxPermissions(this)` the `this` parameter can be a FragmentActivity or a Fragment. If you are using `RxPermissions` inside of a fragment you should pass the fragment instance(`new RxPermissions(this)`) as constructor parameter rather than `new RxPermissions(fragment.getActivity())` or you could face a `java.lang.IllegalStateException: FragmentManager is already executing transactions`. Example : request the CAMERA permission (with Retrolambda for brevity, but not required) ```java // Must be done during an initialization phase like onCreate rxPermissions .request(Manifest.permission.CAMERA) .subscribe(granted -> { if (granted) { // Always true pre-M // I can control the camera now } else { // Oups permission denied } }); ``` If you need to trigger the permission request from a specific event, you need to setup your event as an observable inside an initialization phase. You can use [JakeWharton/RxBinding](https://github.com/JakeWharton/RxBinding) to turn your view to an observable (not included in the library). Example : ```java // Must be done during an initialization phase like onCreate RxView.clicks(findViewById(R.id.enableCamera)) .compose(rxPermissions.ensure(Manifest.permission.CAMERA)) .subscribe(granted -> { // R.id.enableCamera has been clicked }); ``` If multiple permissions at the same time, the result is combined : ```java rxPermissions .request(Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE) .subscribe(granted -> { if (granted) { // All requested permissions are granted } else { // At least one permission is denied } }); ``` You can also observe a detailed result with `requestEach` or `ensureEach` : ```java rxPermissions .requestEach(Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE) .subscribe(permission -> { // will emit 2 Permission objects if (permission.granted) { // `permission.name` is granted ! } else if (permission.shouldShowRequestPermissionRationale) { // Denied permission without ask never again } else { // Denied permission with ask never again // Need to go to the settings } }); ``` You can also get combined detailed result with `requestEachCombined` or `ensureEachCombined` : ```java rxPermissions .requestEachCombined(Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE) .subscribe(permission -> { // will emit 1 Permission object if (permission.granted) { // All permissions are granted ! } else if (permission.shouldShowRequestPermissionRationale) // At least one denied permission without ask never again } else { // At least one denied permission with ask never again // Need to go to the settings } }); ``` Look at the `sample` app for more. ## Important read **As mentioned above, because your app may be restarted during the permission request, the request must be done during an initialization phase**. This may be `Activity.onCreate`, or `View.onFinishInflate`, but not *pausing* methods like `onResume`, because you'll potentially create an infinite request loop, as your requesting activity is paused by the framework during the permission request. If not, and if your app is restarted during the permission request (because of a configuration change for instance), the user's answer will never be emitted to the subscriber. You can find more details about that [here](https://github.com/tbruyelle/RxPermissions/issues/69). ## Status This library is still beta, so contributions are welcome. I'm currently using it in production since months without issue. ## Benefits - Avoid worrying about the framework version. If the sdk is pre-M, the observer will automatically receive a granted result. - Prevents you to split your code between the permission request and the result handling. Currently without this library you have to request the permission in one place and handle the result in `Activity.onRequestPermissionsResult()`. - All what RX provides about transformation, filter, chaining... # License ``` Copyright (C) 2015 Thomas Bruyelle Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` ================================================ FILE: build.gradle ================================================ buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:4.0.0' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.0' classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' } } allprojects { repositories { google() jcenter() } } ext { minSdkVersion = 14 compileSdkVersion = 29 targetSdkVersion = compileSdkVersion rxJava = 'io.reactivex.rxjava3:rxjava:3.0.4' junit = 'junit:junit:4.13' mockito = 'org.mockito:mockito-core:3.3.3' androidXFragment = 'androidx.fragment:fragment:1.2.5' androidXAnnotation = 'androidx.annotation:annotation:1.1.0' androidXAppcompat = 'androidx.appcompat:appcompat:1.1.0' robolectricVersion = '4.3.1' robolectric = "org.robolectric:robolectric:$robolectricVersion" robolectricShadowsSupport = "org.robolectric:shadows-support-v4:$robolectricVersion" // Workaround for https://github.com/robolectric/robolectric/issues/1932 khronosOpenGLApi = "org.khronos:opengl-api:gl1.1-android-2.1_r1" bintrayRepo = 'tbruyelle' bintrayName = 'RxPermissions3' publishedGroupId = 'com.tbruyelle.rxpermissions3' artifact = 'rxpermissions' libraryName = 'RxPermissions' libraryVersion = '0.9.5' libraryDescription = 'A wrapper for Android 6.0 permissions' siteUrl = 'https://github.com/tbruyelle/RxPermissions' gitUrl = 'https://github.com/tbruyelle/RxPermissions.git' developerId = 'tbruyelle' developerName = 'Thomas Bruyelle' developerEmail = 'thomas.bruyelle@gmail.com' licenseName = 'The Apache Software License, Version 2.0' licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt' allLicenses = ["Apache-2.0"] } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Thu Jul 09 16:45:02 CEST 2020 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx1536m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true android.useAndroidX = true android.enableJetifier=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save ( ) { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: lib/bintray.gradle ================================================ apply plugin: 'com.jfrog.bintray' version = libraryVersion task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } task javadoc(type: Javadoc) { source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from javadoc.destinationDir } artifacts { archives javadocJar archives sourcesJar } Properties properties = new Properties() try { properties.load(project.rootProject.file('local.properties').newDataInputStream()) } catch (FileNotFoundException ignore) {} bintray { user = properties.getProperty("bintray.user") key = properties.getProperty("bintray.apikey") configurations = ['archives'] pkg { repo = bintrayRepo name = bintrayName desc = libraryDescription websiteUrl = siteUrl vcsUrl = gitUrl licenses = allLicenses publish = true publicDownloadNumbers = true version { desc = libraryDescription gpg { sign = false } } } } ================================================ FILE: lib/build.gradle ================================================ apply plugin: 'com.android.library' apply from: 'jitpack.gradle' android { compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } testOptions.unitTests.includeAndroidResources = true testOptions.unitTests.all { // unitTests.returnDefaultValues = true // Always show the result of every unit test, even if it passes. testLogging { events 'passed', 'skipped', 'failed', 'standardOut', 'standardError' } } } dependencies { implementation rootProject.ext.rxJava implementation rootProject.ext.androidXFragment implementation rootProject.ext.androidXAnnotation implementation rootProject.ext.androidXAppcompat testImplementation 'junit:junit:4.13' testImplementation rootProject.ext.mockito testImplementation rootProject.ext.robolectric testImplementation rootProject.ext.khronosOpenGLApi } // Commented to use JitPack instead of bintray //apply from: 'install.gradle' //apply from: 'bintray.gradle' ================================================ FILE: lib/install.gradle ================================================ apply plugin: 'com.github.dcendents.android-maven' group = publishedGroupId install { repositories.mavenInstaller { pom { project { packaging 'aar' groupId publishedGroupId artifactId artifact name libraryName description libraryDescription url siteUrl licenses { license { name licenseName url licenseUrl } } developers { developer { id developerId name developerName email developerEmail } } scm { connection gitUrl developerConnection gitUrl url siteUrl } } } } } ================================================ FILE: lib/jitpack.gradle ================================================ apply plugin: 'com.github.dcendents.android-maven' group = 'com.github.tbruyelle' ================================================ FILE: lib/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in ${sdk.dir}/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: lib/src/main/AndroidManifest.xml ================================================ ================================================ FILE: lib/src/main/java/com/tbruyelle/rxpermissions3/Permission.java ================================================ package com.tbruyelle.rxpermissions3; import java.util.List; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.BiConsumer; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.functions.Predicate; public class Permission { public final String name; public final boolean granted; public final boolean shouldShowRequestPermissionRationale; public Permission(String name, boolean granted) { this(name, granted, false); } public Permission(String name, boolean granted, boolean shouldShowRequestPermissionRationale) { this.name = name; this.granted = granted; this.shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale; } public Permission(List permissions) { name = combineName(permissions); granted = combineGranted(permissions); shouldShowRequestPermissionRationale = combineShouldShowRequestPermissionRationale(permissions); } @Override @SuppressWarnings("SimplifiableIfStatement") public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Permission that = (Permission) o; if (granted != that.granted) return false; if (shouldShowRequestPermissionRationale != that.shouldShowRequestPermissionRationale) return false; return name.equals(that.name); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + (granted ? 1 : 0); result = 31 * result + (shouldShowRequestPermissionRationale ? 1 : 0); return result; } @Override public String toString() { return "Permission{" + "name='" + name + '\'' + ", granted=" + granted + ", shouldShowRequestPermissionRationale=" + shouldShowRequestPermissionRationale + '}'; } private String combineName(List permissions) { return Observable.fromIterable(permissions) .map(new Function() { @Override public String apply(Permission permission) throws Exception { return permission.name; } }).collectInto(new StringBuilder(), new BiConsumer() { @Override public void accept(StringBuilder s, String s2) throws Exception { if (s.length() == 0) { s.append(s2); } else { s.append(", ").append(s2); } } }).blockingGet().toString(); } private Boolean combineGranted(List permissions) { return Observable.fromIterable(permissions) .all(new Predicate() { @Override public boolean test(Permission permission) throws Exception { return permission.granted; } }).blockingGet(); } private Boolean combineShouldShowRequestPermissionRationale(List permissions) { return Observable.fromIterable(permissions) .any(new Predicate() { @Override public boolean test(Permission permission) throws Exception { return permission.shouldShowRequestPermissionRationale; } }).blockingGet(); } } ================================================ FILE: lib/src/main/java/com/tbruyelle/rxpermissions3/RxPermissions.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tbruyelle.rxpermissions3; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import java.util.ArrayList; import java.util.List; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.ObservableSource; import io.reactivex.rxjava3.core.ObservableTransformer; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.subjects.PublishSubject; public class RxPermissions { static final String TAG = RxPermissions.class.getSimpleName(); static final Object TRIGGER = new Object(); @VisibleForTesting Lazy mRxPermissionsFragment; public RxPermissions(@NonNull final FragmentActivity activity) { mRxPermissionsFragment = getLazySingleton(activity.getSupportFragmentManager()); } public RxPermissions(@NonNull final Fragment fragment) { mRxPermissionsFragment = getLazySingleton(fragment.getChildFragmentManager()); } @NonNull private Lazy getLazySingleton(@NonNull final FragmentManager fragmentManager) { return new Lazy() { private RxPermissionsFragment rxPermissionsFragment; @Override public synchronized RxPermissionsFragment get() { if (rxPermissionsFragment == null) { rxPermissionsFragment = getRxPermissionsFragment(fragmentManager); } return rxPermissionsFragment; } }; } private RxPermissionsFragment getRxPermissionsFragment(@NonNull final FragmentManager fragmentManager) { RxPermissionsFragment rxPermissionsFragment = findRxPermissionsFragment(fragmentManager); boolean isNewInstance = rxPermissionsFragment == null; if (isNewInstance) { rxPermissionsFragment = new RxPermissionsFragment(); fragmentManager .beginTransaction() .add(rxPermissionsFragment, TAG) .commitNow(); } return rxPermissionsFragment; } private RxPermissionsFragment findRxPermissionsFragment(@NonNull final FragmentManager fragmentManager) { return (RxPermissionsFragment) fragmentManager.findFragmentByTag(TAG); } public void setLogging(boolean logging) { mRxPermissionsFragment.get().setLogging(logging); } /** * Map emitted items from the source observable into {@code true} if permissions in parameters * are granted, or {@code false} if not. *

* If one or several permissions have never been requested, invoke the related framework method * to ask the user if he allows the permissions. */ @SuppressWarnings("WeakerAccess") public ObservableTransformer ensure(final String... permissions) { return new ObservableTransformer() { @Override public ObservableSource apply(Observable o) { return request(o, permissions) // Transform Observable to Observable .buffer(permissions.length) .flatMap(new Function, ObservableSource>() { @Override public ObservableSource apply(List permissions) { if (permissions.isEmpty()) { // Occurs during orientation change, when the subject receives onComplete. // In that case we don't want to propagate that empty list to the // subscriber, only the onComplete. return Observable.empty(); } // Return true if all permissions are granted. for (Permission p : permissions) { if (!p.granted) { return Observable.just(false); } } return Observable.just(true); } }); } }; } /** * Map emitted items from the source observable into {@link Permission} objects for each * permission in parameters. *

* If one or several permissions have never been requested, invoke the related framework method * to ask the user if he allows the permissions. */ @SuppressWarnings("WeakerAccess") public ObservableTransformer ensureEach(final String... permissions) { return new ObservableTransformer() { @Override public ObservableSource apply(Observable o) { return request(o, permissions); } }; } /** * Map emitted items from the source observable into one combined {@link Permission} object. Only if all permissions are granted, * permission also will be granted. If any permission has {@code shouldShowRationale} checked, than result also has it checked. *

* If one or several permissions have never been requested, invoke the related framework method * to ask the user if he allows the permissions. */ public ObservableTransformer ensureEachCombined(final String... permissions) { return new ObservableTransformer() { @Override public ObservableSource apply(Observable o) { return request(o, permissions) .buffer(permissions.length) .flatMap(new Function, ObservableSource>() { @Override public ObservableSource apply(List permissions) { if (permissions.isEmpty()) { return Observable.empty(); } return Observable.just(new Permission(permissions)); } }); } }; } /** * Request permissions immediately, must be invoked during initialization phase * of your application. */ @SuppressWarnings({"WeakerAccess", "unused"}) public Observable request(final String... permissions) { return Observable.just(TRIGGER).compose(ensure(permissions)); } /** * Request permissions immediately, must be invoked during initialization phase * of your application. */ @SuppressWarnings({"WeakerAccess", "unused"}) public Observable requestEach(final String... permissions) { return Observable.just(TRIGGER).compose(ensureEach(permissions)); } /** * Request permissions immediately, must be invoked during initialization phase * of your application. */ public Observable requestEachCombined(final String... permissions) { return Observable.just(TRIGGER).compose(ensureEachCombined(permissions)); } private Observable request(final Observable trigger, final String... permissions) { if (permissions == null || permissions.length == 0) { throw new IllegalArgumentException("RxPermissions.request/requestEach requires at least one input permission"); } return trigger.flatMap( o -> requestImplementation(permissions)); } @TargetApi(Build.VERSION_CODES.M) private Observable requestImplementation(final String... permissions) { List> list = new ArrayList<>(permissions.length); List unrequestedPermissions = new ArrayList<>(); // In case of multiple permissions, we create an Observable for each of them. // At the end, the observables are combined to have a unique response. for (String permission : permissions) { mRxPermissionsFragment.get().log("Requesting permission " + permission); if (isGranted(permission)) { // Already granted, or not Android M // Return a granted Permission object. list.add(Observable.just(new Permission(permission, true, false))); continue; } if (isRevoked(permission)) { // Revoked by a policy, return a denied Permission object. list.add(Observable.just(new Permission(permission, false, false))); continue; } PublishSubject subject = mRxPermissionsFragment.get().getSubjectByPermission(permission); // Create a new subject if not exists if (subject == null) { unrequestedPermissions.add(permission); subject = PublishSubject.create(); mRxPermissionsFragment.get().setSubjectForPermission(permission, subject); } list.add(subject); } if (!unrequestedPermissions.isEmpty()) { String[] unrequestedPermissionsArray = unrequestedPermissions.toArray(new String[unrequestedPermissions.size()]); requestPermissionsFromFragment(unrequestedPermissionsArray); } return Observable.concat(Observable.fromIterable(list)); } /** * Invokes Activity.shouldShowRequestPermissionRationale and wraps * the returned value in an observable. *

* In case of multiple permissions, only emits true if * Activity.shouldShowRequestPermissionRationale returned true for * all revoked permissions. *

* You shouldn't call this method if all permissions have been granted. *

* For SDK < 23, the observable will always emit false. */ @SuppressWarnings("WeakerAccess") public Observable shouldShowRequestPermissionRationale(final Activity activity, final String... permissions) { if (!isMarshmallow()) { return Observable.just(false); } return Observable.just(shouldShowRequestPermissionRationaleImplementation(activity, permissions)); } @TargetApi(Build.VERSION_CODES.M) private boolean shouldShowRequestPermissionRationaleImplementation(final Activity activity, final String... permissions) { for (String p : permissions) { if (!isGranted(p) && !activity.shouldShowRequestPermissionRationale(p)) { return false; } } return true; } @TargetApi(Build.VERSION_CODES.M) void requestPermissionsFromFragment(String[] permissions) { mRxPermissionsFragment.get().log("requestPermissionsFromFragment " + TextUtils.join(", ", permissions)); mRxPermissionsFragment.get().requestPermissions(permissions); } /** * Returns true if the permission is already granted. *

* Always true if SDK < 23. */ @SuppressWarnings("WeakerAccess") public boolean isGranted(String permission) { return !isMarshmallow() || mRxPermissionsFragment.get().isGranted(permission); } /** * Returns true if the permission has been revoked by a policy. *

* Always false if SDK < 23. */ @SuppressWarnings("WeakerAccess") public boolean isRevoked(String permission) { return isMarshmallow() && mRxPermissionsFragment.get().isRevoked(permission); } boolean isMarshmallow() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } void onRequestPermissionsResult(String[] permissions, int[] grantResults) { mRxPermissionsFragment.get().onRequestPermissionsResult(permissions, grantResults, new boolean[permissions.length]); } @FunctionalInterface public interface Lazy { V get(); } } ================================================ FILE: lib/src/main/java/com/tbruyelle/rxpermissions3/RxPermissionsFragment.java ================================================ package com.tbruyelle.rxpermissions3; import android.annotation.TargetApi; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import java.util.HashMap; import java.util.Map; import io.reactivex.rxjava3.subjects.PublishSubject; public class RxPermissionsFragment extends Fragment { private static final int PERMISSIONS_REQUEST_CODE = 42; // Contains all the current permission requests. // Once granted or denied, they are removed from it. private Map> mSubjects = new HashMap<>(); private boolean mLogging; public RxPermissionsFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @TargetApi(Build.VERSION_CODES.M) void requestPermissions(@NonNull String[] permissions) { requestPermissions(permissions, PERMISSIONS_REQUEST_CODE); } @TargetApi(Build.VERSION_CODES.M) public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode != PERMISSIONS_REQUEST_CODE) return; boolean[] shouldShowRequestPermissionRationale = new boolean[permissions.length]; for (int i = 0; i < permissions.length; i++) { shouldShowRequestPermissionRationale[i] = shouldShowRequestPermissionRationale(permissions[i]); } onRequestPermissionsResult(permissions, grantResults, shouldShowRequestPermissionRationale); } void onRequestPermissionsResult(String[] permissions, int[] grantResults, boolean[] shouldShowRequestPermissionRationale) { for (int i = 0, size = permissions.length; i < size; i++) { log("onRequestPermissionsResult " + permissions[i]); // Find the corresponding subject PublishSubject subject = mSubjects.get(permissions[i]); if (subject == null) { // No subject found Log.e(RxPermissions.TAG, "RxPermissions.onRequestPermissionsResult invoked but didn't find the corresponding permission request."); return; } mSubjects.remove(permissions[i]); boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED; subject.onNext(new Permission(permissions[i], granted, shouldShowRequestPermissionRationale[i])); subject.onComplete(); } } @TargetApi(Build.VERSION_CODES.M) boolean isGranted(String permission) { final FragmentActivity fragmentActivity = getActivity(); if (fragmentActivity == null) { throw new IllegalStateException("This fragment must be attached to an activity."); } return fragmentActivity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } @TargetApi(Build.VERSION_CODES.M) boolean isRevoked(String permission) { final FragmentActivity fragmentActivity = getActivity(); if (fragmentActivity == null) { throw new IllegalStateException("This fragment must be attached to an activity."); } return fragmentActivity.getPackageManager().isPermissionRevokedByPolicy(permission, getActivity().getPackageName()); } public void setLogging(boolean logging) { mLogging = logging; } public PublishSubject getSubjectByPermission(@NonNull String permission) { return mSubjects.get(permission); } public void setSubjectForPermission(@NonNull String permission, @NonNull PublishSubject subject) { mSubjects.put(permission, subject); } void log(String message) { if (mLogging) { Log.d(RxPermissions.TAG, message); } } } ================================================ FILE: lib/src/test/java/com/tbruyelle/rxpermissions3/RxPermissionsTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tbruyelle.rxpermissions3; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Build; import androidx.fragment.app.FragmentActivity; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) @Config(sdk = Build.VERSION_CODES.M) public class RxPermissionsTest { private FragmentActivity mActivity; private RxPermissions mRxPermissions; @Before public void setup() { ActivityController activityController = Robolectric.buildActivity(FragmentActivity.class); mActivity = spy(activityController.setup().get()); mRxPermissions = spy(new RxPermissions(mActivity)); mRxPermissions.mRxPermissionsFragment = spy(mRxPermissions.mRxPermissionsFragment); final RxPermissionsFragment rxPermissionsFragment = spy(mRxPermissions.mRxPermissionsFragment.get()); when(rxPermissionsFragment.getActivity()).thenReturn(mActivity); when(mRxPermissions.mRxPermissionsFragment.get()).thenReturn(rxPermissionsFragment); // Default deny all permissions doReturn(false).when(mRxPermissions).isGranted(anyString()); // Default no revoked permissions doReturn(false).when(mRxPermissions).isRevoked(anyString()); } private Observable trigger() { return Observable.just(RxPermissions.TRIGGER); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_preM() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(true); trigger().compose(mRxPermissions.ensure(permission)).subscribe(sub); sub.assertNoErrors(); sub.assertValue(true); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_granted() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED}; trigger().compose(mRxPermissions.ensure(permission)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(true); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_granted() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED}; trigger().compose(mRxPermissions.ensureEach(permission)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(new Permission(permission, true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_granted() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED}; trigger().compose(mRxPermissions.ensureEachCombined(permission)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(new Permission(permission, true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_preM() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(true); trigger().compose(mRxPermissions.ensureEach(permission)).subscribe(sub); sub.assertNoErrors(); sub.assertValue(new Permission(permission, true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_preM() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(true); trigger().compose(mRxPermissions.ensureEachCombined(permission)).subscribe(sub); sub.assertNoErrors(); sub.assertValue(new Permission(permission, true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_alreadyGranted() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(true); trigger().compose(mRxPermissions.ensure(permission)).subscribe(sub); sub.assertNoErrors(); sub.assertValue(true); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_denied() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_DENIED}; trigger().compose(mRxPermissions.ensure(permission)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(false); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_denied() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_DENIED}; trigger().compose(mRxPermissions.ensureEach(permission)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(new Permission(permission, false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_denied() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_DENIED}; trigger().compose(mRxPermissions.ensureEachCombined(permission)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(new Permission(permission, false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_revoked() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isRevoked(permission)).thenReturn(true); trigger().compose(mRxPermissions.ensure(permission)).subscribe(sub); sub.assertNoErrors(); sub.assertValue(false); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_revoked() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isRevoked(permission)).thenReturn(true); trigger().compose(mRxPermissions.ensureEach(permission)).subscribe(sub); sub.assertNoErrors(); sub.assertValue(new Permission(permission, false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_revoked() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isRevoked(permission)).thenReturn(true); trigger().compose(mRxPermissions.ensureEachCombined(permission)).subscribe(sub); sub.assertNoErrors(); sub.assertValue(new Permission(permission, false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_severalPermissions_granted() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_GRANTED}; trigger().compose(mRxPermissions.ensure(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(permissions, result); sub.assertNoErrors(); sub.assertValue(true); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_severalPermissions_granted() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_GRANTED}; trigger().compose(mRxPermissions.ensureEach(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(permissions, result); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0], true), new Permission(permissions[1], true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_severalPermissions_granted() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_GRANTED}; trigger().compose(mRxPermissions.ensureEachCombined(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(permissions, result); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0] + ", " + permissions[1], true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_severalPermissions_oneDenied() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_DENIED}; trigger().compose(mRxPermissions.ensure(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(permissions, result); sub.assertNoErrors(); sub.assertValue(false); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_severalPermissions_oneRevoked() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); when(mRxPermissions.isRevoked(Manifest.permission.CAMERA)).thenReturn(true); trigger().compose(mRxPermissions.ensure(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult( new String[]{Manifest.permission.READ_PHONE_STATE}, new int[]{PackageManager.PERMISSION_GRANTED}); sub.assertNoErrors(); sub.assertValue(false); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_severalPermissions_oneAlreadyGranted() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); when(mRxPermissions.isGranted(Manifest.permission.CAMERA)).thenReturn(true); trigger().compose(mRxPermissions.ensureEach(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult( new String[]{Manifest.permission.READ_PHONE_STATE}, new int[]{PackageManager.PERMISSION_GRANTED}); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0], true), new Permission(permissions[1], true)); ArgumentCaptor requestedPermissions = ArgumentCaptor.forClass(String[].class); verify(mRxPermissions).requestPermissionsFromFragment(requestedPermissions.capture()); assertEquals(1, requestedPermissions.getValue().length); assertEquals(Manifest.permission.READ_PHONE_STATE, requestedPermissions.getValue()[0]); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_severalPermissions_oneAlreadyGranted() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); when(mRxPermissions.isGranted(Manifest.permission.CAMERA)).thenReturn(true); trigger().compose(mRxPermissions.ensureEachCombined(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult( new String[]{Manifest.permission.READ_PHONE_STATE}, new int[]{PackageManager.PERMISSION_GRANTED}); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0] + ", " + permissions[1], true)); ArgumentCaptor requestedPermissions = ArgumentCaptor.forClass(String[].class); verify(mRxPermissions).requestPermissionsFromFragment(requestedPermissions.capture()); assertEquals(1, requestedPermissions.getValue().length); assertEquals(Manifest.permission.READ_PHONE_STATE, requestedPermissions.getValue()[0]); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_severalPermissions_oneDenied() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_DENIED}; trigger().compose(mRxPermissions.ensureEach(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(permissions, result); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0], true), new Permission(permissions[1], false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_severalPermissions_oneDenied() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_DENIED}; trigger().compose(mRxPermissions.ensureEachCombined(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult(permissions, result); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0] + ", " + permissions[1], false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_severalPermissions_oneRevoked() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); when(mRxPermissions.isRevoked(Manifest.permission.CAMERA)).thenReturn(true); trigger().compose(mRxPermissions.ensureEach(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult( new String[]{Manifest.permission.READ_PHONE_STATE}, new int[]{PackageManager.PERMISSION_GRANTED}); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0], true), new Permission(permissions[1], false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_severalPermissions_oneRevoked() { TestObserver sub = new TestObserver<>(); String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA}; when(mRxPermissions.isGranted(ArgumentMatchers.anyString())).thenReturn(false); when(mRxPermissions.isRevoked(Manifest.permission.CAMERA)).thenReturn(true); trigger().compose(mRxPermissions.ensureEachCombined(permissions)).subscribe(sub); mRxPermissions.onRequestPermissionsResult( new String[]{Manifest.permission.READ_PHONE_STATE}, new int[]{PackageManager.PERMISSION_GRANTED}); sub.assertNoErrors(); sub.assertValues(new Permission(permissions[0] + ", " + permissions[1], false)); } @Test @TargetApi(Build.VERSION_CODES.M) public void subscription_trigger_granted() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED}; PublishSubject trigger = PublishSubject.create(); trigger.compose(mRxPermissions.ensure(permission)).subscribe(sub); trigger.onNext(1); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(true); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscription_trigger_granted() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED}; PublishSubject trigger = PublishSubject.create(); trigger.compose(mRxPermissions.ensureEach(permission)).subscribe(sub); trigger.onNext(1); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(new Permission(permission, true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void eachSubscriptionCombined_trigger_granted() { TestObserver sub = new TestObserver<>(); String permission = Manifest.permission.READ_PHONE_STATE; when(mRxPermissions.isGranted(permission)).thenReturn(false); int[] result = new int[]{PackageManager.PERMISSION_GRANTED}; PublishSubject trigger = PublishSubject.create(); trigger.compose(mRxPermissions.ensureEachCombined(permission)).subscribe(sub); trigger.onNext(1); mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result); sub.assertNoErrors(); sub.assertValue(new Permission(permission, true)); } @Test @TargetApi(Build.VERSION_CODES.M) public void shouldShowRequestPermissionRationale_allDenied_allRationale() { when(mRxPermissions.isMarshmallow()).thenReturn(true); Activity activity = mock(Activity.class); when(activity.shouldShowRequestPermissionRationale(anyString())).thenReturn(true); TestObserver sub = new TestObserver<>(); mRxPermissions.shouldShowRequestPermissionRationale(activity, "p1", "p2") .subscribe(sub); sub.assertComplete(); sub.assertNoErrors(); sub.assertValue(true); } @Test @TargetApi(Build.VERSION_CODES.M) public void shouldShowRequestPermissionRationale_allDenied_oneRationale() { when(mRxPermissions.isMarshmallow()).thenReturn(true); Activity activity = mock(Activity.class); when(activity.shouldShowRequestPermissionRationale("p1")).thenReturn(true); TestObserver sub = new TestObserver<>(); mRxPermissions.shouldShowRequestPermissionRationale(activity, "p1", "p2") .subscribe(sub); sub.assertComplete(); sub.assertNoErrors(); sub.assertValue(false); } @Test @TargetApi(Build.VERSION_CODES.M) public void shouldShowRequestPermissionRationale_allDenied_noRationale() { when(mRxPermissions.isMarshmallow()).thenReturn(true); Activity activity = mock(Activity.class); TestObserver sub = new TestObserver<>(); mRxPermissions.shouldShowRequestPermissionRationale(activity, "p1", "p2") .subscribe(sub); sub.assertComplete(); sub.assertNoErrors(); sub.assertValue(false); } @Test @TargetApi(Build.VERSION_CODES.M) public void shouldShowRequestPermissionRationale_oneDeniedRationale() { when(mRxPermissions.isMarshmallow()).thenReturn(true); Activity activity = mock(Activity.class); when(mRxPermissions.isGranted("p1")).thenReturn(true); when(activity.shouldShowRequestPermissionRationale("p2")).thenReturn(true); TestObserver sub = new TestObserver<>(); mRxPermissions.shouldShowRequestPermissionRationale(activity, "p1", "p2") .subscribe(sub); sub.assertComplete(); sub.assertNoErrors(); sub.assertValue(true); } @Test @TargetApi(Build.VERSION_CODES.M) public void shouldShowRequestPermissionRationale_oneDeniedNotRationale() { when(mRxPermissions.isMarshmallow()).thenReturn(true); Activity activity = mock(Activity.class); when(mRxPermissions.isGranted("p2")).thenReturn(true); TestObserver sub = new TestObserver<>(); mRxPermissions.shouldShowRequestPermissionRationale(activity, "p1", "p2") .subscribe(sub); sub.assertComplete(); sub.assertNoErrors(); sub.assertValue(false); } @Test public void isGranted_preMarshmallow() { // unmock isGranted doCallRealMethod().when(mRxPermissions).isGranted(anyString()); doReturn(false).when(mRxPermissions).isMarshmallow(); boolean granted = mRxPermissions.isGranted("p"); assertTrue(granted); } @Test @TargetApi(Build.VERSION_CODES.M) public void isGranted_granted() { // unmock isGranted doCallRealMethod().when(mRxPermissions).isGranted(anyString()); doReturn(true).when(mRxPermissions).isMarshmallow(); when(mActivity.checkSelfPermission("p")).thenReturn(PackageManager.PERMISSION_GRANTED); boolean granted = mRxPermissions.isGranted("p"); assertTrue(granted); } @Test @TargetApi(Build.VERSION_CODES.M) public void isGranted_denied() { // unmock isGranted doCallRealMethod().when(mRxPermissions).isGranted(anyString()); doReturn(true).when(mRxPermissions).isMarshmallow(); when(mActivity.checkSelfPermission("p")).thenReturn(PackageManager.PERMISSION_DENIED); boolean granted = mRxPermissions.isGranted("p"); assertFalse(granted); } @Test public void isRevoked_preMarshmallow() { // unmock isRevoked doCallRealMethod().when(mRxPermissions).isRevoked(anyString()); doReturn(false).when(mRxPermissions).isMarshmallow(); boolean revoked = mRxPermissions.isRevoked("p"); assertFalse(revoked); } @Test @TargetApi(Build.VERSION_CODES.M) public void isRevoked_true() { // unmock isRevoked doCallRealMethod().when(mRxPermissions).isRevoked(anyString()); doReturn(true).when(mRxPermissions).isMarshmallow(); PackageManager pm = mock(PackageManager.class); when(mActivity.getPackageManager()).thenReturn(pm); when(pm.isPermissionRevokedByPolicy(eq("p"), anyString())).thenReturn(true); boolean revoked = mRxPermissions.isRevoked("p"); assertTrue(revoked); } @Test @TargetApi(Build.VERSION_CODES.M) public void isGranted_false() { // unmock isRevoked doCallRealMethod().when(mRxPermissions).isRevoked(anyString()); doReturn(true).when(mRxPermissions).isMarshmallow(); PackageManager pm = mock(PackageManager.class); when(mActivity.getPackageManager()).thenReturn(pm); when(pm.isPermissionRevokedByPolicy(eq("p"), anyString())).thenReturn(false); boolean revoked = mRxPermissions.isRevoked("p"); assertFalse(revoked); } } ================================================ FILE: sample/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.tbruyelle.rxpermissions.sample" minSdkVersion 14 targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } packagingOptions { exclude 'META-INF/rxjava.properties' } } dependencies { implementation project(':rxpermissions') implementation 'com.jakewharton.rxbinding4:rxbinding:4.0.0' implementation rootProject.ext.androidXAppcompat testImplementation 'junit:junit:4.13' testImplementation rootProject.ext.mockito } ================================================ FILE: sample/src/main/AndroidManifest.xml ================================================ ================================================ FILE: sample/src/main/java/com/tbruyelle/rxpermissions3/sample/MainActivity.java ================================================ package com.tbruyelle.rxpermissions3.sample; import android.Manifest.permission; import android.hardware.Camera; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.jakewharton.rxbinding4.view.RxView; import com.tbruyelle.rxpermissions3.Permission; import com.tbruyelle.rxpermissions3.RxPermissions; import java.io.IOException; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.functions.Action; import io.reactivex.rxjava3.functions.Consumer; public class MainActivity extends AppCompatActivity { private static final String TAG = "RxPermissionsSample"; private Camera camera; private SurfaceView surfaceView; private Disposable disposable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RxPermissions rxPermissions = new RxPermissions(this); rxPermissions.setLogging(true); setContentView(R.layout.act_main); surfaceView = findViewById(R.id.surfaceView); disposable = RxView.clicks(findViewById(R.id.enableCamera)) // Ask for permissions when button is clicked .compose(rxPermissions.ensureEach(permission.CAMERA)) .subscribe(new Consumer() { @Override public void accept(Permission permission) { Log.i(TAG, "Permission result " + permission); if (permission.granted) { releaseCamera(); camera = Camera.open(0); try { camera.setPreviewDisplay(surfaceView.getHolder()); camera.startPreview(); } catch (IOException e) { Log.e(TAG, "Error while trying to display the camera preview", e); } } else if (permission.shouldShowRequestPermissionRationale) { // Denied permission without ask never again Toast.makeText(MainActivity.this, "Denied permission without ask never again", Toast.LENGTH_SHORT).show(); } else { // Denied permission with ask never again // Need to go to the settings Toast.makeText(MainActivity.this, "Permission denied, can't enable the camera", Toast.LENGTH_SHORT).show(); } } }, new Consumer() { @Override public void accept(Throwable t) { Log.e(TAG, "onError", t); } }, new Action() { @Override public void run() { Log.i(TAG, "OnComplete"); } }); } @Override protected void onDestroy() { if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); } super.onDestroy(); } @Override protected void onStop() { super.onStop(); releaseCamera(); } private void releaseCamera() { if (camera != null) { camera.release(); camera = null; } } } ================================================ FILE: sample/src/main/res/layout/act_main.xml ================================================