RxPermissions README

The project's README from github.com/tbruyelle/RxPermissions. As one markdown file: README.md.

RxPermissions

BuildVersion Build Status

This library allows the usage of RxJava with the new Android M permission model.

Setup

To use this library your minSdkVersion must be >= 14.

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.12'
}

Usage

Create a RxPermissions instance :

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)

// 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 to turn your view to an observable (not included in the library).

Example :

// 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 :

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 :

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 :

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.

Status

This library is still beta, so contributions are welcome. I'm currently using it in production since months without issue.

Benefits

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.

RxPermissions (tbruyelle/RxPermissions)

Searching Database…

10.4K ·GitHub
archived
Что это такое?Опенсорсная библиотека для Android, которая работает с разрешениями во время выполнения через RxJava2 — она оборачивает модель разрешений Android M в observables.
Это библиотека, которую я подключаю в своё приложение, или отдельный инструмент?Это Java-библиотека, которую вы добавляете в своё Android-приложение; она выпущена под лицензией Apache-2.0. Ваше приложение должно иметь minSdkVersion 14 или выше.
Как создать экземпляр RxPermissions?Создайте его через new RxPermissions(this) из FragmentActivity или Fragment. Внутри фрагмента передавайте сам экземпляр фрагмента, а не fragment.getActivity(), иначе можно поймать IllegalStateException.
Мой проект уже должен использовать RxJava2?Да — весь API построен на RxJava2 observables: разрешения запрашиваются подпиской, а не через обработку колбэков.
Могу ли я запросить разрешение откуда угодно, например из onResume?Нет — запросы должны выполняться на этапе инициализации, например в Activity.onCreate или View.onFinishInflate, а не в методах вроде onResume. Иначе вы рискуете получить бесконечный цикл запросов, а если приложение перезапустится во время запроса, ответ пользователя никогда не будет передан.
Можно запросить несколько разрешений сразу и при этом видеть результат по каждому?Да. Несколько разрешений можно запросить вместе с объединённым результатом; requestEach и ensureEach выдают подробный результат по каждому разрешению, а requestEachCombined или ensureEachCombined дают объединённые подробные результаты.
Можно ли запустить запрос по нажатию кнопки?Да, но настройте событие как observable на этапе инициализации — JakeWharton's RxBinding умеет превращать view в observables — и присоедините запрос разрешений к нему цепочкой.
Есть ли что-то особенное на версиях Android до Marshmallow?Да: на SDK старше M observer автоматически получает результат «разрешено», так что вам не нужно проверять версию системы в коде.
Готово ли это к использованию в продакшене?README по-прежнему помечает её как beta, но автор месяцами использовал её в продакшене без проблем. Учтите, что репозиторий на GitHub уже заархивирован, так что дальнейшей поддержки не ждите.
Creator
tbruyelle
Size
0.6 MB
Stars
10.4K
Age
11y
Commits · 90 Days