1 /* <lambda>null2 * Copyright 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.devicediagnostics 17 18 import android.content.DialogInterface 19 import android.content.Intent 20 import android.net.Uri 21 import android.provider.Settings 22 import androidx.activity.ComponentActivity 23 import androidx.activity.result.contract.ActivityResultContracts 24 import androidx.appcompat.app.AlertDialog 25 26 class PermissionsHelper( 27 private val activity: ComponentActivity, 28 private val permissions: Array<String>, 29 private val onPermissionsGranted: () -> Unit 30 ) { 31 private var permissionsDeniedOnce = false 32 private val requestPermissions = 33 activity.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { 34 permissions -> 35 handlePermissions(permissions) 36 } 37 private var active = false 38 39 private fun handlePermissions(permissions: Map<String, Boolean>) { 40 if (!permissions.entries.all { it.value }) { 41 requestPermissionsAgain() 42 return 43 } 44 onPermissionsGranted() 45 } 46 47 public fun requestPermissions() { 48 if (active) { 49 return 50 } 51 active = true 52 requestPermissions.launch(permissions) 53 } 54 55 private fun requestPermissionsAgain() { 56 val builder = AlertDialog.Builder(activity) 57 builder.setMessage(R.string.grant_eval_permissions_dialog) 58 builder.setNegativeButton( 59 R.string.cancel_button, 60 DialogInterface.OnClickListener { _, _ -> 61 active = false 62 activity.finish() 63 } 64 ) 65 builder.setPositiveButton( 66 R.string.try_again_button, 67 DialogInterface.OnClickListener { _, _ -> 68 // Android doesn't let apps spam users with repeated permissions requests, so after 69 // one failure 70 // we have to direct them to the Settings app to correct things. 71 if (permissionsDeniedOnce) { 72 activity.startActivity( 73 Intent().apply { 74 action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS 75 data = 76 Uri.fromParts( 77 "package", 78 activity.getString(R.string.package_name), 79 null 80 ) 81 } 82 ) 83 active = false 84 } else { 85 requestPermissions.launch(permissions) 86 permissionsDeniedOnce = true 87 } 88 } 89 ) 90 builder.show() 91 } 92 } 93