Giter Site home page Giter Site logo

patilshreyas / permission-flow-android Goto Github PK

View Code? Open in Web Editor NEW
549.0 5.0 21.0 979 KB

Know about real-time state of a Android app Permissions with Kotlin Flow APIs.

Home Page: https://PatilShreyas.github.io/permission-flow-android/

License: Apache License 2.0

Kotlin 100.00%
android android-library coroutines-android kotlin kotlin-android permission-android stateflow stateflow-android android-app compose

permission-flow-android's Introduction

Permission Flow for Android

Know about real-time state of a Android app Permissions with Kotlin Flow APIs. Made with โค๏ธ for Android Developers.

Build Release codecov Maven Central GitHub

dokka kover

๐Ÿ’กIntroduction

In big projects, app is generally divided in several modules and in such cases, if any individual module is just a data module (not having UI) and need to know state of a permission, it's not that easy. This library provides a way to know state of a permission throughout the app and from any layer of the application safely.

For example, you can listen for state of contacts permission in class where you'll instantly show list of contacts when permission is granted.

It's a simple and easy to use library. Just Plug and Play.

๐Ÿš€ Implementation

You can check /app directory which includes example application for demonstration.

1. Gradle setup

In build.gradle of app module, include this dependency

dependencies {
    implementation "dev.shreyaspatil.permission-flow:permission-flow-android:$version"
    
    // For using in Jetpack Compose
    implementation "dev.shreyaspatil.permission-flow:permission-flow-compose:$version"
}

You can find latest version and changelogs in the releases.

2. Observing a Permission State

2.1 Observing Permission with StateFlow

A permission state can be subscribed by retrieving StateFlow<PermissionState> or StateFlow<MultiplePermissionState> as follows:

val permissionFlow = PermissionFlow.getInstance()

// Observe state of single permission
suspend fun observePermission() {
    permissionFlow.getPermissionState(Manifest.permission.READ_CONTACTS).collect { state ->
        if (state.isGranted) {
            // Permission granted, access contacts.
        } else if (state.isRationaleRequired == true) {
            // Permission denied, but can be requested again
        } else {
            // Permission denied, and can't be requested again
        }
    }
}

// Observe state of multiple permissions
suspend fun observeMultiplePermissions() {
    permissionFlow.getMultiplePermissionState(
        Manifest.permission.READ_CONTACTS,
        Manifest.permission.READ_SMS
    ).collect { state ->
        // All permission states
        val allPermissions = state.permissions

        // Check whether all permissions are granted
        val allGranted = state.allGranted

        // List of granted permissions
        val grantedPermissions = state.grantedPermissions

        // List of denied permissions
        val deniedPermissions = state.deniedPermissions
        
        // List of permissions requiring rationale
        val permissionsRequiringRationale = state.permissionsRequiringRationale
    }
}

2.2 Observing permissions in Jetpack Compose

State of a permission and state of multiple permissions can also be observed in Jetpack Compose application as follows:

@Composable
fun ExampleSinglePermission() {
    val state by rememberPermissionState(Manifest.permission.CAMERA)
    if (state.isGranted) {
        // Permission granted
    } else if (state.isRationaleRequired == true) {
        // Permission denied, but can be requested again
    } else {
        // Permission denied, and can't be requested again
    }
}

@Composable
fun ExampleMultiplePermission() {
    val state by rememberMultiplePermissionState(
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.READ_CONTACTS
    )

    if (state.allGranted) {
        // Render something
    }

    val grantedPermissions = state.grantedPermissions
    // Do something with `grantedPermissions`

    val deniedPermissions = state.deniedPermissions
    // Do something with `deniedPermissions`
    
    val permissionsRequiringRationale = state.permissionsRequiringRationale
    // Do something with `permissionsRequiringRationale`
}

3. Requesting permission with PermissionFlow

It's necessary to use utilities provided by this library to request permissions so that whenever permission state changes, this library takes care of notifying respective flows.

3.1 Request permission from Activity / Fragment

Use registerForPermissionFlowRequestsResult() method to get ActivityResultLauncher and use launch() method to request for permission.

class ContactsActivity : AppCompatActivity() {

    private val permissionLauncher = registerForPermissionFlowRequestsResult()

    private fun askContactsPermission() {
        permissionLauncher.launch(Manifest.permission.READ_CONTACTS, ...)
    }
}

3.2 Request permission in Jetpack Compose

Use rememberPermissionFlowRequestLauncher() method to get ManagedActivityResultLauncher and use launch() method to request for permission.

@Composable
fun Example() {
    val permissionLauncher = rememberPermissionFlowRequestLauncher()

    Button(onClick = { permissionLauncher.launch(android.Manifest.permission.CAMERA, ...) }) {
        Text("Request Permissions")
    }
}

4. Manually notifying permission state changes โš ๏ธ

If you're not using ActivityResultLauncher APIs provided by this library then you will not receive permission state change updates. But there's a provision by which you can help this library to know about permission state changes.

Use PermissionFlow#notifyPermissionsChanged() to notify the permission state changes from your manual implementations.

