Android Studio Ask User Permission Again if Denied

Previous Tabular array of Contents Next
Video Recording and Paradigm Capture on Android using Camera Intents Android Sound Recording and Playback using MediaPlayer and MediaRecorder

You are reading a sample chapter from the Android Studio three.0 / Android 8 Edition book.

Purchase the fully updated Android Studio Bumble Bee Kotlin Edition of this publication in eBook ($29.99) format

Android Studio Bumble Bee Essentials - Kotlin Edition eBook (PDF) edition contains 94 chapters and over 800 pages
Buy Print Preview Book


In a number of the example projects created in preceding chapters, changes have been made to the AndroidManifest.xml file to request permission for the app to perform a specific task. In a couple of instances, for example, internet admission permission has been requested in order to allow the app to download and display spider web pages. In each case upward until this point, the improver of the asking to the manifest was all that is required in social club for the app to obtain permission from the user to perform the designated task.

There are, however, a number of permissions for which additional steps are required in order for the app to role when running on Android six.0 or later. The starting time of these and then-called "dangerous" permissions will be encountered in the adjacent chapter. Before reaching that point, withal, this chapter volition outline the steps involved in requesting such permissions when running on the latest generations of Android.

Contents


Understanding Normal and Unsafe Permissions

Android enforces security by requiring the user to grant permission for an app to perform sure tasks. Prior to the introduction of Android 6, permission was always sought at the indicate that the app was installed on the device. Figure 73-1, for example, shows a typical screen seeking a variety of permissions during the installation of an app via Google Play.

 As3.0 permissions on install.png 

For many types of permissions this scenario still applies for apps on Android 6.0 or later. These permissions are referred to as normal permissions and are still required to be accepted by the user at the bespeak of installation. A second blazon of permission, referred to as dangerous permissions must also be declared inside the manifest file in the same way every bit a normal permission, but must also be requested from the user when the application is first launched. When such a request is made, it appears in the form of a dialog box as illustrated in Figure 73-2:

As3.0 permission request.png 

The full list of permissions that fall into the dangerous category is contained in Tabular array 73-6:

Permission Group Permission
Agenda READ_CALENDAR
WRITE_CALENDAR
Camera

Camera

Contacts

READ_CONTACTS
WRITE_CONTACTS
GET_ACCOUNTS

Location

ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION

Microphone

RECORD_AUDIO

Telephone

READ_PHONE_STATE
CALL_PHONE
READ_CALL_LOG
WRITE_CALL_LOG
ADD_VOICEMAIL
USE_SIP
PROCESS_OUTGOING_CALLS

Sensors

BODY_SENSORS

phone

SMS
SEND_SMS
RECEIVE_SMS
READ_SMS
RECEIVE_WAP_PUSH
RECEIVE_MMS

Storage

READ_EXTERNAL_STORAGE
WRITE_EXTERNAL_STORAGE



You lot are reading a sample chapter from the Android Studio three.0 / Android viii Edition book.

Purchase the fully updated Android Studio Bumble Bee Kotlin Edition of this publication in eBook ($29.99) format

Android Studio Bumble Bee Essentials - Kotlin Edition eBook (PDF) edition contains 94 chapters and over 800 pages
Buy Print Preview Book

Creating the Permissions Example Project

Create a new project in Android Studio, entering PermissionDemo into the Application proper name field and com.ebookfrenzy as the Visitor Domain setting earlier clicking on the Next button.

On the form factors screen, enable the Phone and Tablet pick and set the minimum SDK setting to API 19: Android 4.four (KitKat). Continue to proceed through the screens, requesting the creation of an Empty Activity named PermissionDemoActivity with a respective layout named activity_permission_demo.


Checking for a Permission

The Android Support Library contains a number of methods that can be used to seek and manage dangerous permissions within the code of an Android app. These API calls tin be made safely regardless of the version of Android on which the app is running, but will but perform meaningful tasks when executed on Android 6.0 or after.

Before an app attempts to make use of a characteristic that requires approving of a unsafe permission, and regardless of whether or not permission was previously granted, the lawmaking must bank check that the permission has been granted. This tin can be accomplished via a phone call to the checkSelfPermission() method of the ContextCompat class, passing through as arguments a reference to the current activity and the permission being requested. The method volition check whether the permission has been previously granted and render an integer value matching PackageManager.PERMISSION_GRANTED or PackageManager.PERMISSION_DENIED.

Inside the PermissionDemoActivity.kt file of the example project, modify the code to check whether permission has been granted for the app to record audio:

