android 如何在Kotlin中获取权限结果

jyztefdp  于 2023-02-06  发布在  Android
关注(0)|答案(3)|浏览(231)

我正在尝试在我的Android上使用摄像头。用户将被提示输入摄像头的权限。之前我为它们使用了startActivityForResult和onRequestPermissionRequest。最近我发现它们被弃用了,所以我尝试使用registerForActivity。我设法更改为startActivity,但我被权限请求卡住了。我想知道我是否必须创建另一个permissionlauncher,或者我可以在我的resultlauncher中创建权限。

companion object{
        private const val CAMERA_PERMISSION_CODE = 1
        private const val CAMERA_REQUEST_CODE = 2 
    }
val checkpermission = Manifest.permission.CAMERA

        var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val data: Intent? = result.data
                    val DP: Bitmap = data!!.extras!!.get("data") as Bitmap
                    val image = findViewById<ImageView>(R.id.imageButtonVerifyPhoto)
                    image.setImageBitmap(DP)
                }

            }

        val permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
                isGranted ->
            if(isGranted){
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) 
                resultLauncher.launch((intent))
                Toast.makeText(this,"Permission is tested", Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(this,"Permission is denied",Toast.LENGTH_SHORT).show()
            }

        }
        var cameraButton = findViewById<Button>(R.id.buttonRetakePhoto) // can change later

        cameraButton.setOnClickListener {
            if(ContextCompat.checkSelfPermission(
                    this,
                    checkpermission
                ) == PackageManager.PERMISSION_GRANTED
            ){
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) 
                resultLauncher.launch(intent)

            }else{
                permissionLauncher.launch(checkpermission)
            }
        }

    }

下面是我以前的onRequestPermission代码

override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == CAMERA_REQUEST_CODE){
            if(grantResults.isNotEmpty()&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) 
                startActivityForResult(intent, CAMERA_REQUEST_CODE)
            }else{
                Toast.makeText(this,"Permission is denied",Toast.LENGTH_SHORT).show()
            }
        }
    }
vpfxa7rd

vpfxa7rd1#

请求运行时权限只是稍微简化了一点

private val requestPermission =
    registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        // do something
    }

现在,我们可以调用此函数来获取所需的任何类型的权限

cameraButton.setOnClickListener {
        
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // Pass any permission you want while launching
            requestPermission.launch(Manifest.permission.CAMERA)
        }
    }

确保添加build.gradle

implementation 'androidx.fragment:fragment-ktx:1.2.0' // or later
implementation 'androidx.activity:activity-ktx:1.3.0' // or later

如果你想了解这一切是如何工作的检查这里

gojuced7

gojuced72#

2022年最新解决方案:(没有更多的请求代码)
1.创建帮助器扩展函数(用于Fragment):

fun Fragment.requestPermissions(request: ActivityResultLauncher<Array<String>>, permissions: Array<String>) = request.launch(permissions)

 fun Fragment.isAllPermissionsGranted(permissions: Array<String>) = permissions.all {
     ContextCompat.checkSelfPermission(requireContext(), it) == PackageManager.PERMISSION_GRANTED
 }

1.在Fragment中请求权限:

class FirstFragment : Fragment() {
     companion object {
         private val PERMISSIONS = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
     }

     private lateinit var binding: FragmentFirstBinding
     private lateinit var permissionsRequest: ActivityResultLauncher<Array<String>>

     override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
         binding = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false)
         permissionsRequest = getPermissionsRequest()

         binding.grantButton.setOnClickListener {
             requestPermissions(permissionsRequest, PERMISSIONS)     //extension function
         }

         return binding.root
     }

     private fun getPermissionsRequest() = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
         if (isAllPermissionsGranted(PERMISSIONS)) {             //extension function
             //do your stuff
         } else {
             //do your stuff
         }
     }
 }
9rygscc1

9rygscc13#

您可以尝试Aaper,它允许使用如下注解请求权限:
首先,将权限添加到清单中:

<uses-permission android:name="android.permission.CAMERA" />

然后,注解一个需要使用摄像头的方法:

@EnsurePermissions(permissions = [Manifest.permission.CAMERA])  
fun takePhoto() {  
    Toast.makeText(this, "Camera permission granted", Toast.LENGTH_SHORT).show()  
}

就是这样,当你调用takePhoto方法时,它会检查摄像头权限,如果不可用,它会启动一个权限请求对话框,如果用户同意,它会继续运行takePhoto的body。
免责声明我是阿普的创造者

相关问题