How to Utilize Ionic/Angular Diagnostic.requestRuntimePermission (Incomplete Documentation)

My current application requires permission for Camera, AudioInput (Microphone), and Storage. Since Android 6, it has become necessary to request these permissions at runtime in order to gain access. To accomplish this, the Ionic 2 Cordova Plugin "Diagnostics" is used, which can be found here.

The documentation provided seems to be incomplete as it only covers how to check the Bluetooth state without detailed information on calling permissions or handling different status scenarios.

After some experimentation, I discovered a function called diagnostic.requestRuntimePermission that could potentially be utilized as follows:


that.diagnostic.requestRuntimePermission('CAMERA')
.then((status) =>{
    switch(status){
        case "GRANTED":
            console.log("Permission granted to use the camera");
            break;
        case "DENIED":
            console.log("Permission denied - should we ask again?");
            break;
        case "DENIED_ALWAYS":
            console.log("Permission permanently denied - may need alternative approach.");
            break;
    }
}).catch(e => console.error(e));

This code snippet is based on assumptions and might not be accurate. For instance, when checking if a camera is available:


let successCallback = (isAvailable) => { console.log('Is camera available? ' + isAvailable); };
let errorCallback = (e) => console.error(e);
that.diagnostic.isCameraAvailable().then(successCallback).catch(errorCallback);

Subsequently, obtaining the authorization status of the camera to determine whether the permission has been granted, denied, or remains unrequested:


that.diagnostic.getCameraAuthorizationStatus()
.then((state) => {
   switch(state){
       /*Work with the state to decide on requesting permission*/
   }
}).catch(e => console.error(e));

However, uncertainty arises regarding the states returned by getCameraAuthorizationStatus and how to handle them effectively:


switch(status){
    case "GRANTED":
        console.log("Permission granted to use the camera");
        break;
    case "DENIED":
        //Call PermissionRequest function here
        console.log("Permission denied - should we try again?");
        break;
    case "DENIED_ALWAYS":
        console.log("Permission permanently denied - alternatives required.");
        break;
}

If you have insights on:

  • The specific statuses returned and how to retrieve them

  • The correct usage of diagnostics.requestRuntimePermission

Feel free to provide guidance or refer to the original discussion on the Ionic 2 Forum here.

Answer №1

It appears that the cordova-plugin you are utilizing for runtime permissions may not be the correct one. The diagnostics plugin is designed to determine the availability of certain device features, such as the camera, rather than request runtime permissions. For this purpose, I recommend using the Android Permissions plugin, which is specifically tailored for requesting permissions during runtime. Additionally, there is an Ionic Native wrapper available for this plugin.

Clarification: To address your specific inquiries: As stated in the Ionic Native wrapper documentation for this plugin, the response to a permission status query will correspond to various properties within an object:

permissionStatus: {
  GRANTED: string;
  DENIED: string;
  NOT_REQUESTED: string;
  DENIED_ALWAYS: string;
  RESTRICTED: string;
  GRANTED_WHEN_IN_USE: string;
};

In your Ionic class, you can access this object by injecting the Ionic-native class into your constructor as follows:

constructor(private diagnostic: Diagnostic){}

You can retrieve the permissionStatus object like this:

this.diagnostic.permissionStatus

Subsequently, you can revise your switch-case statement accordingly:

let permissionStatus = this.diagnostic.permissionStatus;
that.diagnostic.getCameraAuthorizationStatus()
  .then((state) => {
    switch(state){
      case permissionStatus.GRANTED:
        console.log("Permission granted to use the camera");
        break;
      case permissionStatus.DENIED:
        //You should call the PermissionRequest function here
        console.log("Permission denied to use the camera - consider reapplying?");
        break;
      case permissionStatus.DENIED_ALWAYS:
        console.log("Permission permanently denied to use the camera - indicating 
        we cannot utilize it.");
        break;
    }
}).catch(e => console.error(e));

For example, to request camera permission at runtime:

let permission = this.diagnostic.permission;
this.diagnostic.requestRuntimePermission(permission.CAMERA).then(
  success => {
    console.log('requestCameraAuthorization, success', success);
  },
  error => {
    console.log('requestCameraAuthorization, error', error);
  },
);

Notably, manual requests for runtime permission may not be necessary in cases of permissionStatus.DENIED or permissionStatus.NOT_REQUESTED, as per the Ionic documentation. This method automatically prompts for runtime permission unless specified otherwise with a "false" parameter.

If unsure about the outcome of a promise result, logging it to the console (e.g., console.log(success)) can provide clarity. Furthermore, examining the injectable (such as this.diagnostic in your instance) can reveal the available public methods and objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

Utilizing Ajax, Jquery, and Struts2 for File Uploading

Can someone please provide guidance on uploading files using a combination of Ajax, jQuery, and Struts2? I have searched through numerous tutorials online but haven't found a suitable solution yet. The goal is to trigger a JavaScript function when a b ...

At what point are functions executed? What methods can I use to manage their execution?

Looking to make a simple call to an API using jQuery's $.get() function as a JS beginner. The issue I'm facing is that the function seems to be called randomly rather than where I expect it in my code. I am open to either doing everything inside ...

Range slider position not being updated after user interaction

I am working on a webpage with an embedded video and a range slider that serves as a progress bar. Using Javascript, I update the value of the range slider as the video plays, allowing users to navigate through the video content. However, I have encounter ...

Getting errors while working with Expo code in React Native is a common occurrence

I'm attempting to implement drawer navigation in a Snack using Expo's sample code directly from the documentation on Drawer Navigation in React Native You can find the Snack code at this link: Code Sample for troubleshooting Unfortunately, the ...

Having trouble activating the submit function using an external JavaScript file

Having trouble getting the form to submit properly. I have placed the form inside a <div id="access"></div> by setting its innerHTML using an included js file in the header of the page. Here's how it looks: <div id="access"> < ...

The flow of events is not hindered by an if statement, even when the code within it is executed

I'm facing an issue where the console.log statement keeps executing even after calling the search function within the "if statements" in my code. Is there a way to prevent this from happening? function search() { /** * The Tweet checking algori ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

What is the best way to add JavaScript sources to the startup.cs of AspNetCore?

Is there a simple way to link JS sources from a JS project located at "JSProj/src/main.js" and "JSProj/package.json" to execute in "AspNetCoreProj/startup.cs"? How can I ensure that when I run the ASP, my controller from &quo ...

Evaluation of jQuery code

Just starting out with jQuery and programming in general. I posted my first hour of work here and would appreciate some feedback on how to improve it. $(function() { function hideElements() //Hides specified elements on page load. { $("li.credentia ...

actions with frontend routing for CRUD operations

Imagine you are creating a simple CRUD todo application. Whether you choose to use Angular, React, or Vue for routing, the setup will be similar: /todos => see all todos /todos/:id => view one todo by id /todos/:id/edit => edit one todo by id /t ...

Extracting information from state and showcasing it in a dynamic layout using antd

When I try to use languages from the state in this line {({languages}, {add, remove}) => ...., I encounter a problem referencing the state. The error message .map is not a function is displayed. Upon clicking Add another languages, more input fields sho ...

Issues with JavaScript PHP Ajax request

I am currently developing a Single Page Application and facing challenges with Ajax. The two files I am working with are bhart.js and RespSelArt.php. However, my Ajax Call is not functioning as expected. At this point, all I want is to display "worked". H ...

What is the best way to display long text in a browser alert without it being cut off?

Seeking to display a large amount of data in an alert box, but only a portion is currently visible. The following text is all that can be seen: ["19467,1496257152583","19227,1496256651094","19469,1496257033968","17285, ...

Is there a way to execute a function after EACH user interaction?

I am in the process of developing a React Native kiosk application for an Android tablet that will be mounted on a wall. The main requirement is to include a "screen saver" feature, where if the user does not interact with the screen for 30 seconds, it wil ...

The sequence of HTML5 DragDrop Enter and Leave events occur consecutively

I am encountering a problem with a simple drag & drop effect where the class name is changed when the drag enters or leaves, resulting in continuous entering and leaving. Take a look at this basic HTML code: <div class="box"> <div cla ...

"Firebase manages the process of sending password reset emails for users who have not yet

Upon registering with the web application, a verification email is automatically sent to new users. To ensure security, these users are unable to log in until they have verified their email. In the event that the verification link expires and a user forge ...

Attempting to comprehend the reason behind the presence of additional parentheses at the conclusion of a function invocation

Just a quick question I have while experimenting with an example involving OAuth. I want to make sure I fully understand what's going on before incorporating it into my own code. The example uses node, express, and passport-azure-ad. In the code sni ...

Display the user's chosen background image as the backdrop for my activity

As I've been exploring various corners of the internet, I've come across a potential technique for accessing the user's background from within my activity. I've brainstormed a couple of ideas (even though they might seem silly, just to ...

Access your login page with a nodejs mongoDB connection

After successfully sending username, password, and email through postman, the information gets added to the MongoDB schema. However, on the login page in React, it doesn't seem to work correctly. Any assistance would be greatly appreciated. Thank you. ...