parcel com.ebookfrenzy.permissiondemo   import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.Manifest import android.content.pm.PackageManager import android.support.v4.content.ContextCompat import android.util.Log   class PermissionDemoActivity : AppCompatActivity() {       private val TAG = "PermissionDemo"          override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_permission_demo)           setupPermissions()     }       private fun setupPermissions() {         val permission = ContextCompat.checkSelfPermission(this,                 Manifest.permission.RECORD_AUDIO)           if (permission != PackageManager.PERMISSION_GRANTED) {             Log.i(TAG, "Permission to record denied")         }     } }        

Run the app on a device or emulator running a version of Android that predates Android 6.0 and check the log cat output within Android Studio. After the app has launched, the Logcat output should include the "Permission to record denied" bulletin.

Edit the AndroidManifest.xml file (located in the Projection tool window under app -> manifests) and add a line to request recording permission every bit follows:

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.ebookfrenzy.permissiondemoactivity" >       <uses-permission android:name="android.permission.RECORD_AUDIO" />       <application         android:allowBackup="truthful"         android:icon="@mipmap/ic_launcher"         android:characterization="@string/app_name"         android:supportsRtl="truthful"         android:theme="@fashion/AppTheme" >         <activity android:name=".PermissionDemoActivity" >             <intent-filter>                 <action android:name="android.intent.action.Master" />                   <category                    android:proper name="android.intent.category.LAUNCHER" />             </intent-filter>         </activeness>     </application>   </manifest>        

Compile and run the app in one case over again and annotation that this time the permission denial bulletin does not appear. Clearly, everything that needs to be done to request this permission on older versions of Android has been done. Run the app on a device or emulator running Android vi.0 or afterward, however, and note that even though permission has been added to the manifest file, the cheque yet reports that permission has been denied. This is considering Android version vi or later requires that the app as well request dangerous permissions at runtime.

You are reading a sample affiliate from the Android Studio 3.0 / Android viii Edition book.

Buy the fully updated Android Studio Bumble Bee Kotlin Edition of this publication in eBook ($29.99) format

Android Studio Bumble Bee Essentials - Kotlin Edition eBook (PDF) edition contains 94 chapters and over 800 pages
Buy Print Preview Book

Requesting Permission at Runtime

A permission request is made via a telephone call to the requestPermissions() method of the ActivityCompat form. When this method is called, the permission request is handled asynchronously and a method named onRequestPermissionsResult() is called when the chore is completed.

The requestPermissions() method takes equally arguments a reference to the current activity, together with the identifier of the permission existence requested and a asking lawmaking. The asking lawmaking can be whatsoever integer value and will exist used to place which request has triggered the telephone call to the onRequestPermissionsResult() method. Modify the PermissionDemoActivity.kt file to declare a request lawmaking and request recording permission in the result that the permission check failed:

package com.ebookfrenzy.permissiondemo   import android.back up.v7.app.AppCompatActivity import android.bone.Bundle import android.Manifest import android.content.pm.PackageManager import android.support.v4.content.ContextCompat import android.util.Log import android.support.v4.app.ActivityCompat   class PermissionDemoActivity : AppCompatActivity() {       private val TAG = "PermissionDemo"     individual val RECORD_REQUEST_CODE = 101 . .     private fun setupPermissions() {         val permission = ContextCompat.checkSelfPermission(this,                 Manifest.permission.RECORD_AUDIO)           if (permission != PackageManager.PERMISSION_GRANTED) {             Log.i(TAG, "Permission to record denied")             makeRequest()         }     }       private fun makeRequest() {         ActivityCompat.requestPermissions(this,                 arrayOf(Manifest.permission.RECORD_AUDIO),                 RECORD_REQUEST_CODE)     } }        

Next, implement the onRequestPermissionsResult() method so that it reads as follows:

override fun onRequestPermissionsResult(requestCode: Int,               permissions: Assortment<Cord>, grantResults: IntArray) {     when (requestCode) {         RECORD_REQUEST_CODE -> {               if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) {                   Log.i(TAG, "Permission has been denied by user")             } else {                 Log.i(TAG, "Permission has been granted by user")             }         }     } }        

Compile and run the app on an Android 6 or later emulator or device and note that a dialog seeking permission to record sound appears as shown in Figure 73-3:


As3.0 permission request.png


Tap the Allow button and check that the "Permission has been granted past user" bulletin appears in the Logcat console.

In one case the user has granted the requested permission, the checkSelfPermission() method call will return a PERMISSION_GRANTED consequence on future app invocations until the user uninstalls and re-installs the app or changes the permissions for the app in Settings.

You are reading a sample chapter from the Android Studio three.0 / Android viii Edition book.

