• Stars
    star
    9,846
  • Rank 3,582 (Top 0.08 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simplify Android M system permissions

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.

More Repositories

1

mlkit

A collection of sample apps to demonstrate how to use Google's ML Kit APIs on Android and iOS
Java
3,534
star
2

google-services

A collection of quickstart samples demonstrating the Google APIs for Android and iOS
Java
3,045
star
3

android-vision

Deprecated: The Mobile Vision API is now a part of ML Kit: Check out this repo:
Java
2,928
star
4

android-testing-templates

Java
1,960
star
5

unity-jar-resolver

Unity plugin which resolves Android & iOS dependencies and performs version management
C#
1,275
star
6

mediapipe

Jupyter Notebook
1,253
star
7

android-custom-lint-rules

This sample demonstrates how to create a custom lint checks and corresponding lint tests
Kotlin
949
star
8

assistant-sdk-python

Samples and bindings for the Google Assistant API
Python
914
star
9

android-vulkan-tutorials

A set of samples to illustrate Vulkan API on Android
C++
849
star
10

arcore-depth-lab

ARCore Depth Lab is a set of Depth API samples that provides assets using depth for advanced geometry-aware features in AR interaction and rendering. (UIST 2020)
C#
777
star
11

android-testdpc

Test DPC is a sample device policy controller for use with Android Enterprise. It gives developers the ability to see how their app will behave in a managed context such as device owner or within a managed profile. Users can set up a work profile, enable work apps, set applications restrictions, manage security polices, and much more. The app also serves as a implementation reference for other DPCs
Java
751
star
12

io2015-codelabs

codelabs for Google I/O 2015
Java
517
star
13

google-photos

Samples for the Google Photos Library API 📸
JavaScript
495
star
14

vulkan-basic-samples

C++
494
star
15

android-play-publisher-api

Java
491
star
16

androidtv-sample-inputs

Sample Channel App (TV Input Service) on Android TV using TIF
Java
487
star
17

oauth-apps-for-windows

OAuth for Apps: Samples for Windows
C#
474
star
18

android-media-controller

Kotlin
448
star
19

android-dynamic-code-loading

Android dynamic code loading sample for Dynamic Feature Modules.
Kotlin
423
star
20

google-signin-unity

Google Sign-In API plugin for Unity game engine. Works with Android and iOS.
C++
407
star
21

android-AppUsageStatistics

Java
366
star
22

web-fundamentals

Google Web Fundamentals
HTML
313
star
23

android-play-safetynet

Samples for the Google SafetyNet Attestation API
Java
287
star
24

io2014-codelabs

Google I/O 2014 Codelabs
Java
177
star
25

android-play-games-in-motion

Java
152
star
26

glass-enterprise-samples

Glass Enterprise Edition 2 Samples
Java
123
star
27

cloud-polymer-go

Sample App Engine application with Go, Cloud Endpoints, and Polymer
HTML
118
star
28

appauth-js-electron-sample

This is an Electron Application, which uses the AppAuth-JS library.
TypeScript
115
star
29

arcore-lightboard

C#
97
star
30

assistant-sdk-cpp

Example of Google Assistant gRPC in C++
C++
96
star
31

android-PermissionRequest

Java
95
star
32

ios-vision

Objective-C
93
star
33

assistant-sdk-nodejs

JavaScript
93
star
34

sceneform-samples

Sceneform samples for 3D rendering for ARCore in Java.
Java
87
star
35

arcore-ml-sample

Java
71
star
36

ios-nearby

Objective-C
68
star
37

arcore-illusive-images

C#
62
star
38

mugo

Sample on how to transpile a small subset of go to Arduino sketches
Go
47
star
39

identity-appflip-android

Lightweight Android app that simulates your native app role during App Flip
Java
34
star
40

identity-toolkit-node

JavaScript
29
star
41

functions-as-a-service

A demo showing Google Cloud Functions + Google Maps Platform
TypeScript
28
star
42

identity-toolkit-go

Identity toolkit sample code for Go
Go
25
star
43

identity-toolkit-java

Java
23
star
44

identity-appflip-tester-android

Lightweight Android app that simulates the Google app role during App Flip
Java
18
star
45

onetwoseven

Programmers debugging web server.
Go
16
star
46

identity-toolkit-php

PHP
15
star
47

android-TensorFlowCloudMachineLearningEngineStylizer

Java
14
star
48

Firebase-Plays-GCP-2016

JavaScript
14
star
49

identity-toolkit-ios

Objective-C
14
star
50

brillo-dragonboard-jacksmart

12
star
51

maps-deckgl-scatterplot-example

JavaScript
11
star
52

io19-sonic-boom

Live coding demo of "Sonic Boom!" talk in Google I/O 2019
C++
11
star
53

meet-live-sharing

Java
10
star
54

identity-appflip-ios

Lightweight iOS app that simulates your native app role during App Flip
Swift
10
star
55

dcp-parser-go

Go
9
star
56

identity-appflip-tester-ios

Lightweight iOS app that simulates the Google app role during App Flip
Swift
9
star
57

amapi

Kotlin
8
star
58

testloopmanager

Java
8
star
59

task-interop

Kotlin
6
star
60

sceneform-poly-browser

Java
6
star
61

subgraph_sdk_sample

Kotlin
6
star
62

identity-toolkit-ruby

HTML
4
star
63

engage-sdk-samples

Set of sample apps that demonstrate how to integrate the SDK in your app to publish different types of content. These apps are a great way to learn how to use the SDK, to get started with the integration in your own app, as well as some best practices.
Java
4
star
64

gboard-dev-samples

Java
4
star
65

identity-toolkit-django

2
star
66

snippets

Hosting for miscellaneous code snippets
2
star
67

pluscode-swift-demo

An example Plus Code service written in Swift
Swift
2
star
68

searchinapps-sample

Kotlin
2
star
69

.allstar

1
star
70

.github

1
star
71

zero-touch-enrollment-colabs

Jupyter Notebook
1
star