For example:

class MyActivity: AppCompatActivity() {
    private val permissionFlow = PermissionFlow.getInstance()

    private val permissionLauncher = registerForActivityResult(RequestPermission()) { isGranted ->
        permissionFlow.notifyPermissionsChanged(android.Manifest.permission.READ_CONTACTS)
    }
}

5. Manually Start / Stop Listening โš ๏ธ

This library starts processing things lazily whenever getPermissionState() or getMultiplePermissionState() is called for the first time. But this can be controlled with these methods:

fun doSomething() {
    // Stops listening to the state changes of permissions throughout the application.
    // This means the state of permission retrieved with [getMultiplePermissionState] method will not 
    // be updated after stopping listening. 
    permissionFlow.stopListening()

    // Starts listening the changes of state of permissions after stopping listening
    permissionFlow.startListening()
}

6. What about Initialization?

This library automatically gets initialized with the App Startup library. If you want to provide own coroutine dispatcher

6.1 Initialize PermissionFlow as follows (For example, in Application class)

class MyApplication: Application() {
    override fun onCreate() {
        super.onCreate()
        val permissionDispatcher = Executors.newFixedThreadPool(3).asCoroutineDispatcher()
        PermissionFlow.init(this, permissionDispatcher)
    }
}

6.2 Disable PermissionFlowInitializer in AndroidManifest.xml

Disable auto initialization of library with default configuration using this:

<provider
    android:name="androidx.startup.InitializationProvider"
    android:authorities="${applicationId}.androidx-startup"
    android:exported="false"
    tools:node="merge">

    <meta-data
        android:name="dev.shreyaspatil.permissionFlow.initializer.PermissionFlowInitializer"
        android:value="androidx.startup"
        tools:node="remove" />
</provider>

๐Ÿ“„ API Documentation

Visit the API documentation of this library to get more information in detail. This documentation is generated using Dokka.

๐Ÿ“Š Test coverage report

Check the Test Coverage Report of this library. This is generated using Kover.


๐Ÿ™‹โ€โ™‚๏ธ Contribute

Read contribution guidelines for more information regarding contribution.

๐Ÿ’ฌ Discuss?

Have any questions, doubts or want to present your opinions, views? You're always welcome. You can start discussions.

๐Ÿ“ License

Copyright 2022 Shreyas Patil

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.

permission-flow-android's People

Contributors

dependabot[bot] avatar patilshreyas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

permission-flow-android's Issues

isRationaleRequired is null after manual initialization

Hi, when adding WorkManager (Including the initializer in the manifest):

<provider
   android:name="androidx.startup.InitializationProvider"
   android:authorities="${applicationId}.androidx-startup"
   tools:node="remove" />

An error occurs:

java.lang.IllegalStateException: Failed to create instance of PermissionFlow. Did you forget to call PermissionFlow.init(context)?

But after adding the PermissionFlow initializer to the Aplication class and manifest - the value of isRationaleRequired becomes null:

permission=android.permission.POST_NOTIFICATIONS, isGranted=false, isRationaleRequired=null)

Maybe it's some kind of mistake on my part?

Wrong state for Manifest.permission.ACCESS_NOTIFICATION_POLICY

Hello, i've been using this library to handle permissions in my app. And i've noticed that it works fine with other permissions in my app except this one (Manifest.permission.ACCESS_NOTIFICATION_POLICY). for some reason the state of this permission isGranted value is always true even when the permission is not granted. i have tried it on multiple emulator instances and my physical device and all have produced the same results. Unfortunately i don't have much knowledge in this library except on how to use it, and i don't know what causes this or how to solve it.

Package not found

Getting Package not found when requesting for permissions. Checked on API Level 31 and 32. Attaching Log Screenshot
Screenshot 2023-07-05 at 4 01 00 PM

Support for shouldShowRequestRationale

I was wondering if we can add support for shouldShowRequestRationale as mentioned in the recommend flow of permissions by Google

Infact, I was trying to do the same, but I am not too sure about the implementation

Collecting the StateFlow is sending the initial State

When we call permissionFlow.getMultiplePermissionState(*permissions) and use collect on it it is creating a state flow with an initial value this initial value is getting collected first and then permission dialog is shown to the user based on user action collect is again triggered. In the initial state permission is not granted and if the user also didn't grant the permission then collect block is called with the same permission state as initial state here how to identify these two states inside the collect block the initial state and the user denied state.

Getting Fragment not attached to an activity exception

I'm trying to use the library version 1.1.0 in a Fragment but I get a crash with
Caused by: java.lang.IllegalStateException: Fragment XYZ{8954ecf} (8e69d028-83c3-4c49-90fb-7e0e59a8156a) not attached to an activity.

What is have done

  1. added lib dependency

  2. obtained ActivityResultLauncher in my Fragment as below

private val permissionLauncher = registerForPermissionFlowRequestsResult()

  1. Ran my project and got the crash

Am I missing something?

Use in domain layer

Hi Patil,
Great work. My question is could we use this lib in domain layer of Clean architecture without make depend it to platform?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.