Purchase the fully updated Android Studio Bumble Bee Kotlin Edition of this publication in eBook ($29.99) format

Android Studio Bumble Bee Essentials - Kotlin Edition eBook (PDF) edition contains 94 chapters and over 800 pages
Buy Print Preview Book

Providing a Rationale for the Permission Asking

Every bit is evident from Figure 73-three, the user has the choice to deny the requested permission. In this instance, the app will continue to request the permission each fourth dimension that it is launched past the user unless the user selected the "Never ask again" option prior to clicking on the Deny button. Repeated denials by the user may indicate that the user doesn't understand why the permission is required by the app. The user might, therefore, be more probable to grant permission if the reason for the requirements is explained when the request is fabricated. Unfortunately, information technology is not possible to change the content of the request dialog to include such an explanation.

An caption is best included in a separate dialog which can be displayed before the request dialog is presented to the user. This raises the question as to when to display this explanation dialog. The Android documentation recommends that an explanation dialog just be shown in the event that the user has previously denied the permission and provides a method to identify when this is the case.

A call to the shouldShowRequestPermissionRationale() method of the ActivityCompat form will render a truthful result if the user has previously denied a request for the specified permission, and a faux consequence if the asking has not previously been fabricated. In the case of a true consequence, the app should brandish a dialog containing a rationale for needing the permission and, one time the dialog has been read and dismissed by the user, the permission request should be repeated.

To add together this functionality to the example app, modify the onCreate() method then that it reads as follows:

. . import android.app.AlertDialog . . individual fun setupPermissions() {     val permission = ContextCompat.checkSelfPermission(this,             Manifest.permission.RECORD_AUDIO)       if (permission != PackageManager.PERMISSION_GRANTED) {         Log.i(TAG, "Permission to record denied")         if (ActivityCompat.shouldShowRequestPermissionRationale(this,                 Manifest.permission.RECORD_AUDIO)) {             val builder = AlertDialog.Architect(this)             builder.setMessage("Permission to access the microphone is required  for this app to record audio.")                     .setTitle("Permission required")               builder.setPositiveButton("OK"             ) { dialog, id ->                 Log.i(TAG, "Clicked")                 makeRequest()             }               val dialog = architect.create()             dialog.show()         } else {             makeRequest()         }     } }        

The method nevertheless checks whether or not the permission has been granted, but at present as well identifies whether a rationale needs to be displayed. If the user has previously denied the request, a dialog is displayed containing an explanation and an OK button on which a listener is configured to call the makeRequest() method when the push is tapped. In the event that the permission request has non previously been made, the code moves direct to seeking permission.

Testing the Permissions App

On the Android 6 or later device or emulator session on which testing is being performed, launch the Settings app, select the Apps pick and scroll to and select the PermissionDemo app. On the app settings screen, tap the uninstall button to remove the app from the device.

Run the app once once again and, when the permission request dialog appears, click on the Deny push button. Terminate the app, run information technology a second time and verify that the rationale dialog appears. Tap the OK push and, when the permission asking dialog appears, tap the Allow push button.

Render to the Settings app, select the Apps selection and select the PermissionDemo app one time once more from the list. In one case the settings for the app are listed, verify that the Permissions section lists the Microphone permission:

As3.0 permission enabled in settings.png

Summary

Prior to the introduction of Android 6.0 the just stride necessary for an app to request permission to admission certain functionality was to add an appropriate line to the application's manifest file. The user would then exist prompted to corroborate the permission at the point that the app was installed. This is still the case for well-nigh permissions, with the exception of a set of permissions that are considered dangerous. Permissions that are considered dangerous unremarkably have the potential to allow an app to violate the user's privacy such equally assuasive access to the microphone, contacts list or external storage.

As outlined in this chapter, apps based on Android 6 or later must now request dangerous permission approval from the user when the app launches in addition to including the permission request in the manifest file.

You are reading a sample affiliate from the Android Studio 3.0 / Android 8 Edition volume.

Purchase the fully updated Android Studio Bumble Bee Kotlin Edition of this publication in eBook ($29.99) format

Android Studio Bumble Bee Essentials - Kotlin Edition eBook (PDF) edition contains 94 chapters and over 800 pages
Buy Print Preview Book


Previous Table of Contents Side by side
Video Recording and Paradigm Capture on Android using Camera Intents Android Audio Recording and Playback using MediaPlayer and MediaRecorder

mccorkleephimagent.blogspot.com

Source: https://www.techotopia.com/index.php/Kotlin_-_Making_Runtime_Permission_Requests_in_Android

0 Response to "Android Studio Ask User Permission Again if Denied"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel