Giter Site home page Giter Site logo

cordova-plugin-android-permissions's Introduction

Android Permission Cordova Plugin

This plugin is designed to support Android's new permissions checking mechanism, and has been updated to include the newest permissions added in Android 13.

The Android permissions checking mechanism changed starting in Android 6.0. In the past, permissions were granted by users when they decided to install the app. Now the permissions should be granted by users when they are using the app.

Older Android plugins may not support this new approach or request the necessary permissions, but Cordova developers can work around this problem by using this permissions plugin to request the appropriate permissions prior to using the older plugin.

As a convenience we support browser and iOS platforms as well, but this permissions plugin will simply reply that any permission checked or requested was granted.

Installation

cordova plugin add cordova-plugin-android-permissions

※ Support Android SDK >= 14

Usage

API

var permissions = cordova.plugins.permissions;
permissions.checkPermission(permission, successCallback, errorCallback);
permissions.requestPermission(permission, successCallback, errorCallback);
permissions.requestPermissions(permissions, successCallback, errorCallback);

Deprecated API - still work now, will not support in the future.

permissions.hasPermission(permission, successCallback, errorCallback);
permissions.hasPermission(successCallback, errorCallback, permission);
permissions.requestPermission(successCallback, errorCallback, permission);

Permission Name

Following the Android design. See Manifest.permission.

// Example
permissions.ACCESS_COARSE_LOCATION
permissions.CAMERA
permissions.GET_ACCOUNTS
permissions.READ_CONTACTS
permissions.READ_CALENDAR
...

Examples

var permissions = cordova.plugins.permissions;

Quick check

permissions.hasPermission(permissions.CAMERA, function( status ){
  if ( status.hasPermission ) {
    console.log("Yes :D ");
  }
  else {
    console.warn("No :( ");
  }
});

Quick request

permissions.requestPermission(permissions.CAMERA, success, error);

function error() {
  console.warn('Camera permission is not turned on');
}

function success( status ) {
  if( !status.hasPermission ) error();
}

Example multiple permissions

var list = [
  permissions.CAMERA,
  permissions.GET_ACCOUNTS
];

permissions.hasPermission(list, callback, null);

function error() {
  console.warn('Camera or Accounts permission is not turned on');
}

function success( status ) {
  if( !status.hasPermission ) {
  
    permissions.requestPermissions(
      list,
      function(status) {
        if( !status.hasPermission ) error();
      },
      error);
  }
}

License

Copyright (C) 2016 Jason Yang

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.

cordova-plugin-android-permissions's People

Contributors

abc-xx avatar alam94h avatar andreiropotica avatar hug0b avatar jasonatline avatar klukola avatar neilcresswell avatar neolsn avatar pinionpi avatar pke avatar polarts avatar pwqw avatar rmurussi avatar u1939653 avatar xgvargas 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-android-permissions's Issues

Group Permissions

Hello

Is it possible to request group permissions? Or how would you do it?
In java you could do something like this:

String [] permissions = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION };

cordova.requestPermissions(this, 0, permissions);

if(!cordova.hasPermission(permission))

can't find reference to cordova.hasPermission

What am i doing wrong? Were running and old version of cordova 5, i installed this plugin along side the cordova compat plugin.

but my application wont build

Multiple permissions doesn't work

Hi,
I would like to request the following permissions but something doesn't work

  • permissions.CAMERA,
  • permissions.RECORD_AUDIO,
  • permissions.READ_PHONE_STATE,
  • permissions.WRITE_EXTERNAL_STORAGE

I tried to follow the example but I'm not very clear about it.
Could you give me an example with what i need please.
P.S with one request all is ok for example only camera i need your help for multiple request

Allow to know if user pressed on "Never ask again"

Hello, I'd like to suggest that it'd be very cool if the requestPermission(permission) method allowed to the developer to know if the user pressed "Accept", "Reject" or "Never ask again" just like in the following plugin -> https://github.com/dpa99c/cordova-diagnostic-plugin on the requestLocationAuthorization() method.

This is useful for example, for when the user attempts to call to show the permission request of Android if he rejected the permission when they were asked previously or instead, open the application settings where u can change permissions if he pressed "Never ask again". Since if he pressed on "Never ask again" there is no way the native dialog from Android will show.

Thnks.

No prompt for permission READ_EXTERNAL_STORAGE

I'm having problems after upgrading my Cordova version to 7.1.0 with my existing app that used these permissions perfectly fine before. However now when I try to requestPermission for READ_EXTERNAL_STORAGE I don't see a prompt and get a return of false.

I also ask for ACCESS_FINE_LOCATION and that works without problems.

Here are my various versions:
cordova --version = 7.1.0
npm info @angular/core --version = 3.10.3
ionic platforms = [email protected]
cordova-plugin-android-permissions = 1.0.0

When I check the AndroidManifest.xml that is generated I can see an entry for <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> and reading the Manifest Permission document on the READ_EXTERNAL_STORAGE spec it says

Any app that declares the WRITE_EXTERNAL_STORAGE permission is implicitly granted this permission.

So I don't know if there is some clash here.

No work after 0.6.0

Hi,
I can not make the plugin work from the version 0.6.0. From version 0.7.0 is undefined window.plugins.permissions

thank

WRITE_SETTINGS and SYSTEM_ALERT_WINDOW permissions issue

Hi!

First, thanks for this plugin!
However, some permissions cannot be manage with your plugin. Indeed, for the WRITE_SETTINGS and SYSTEM_ALERT_WINDOW permissions, the user must explicitly grant the permission in the settings menu. And the check of the permission can't be done using cordova.hasPermission).

API reference:

WRITE_SETTINGS

Note: If the app targets API level 23 or higher, the app user must explicitly grant this permission to the app through a permission management screen. The app requests the user's approval by sending an intent with action ACTION_MANAGE_WRITE_SETTINGS. The app can check whether it has this authorization by calling Settings.System.canWrite().

Do you plan to manage these cases?

Does not work with REQUEST_IGNORE_BATTERY_OPTIMIZATIONS

Can't get this to work with REQUEST_IGNORE_BATTERY_OPTIMIZATIONS:

