Convert Figma logo to code with AI

googlesamples logoeasypermissions

Simplify Android M system permissions

9,859
1,460
9,859
40

Top Related Projects

A declarative API to handle Android runtime permissions.

Android runtime permissions powered by RxJava2

5,232

Android library that simplifies the process of requesting permissions at runtime.

Easy check permission library for Android Marshmallow

Quick Overview

EasyPermissions is a wrapper library for Android's runtime permissions system, simplifying the process of requesting and handling permissions in Android applications. It provides a more intuitive API for managing permissions, reducing boilerplate code and making it easier for developers to implement proper permission handling.

Pros

  • Simplifies the process of requesting and handling runtime permissions
  • Reduces boilerplate code compared to native Android permission handling
  • Provides helper methods for checking permission status and rationale
  • Supports both Activity and Fragment contexts

Cons

  • Adds an additional dependency to the project
  • May not be necessary for simple apps with minimal permission requirements
  • Requires learning a new API, albeit a simpler one
  • May not always keep up with the latest Android permission changes immediately

Code Examples

  1. Requesting permissions:
EasyPermissions.requestPermissions(
    this,
    "This app needs access to your camera and location to take photos.",
    RC_CAMERA_AND_LOCATION,
    Manifest.permission.CAMERA,
    Manifest.permission.ACCESS_FINE_LOCATION
)
  1. Checking if permissions are granted:
if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
    // Camera permission is granted, proceed with camera-related tasks
} else {
    // Request camera permission
}
  1. Handling permission results:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}

@AfterPermissionGranted(RC_CAMERA_AND_LOCATION)
private fun cameraAndLocationTask() {
    // Camera and location permission granted, proceed with tasks
}

Getting Started

  1. Add the dependency to your app's build.gradle file:
dependencies {
    implementation 'pub.devrel:easypermissions:3.0.0'
}
  1. Implement EasyPermissions.PermissionCallbacks in your Activity or Fragment:
class MainActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {
    // ...

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        // Handle granted permissions
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        // Handle denied permissions
    }
}
  1. Use EasyPermissions methods to request and check permissions as shown in the code examples above.

Competitor Comparisons

A declarative API to handle Android runtime permissions.

Pros of PermissionsDispatcher

  • Uses annotation processing for compile-time code generation, reducing runtime overhead
  • Provides more granular control over permission requests and callbacks
  • Supports special permissions like system alert window and write settings

Cons of PermissionsDispatcher

  • Requires more setup and configuration compared to EasyPermissions
  • Steeper learning curve due to its annotation-based approach
  • May increase build time due to annotation processing

Code Comparison

PermissionsDispatcher:

@RuntimePermissions
class MainActivity : AppCompatActivity() {
    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        // Camera-related code
    }
}

EasyPermissions:

class MainActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {
    @AfterPermissionGranted(RC_CAMERA_PERM)
    private fun cameraTask() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            // Camera-related code
        } else {
            EasyPermissions.requestPermissions(this, "Camera permission is required", RC_CAMERA_PERM, Manifest.permission.CAMERA)
        }
    }
}

Both libraries simplify Android runtime permissions, but PermissionsDispatcher offers more advanced features at the cost of increased complexity, while EasyPermissions provides a simpler API with less setup required.

Android runtime permissions powered by RxJava2

Pros of RxPermissions

  • Integrates seamlessly with RxJava, allowing for reactive programming patterns
  • Provides a more concise API for handling multiple permissions
  • Offers better support for handling permission requests in fragments

Cons of RxPermissions

  • Requires RxJava as a dependency, which may increase app size
  • Steeper learning curve for developers not familiar with reactive programming
  • Less actively maintained compared to EasyPermissions

Code Comparison

EasyPermissions:

EasyPermissions.requestPermissions(
    this,
    "This app needs access to your camera and location",
    RC_CAMERA_AND_LOCATION,
    Manifest.permission.CAMERA,
    Manifest.permission.ACCESS_FINE_LOCATION
);

RxPermissions:

rxPermissions
    .request(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION)
    .subscribe(granted -> {
        if (granted) {
            // All permissions granted
        } else {
            // At least one permission denied
        }
    });

Both libraries simplify Android runtime permissions, but RxPermissions leverages RxJava for a more reactive approach. EasyPermissions offers a simpler API and is more actively maintained, while RxPermissions provides better integration with reactive programming paradigms.

5,232

Android library that simplifies the process of requesting permissions at runtime.

Pros of Dexter

  • More comprehensive and feature-rich, offering advanced permission handling capabilities
  • Provides a fluent API for easier and more readable permission requests
  • Supports handling multiple permissions simultaneously

Cons of Dexter

  • Larger library size, which may impact app size and performance
  • Steeper learning curve due to more complex API and features
  • Less frequently updated compared to EasyPermissions

Code Comparison

EasyPermissions:

EasyPermissions.requestPermissions(
    this,
    "This app needs access to your camera and location",
    RC_CAMERA_AND_LOCATION,
    Manifest.permission.CAMERA,
    Manifest.permission.ACCESS_FINE_LOCATION
);

Dexter:

Dexter.withActivity(this)
    .withPermissions(
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_FINE_LOCATION
    )
    .withListener(new MultiplePermissionsListener() {
        @Override
        public void onPermissionsChecked(MultiplePermissionsReport report) { /* ... */ }
        @Override
        public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) { /* ... */ }
    }).check();

Easy check permission library for Android Marshmallow

Pros of TedPermission

  • More customizable UI for permission requests
  • Supports both Kotlin and Java
  • Includes pre-built dialogs for common permission scenarios

Cons of TedPermission

  • Larger library size compared to EasyPermissions
  • May have a steeper learning curve for simpler use cases
  • Less frequent updates and maintenance

Code Comparison

EasyPermissions:

EasyPermissions.requestPermissions(
    this,
    "This app needs access to your camera and location",
    123,
    Manifest.permission.CAMERA,
    Manifest.permission.ACCESS_FINE_LOCATION
)

TedPermission:

TedPermission.with(context)
    .setPermissionListener(permissionListener)
    .setDeniedMessage("Permission denied message")
    .setPermissions(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION)
    .check()

Both libraries simplify the process of requesting runtime permissions, but TedPermission offers more customization options out of the box. EasyPermissions provides a more straightforward API for basic permission requests, while TedPermission allows for greater control over the permission request flow and UI. The choice between the two depends on the specific needs of your project and the level of customization required.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

EasyPermissions Build Status Android Weekly

EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.

Note: If your app is written in Kotlin consider the easypermissions-ktx library which adds Kotlin extensions to the core EasyPermissions library.

Installation

EasyPermissions is installed by adding the following dependency to your build.gradle file:

dependencies {
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
 
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
}

Usage

Basic

To begin using EasyPermissions, have your Activity (or Fragment) override the onRequestPermissionsResult method:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}

Request Permissions

The example below shows how to request permissions for a method that requires both CAMERA and ACCESS_FINE_LOCATION permissions. There are a few things to note:

  • Using EasyPermissions#hasPermissions(...) to check if the app already has the required permissions. This method can take any number of permissions as its final argument.
  • Requesting permissions with EasyPermissions#requestPermissions. This method will request the system permissions and show the rationale string provided if necessary. The request code provided should be unique to this request, and the method can take any number of permissions as its final argument.
  • Use of the AfterPermissionGranted annotation. This is optional, but provided for convenience. If all of the permissions in a given request are granted, all methods annotated with the proper request code will be executed(be sure to have an unique request code). The annotated method needs to be void and without input parameters (instead, you can use onSaveInstanceState in order to keep the state of your suppressed parameters). This is to simplify the common flow of needing to run the requesting method after all of its permissions have been granted. This can also be achieved by adding logic on the onPermissionsGranted callback.
@AfterPermissionGranted(RC_CAMERA_AND_LOCATION)
private void methodRequiresTwoPermission() {
    String[] perms = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION};
    if (EasyPermissions.hasPermissions(this, perms)) {
        // Already have permission, do the thing
        // ...
    } else {
        // Do not have permissions, request them now
        EasyPermissions.requestPermissions(this, getString(R.string.camera_and_location_rationale),
                RC_CAMERA_AND_LOCATION, perms);
    }
}

Or for finer control over the rationale dialog, use a PermissionRequest:

EasyPermissions.requestPermissions(
        new PermissionRequest.Builder(this, RC_CAMERA_AND_LOCATION, perms)
                .setRationale(R.string.camera_and_location_rationale)
                .setPositiveButtonText(R.string.rationale_ask_ok)
                .setNegativeButtonText(R.string.rationale_ask_cancel)
                .setTheme(R.style.my_fancy_style)
                .build());

Optionally, for a finer control, you can have your Activity / Fragment implement the PermissionCallbacks interface.

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted
        // ...
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        // ...
    }
}

Required Permissions

In some cases your app will not function properly without certain permissions. If the user denies these permissions with the "Never Ask Again" option, you will be unable to request these permissions from the user and they must be changed in app settings. You can use the method EasyPermissions.somePermissionPermanentlyDenied(...) to display a dialog to the user in this situation and direct them to the system setting screen for your app:

Note: Due to a limitation in the information provided by the Android framework permissions API, the somePermissionPermanentlyDenied method only works after the permission has been denied and your app has received the onPermissionsDenied callback. Otherwise the library cannot distinguish permanent denial from the "not yet denied" case.

@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
    Log.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

    // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
    // This will display a dialog directing them to enable the permission in app settings.
    if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
        new AppSettingsDialog.Builder(this).build().show();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
        // Do something after user returned from app settings screen, like showing a Toast.
        Toast.makeText(this, R.string.returned_from_app_settings_to_activity, Toast.LENGTH_SHORT)
                .show();
    }
}

Interacting with the rationale dialog

Implement the EasyPermissions.RationaleCallbacks if you want to interact with the rationale dialog.

@Override
public void onRationaleAccepted(int requestCode) {
    // Rationale accepted to request some permissions
    // ...
}

@Override
public void onRationaleDenied(int requestCode) {
    // Rationale denied to request some permissions
    // ...
}

Rationale callbacks don't necessarily imply permission changes. To check for those, see the EasyPermissions.PermissionCallbacks.

LICENSE

	Copyright 2017 Google

   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.