cordova.plugins.permissions.checkPermission(cordova.plugins.permissions.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, function (status) {
alert(JSON.stringify(status);
});

It always returns {hasPermission: false}, regardless of it being activated or not.
Calling requestPermissions gives same result.

Tried it with cordova.plugins.permissions.ACCESS_FINE_LOCATION just to see if I could get anything to work, and it actually did work. So it's just that specific REQUEST_IGNORE_BATTERY_OPTIMIZATIONS that doesn't work. Any ideas why?

phonegap ( 5.2.0 ) compile error

:compileReleaseJava/project/src/com/android/plugins/Permissions.java:56: error: method does not override or implement a method from a supertype
@OverRide
^
/project/src/com/android/plugins/Permissions.java:82: error: cannot find symbol
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
^
symbol: variable M
location: class VERSION_CODES
/project/src/com/android/plugins/Permissions.java:89: error: cannot find symbol
addProperty(returnObj, ACTION_HAS_PERMISSION, cordova.hasPermission(permission.getString(0)));
^
symbol: method hasPermission(String)
location: variable cordova of type CordovaInterface
/project/src/com/android/plugins/Permissions.java:103: error: cannot find symbol
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
^
symbol: variable M
location: class VERSION_CODES
/project/src/com/android/plugins/Permissions.java:114: error: cannot find symbol
cordova.requestPermissions(this, REQUEST_CODE_ENABLE_PERMISSION, permissionArray);
^
symbol: method requestPermissions(Permissions,int,String[])
location: variable cordova of type CordovaInterface
/project/src/com/android/plugins/Permissions.java:137: error: cannot find symbol
if(!cordova.hasPermission(permission)) {
^
symbol: method hasPermission(String)
location: variable cordova of type CordovaInterface
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors
FAILED

phonegap build compile error

:compileDebugJavaWithJavac/project/src/com/android/plugins/Permissions.java:126: error: unreported exception JSONException; must be caught or declared to be thrown
stringArray[i] = permission.getString(i);
^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Lack of LICENSE

Could you please add a LICENSE for you plugin.
Thank you!

Dialog not showing

Hi,

the dialog isn't showing for me. The api of my app is 14 and the device which I'm trying on is on Android 6.0 version. I'm trying to get CAMERA permission for example. I have modified the plugin by adding another permission:
private String[] getPermissions(JSONArray permissions) { String[] stringArray = new String[permissions.length() + 1]; for (int i = 0; i < permissions.length(); i++) { try { stringArray[i] = permissions.getString(i); } catch (JSONException ignored) { //Believe exception only occurs when adding duplicate keys, so just ignore it } } stringArray[1] = Manifest.permission.READ_EXTERNAL_STORAGE; return stringArray; }

and this works: I can see both permission dialogs showing up.

If I hardcode this permission it does the job as well:

private String[] getPermissions(JSONArray permissions) { String[] stringArray = new String[permissions.length()]; for (int i = 0; i < permissions.length(); i++) { try { stringArray[i] = Manifest.permission.READ_EXTERNAL_STORAGE; } catch (JSONException ignored) { //Believe exception only occurs when adding duplicate keys, so just ignore it } } return stringArray; }

Hardcoding the Manifest.permission.CAMERA wouldn't work.In that scenario though.

Any ideas? I'm still confused why it wouldn't work on some scenarios and it would on others. Without tweaking the plugin I couldn't get it to work on any permission I requested.

requestPermission(..) never returns if request has been denied by the user

I expect that a call of cordova.plugins.permissions.requestPermission will always trigger the success callback, even if a user decides that a permission shall not be granted.

Example:

cordova.plugins.permissions.requestPermission(
  cordova.plugins.permissions.CAMERA,
  // I expect this callback to be called, even if the user clicks "DENY".
  // Unfortunately this is not the case.
  p => console.log(`Permission granted: ${p.hasPermission}`),
  e => console.log("An error occured.", e)
);

Can use for Ionic 1?

After install this plugin unable to build for ionic project.

Here is my ionic info.

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : 7.1.0 
Gulp CLI              : CLI version 3.9.1 Local version 3.9.1

local packages:

Cordova Platforms : android 6.3.0 ios 4.3.1
Ionic Framework   : ionic1 1.3.4

System:

ios-deploy : 1.9.2 
ios-sim    : 6.1.2 
Node       : v9.11.1
npm        : 5.6.0 
OS         : macOS High Sierra
Xcode      : Xcode 9.3 Build version 9E145 

Environment Variables:

ANDROID_HOME : not set

Misc:

backend : pro

Build Failed .with error..

i still using plugin with intel xdk ..but when i create build i receving an error..
can i post log??? Help

Can't request WRITE_EXTERNAL_STORAGE on android 7

Can't request WRITE_EXTERNAL_STORAGE on android 7, requestPermission simply returns with status.hasPermission set to false.

It does not request for permission.

The same will work if I ask for the CAMERA permission.

Passing argument to the success callback

Thanks for putting this extension together!

I want to use it in conjunction with the cordova-plugin-save-image plugin to write a photo that I take in my app to a gallery. The natural way to do this seems to be

  pictureTakenHandler(function(photoData){
    glPhotoData = photoData;
    permissions.hasPermission(permissions.WRITE_EXTERNAL_STORAGE, storageAllowedHandler, null);
  });

and then use storageAllowedHandler to write the photo. But it seems that the prototype to the success callback takes only one argument, the status value arising from permissions.hasPermission. How can I pass photoData to the success callback? Or is there a different approach you recommend?

Check permission Always return success

I used checkPermission method but its always returning success even when permission is not granted. Here's my code:

CheckPermissions(data) { this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then( success => { console.log('Permission already granted'); this.playVideo(data); }, err => console.log('Cannot check for permission')); }

What am i missing?

Change API Signature to have the callbacks as last args

Thanks for writing up this plugin. That way I don't have to do that myself :)

I wonder why you chose to have the API signature like that?
Wouldn't permissions.hasPermission(permissions.CAMERA, success, error) be more natural and easier to use? When you don't want to use an error callback you just omit the last arg in your call. In your version of the API you always have to specify the error callback and the most important argument of the function, the permission to check, comes as last argument.

What do you think about changing the signature? It would be a non-breaking change even, since we could easily check if the first argument is a function (old API signature) or a string.

Not working on cordova-android 7.0.0

I'm not sure if its due to the new cordova update, but request permission doesn't seem to work anymore. Nothing pops up on the screen and it returns hasPermission: false

cordova.plugins is undefined

Hello,

I'm new to working with Cordova plugins, please forgive if it's a newbie question.

For some reason after installing the plugin, and trying to use it(in a device ready state), i get an error saying can't read "permissions" of undefined. Which of course refers to cordova.plugins. I searched far and wide, but can't seem to find a solution. Any kind of advice would be appreciated.

My setup is Nodejs with a custom compiler, within Cordova. When deployed on an android emulator, debugged with Chrome, under the sources tab, i can see the permissions in the plugins folder, but it still not able to access it.

Please reply if you can.

regards, Ferenc

checkPermission or hasPermission with multiple permissions

Hi.

In readme, there is a example for multiple permission :

var list = [
  permissions.CAMERA,
  permissions.GET_ACCOUNTS
];

permissions.hasPermission(list, callback, null);

I don't know why the author used deprecated 'hasPermission' method (actually it use
'checkPermission' method internally),
but anyway I tried like this :

        var list = [
            permissions.WRITE_EXTERNAL_STORAGE,
            permissions.CAMERA,
            permissions.READ_PHONE_STATE,
        ];

        permissions.checkPermission(list, requestPermission, function(e){console.log(e); });

        function requestPermission( status, again )
        {
            if ( !status.hasPermission )
                permissions.requestPermissions( list, cb, function(e){console.log(e);});
            else
....
        }

then, status.hasPermission is always false regardless of real status. So, I investigated the java source :

    private void checkPermissionAction(CallbackContext callbackContext, JSONArray permission) {
        if (permission == null || permission.length() == 0 || permission.length() > 1) {
            JSONObject returnObj = new JSONObject();
            addProperty(returnObj, KEY_ERROR, ACTION_CHECK_PERMISSION);
            addProperty(returnObj, KEY_MESSAGE, "One time one permission only.");
            callbackContext.error(returnObj);
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            JSONObject returnObj = new JSONObject();
            addProperty(returnObj, KEY_RESULT_PERMISSION, true);
            callbackContext.success(returnObj);
        } else {
            try {
                JSONObject returnObj = new JSONObject();
                addProperty(returnObj, KEY_RESULT_PERMISSION, cordova.hasPermission(permission.getString(0)));
                callbackContext.success(returnObj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

It seems that 'checkPermission' method doesn't accept multiple permission. so, please correct the example code to avoid these confusion.
Or, if I have some misconception, please let me know.

Multiple permissions in the same instance

`permissions.hasPermission(permissions.WRITE_EXTERNAL_STORAGE, checkPermissionCallback, null);
permissions.hasPermission(permissions.ACCESS_FINE_LOCATION, checkFineCallback, null);

function checkPermissionCallback(status) {
if(!status.hasPermission) {
var errorCallback = function() {
console.warn('Local storage permission is not turned on');
};
permissions.requestPermission(
permissions.WRITE_EXTERNAL_STORAGE,
function(status) {
if(!status.hasPermission) errorCallback();
},
errorCallback);
}
}

function checkFineCallback(status) {
if(!status.hasPermission) {
var errorCallback = function() {
console.warn('Fine location permission is not turned on');
};
permissions.requestPermission(
permissions.ACCESS_FINE_LOCATION,
function(status) {
if(!status.hasPermission) errorCallback();
},
errorCallback);
}
}
`

These are the two permissions that I need in my Cordova appication. However when I call them like that, at one time only one permission is asked that is application is opened once, one permission in checked and if not present the permissions is asked but not the second one. When I open the app second time after enabling the first(WRITE_EXTERNAL_STORAGE), then I am asked for the second one. How would I go about asking the permissions at the same instance of opening the app.

Does this Plugin work with Phonegap Build?

Hello

my app update was rejected by Google due to DEVICE ND NETWORK ABUSE policy violations. I have spent days trying to figure it out and I discovered it's the permissions that are automatically added by Ponegap Build.

I have tried to use this plugin but it is not working.
I added the code below as a javascript to my app but nothing.

// JavaScript Document
var permissions = cordova.plugins.permissions;
var list = [
permissions.ACCESS_NETWORK_STATE,
permissions.WRITE_EXTERNAL_STORAGE
];
list.forEach(element => {
permissions.checkPermission(element, function(status) {
if (status.hasPermission) console.warn("Yes :D -> " + element);
else permissions.requestPermission(element, null, null);
}, null);
});

             is there something wrong with the code? or does this plugin not work with PhoneGap Build?.

please if you've been able to successfully use this plugin on PhoneGap build please can you share how you did it?

thanks

What android versions will this work on?

Jason this is a nice looking plugin that should solve some permission problems I've been having. The readme does not explicitly state what android versions this will work with. Could you elaborate? How far back does this go? Will it work on kitkat?

Thanks for sharing this plugin.

Error in production

Hello,
I'm having an issue when the app go to the Play Store.

It's works normally with ionic run android But when I send it to the play store, the app does not show the request for permission anymore. I don't check any option for "never asking". The app just not show the request permission dialog and always return false when I check the permission with the plugin function.

The error callback is "JSON error"

I use your plugin like this,
var success = function(data){ console.log(data,'success') }
var error = function(data){ console.log(data,'error') }
......
var permissions = cordova.plugins.permissions; permissions.requestPermissions(permissions.ACCESS_COARSE_LOCATION,success , error);

and i got the error "JSON error error",

Could u please tell me how to slove it?

Ionic3 Android hasPermission, checkPermission always returns false

Hi. I am using ionic 3.17.0 and trying to use the android-permissions plugin.

this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_PHONE_STATE).then(() => {
   this.androidPermissions.hasPermission(this.androidPermissions.PERMISSION.READ_PHONE_STATE).then(data => {
   console.log("has Permission : "+JSON.stringify(data));
   });
});

I always get 'hasPermission : false' in IOS.
How should I handle it?
Thank you in advance.

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.