0

我正在尝试将图像保存到 Android 存储中,它运行良好,但是当涉及到权限对话框时,它会有点中断。

当我拒绝对 API 30 的许可时,它不会再询问,但在较低的情况下效果很好。

这是我的清单

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="28"
        tools:ignore="ScopedStorage"
        />

    <application android:requestLegacyExternalStorage="true">
    ....
    </application>

object Versions {
    const val COMPILE_SDK = 30
    const val MIN_SDK = 23
    const val TARGET_SDK = 30
}

在我的活动中,我有一个存储图像的按钮,并且我有此代码

private var permissionRequest: ActivityResultLauncher<Array<String>> =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            readPermissionGranted =
                permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: readPermissionGranted
            writePermissionGranted =
                permissions[Manifest.permission.WRITE_EXTERNAL_STORAGE] ?: writePermissionGranted

            if (!readPermissionGranted || !writePermissionGranted) {
                //Here the permissions are not granted show a toast
            } else {
                //method to save image
            }
        }

    private fun updateOrRequestPermissions() {
        val hasReadPermission = ContextCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
        val hasWritePermission = ContextCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
        val minSdk29 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q

        readPermissionGranted = hasReadPermission
        writePermissionGranted = hasWritePermission || minSdk29

        val permissionsToRequest = mutableListOf<String>()
        if (!writePermissionGranted) {
            permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        if (!readPermissionGranted) {
            permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        if (permissionsToRequest.isNotEmpty()) {
            permissionRequest.launch(permissionsToRequest.toTypedArray())
        } else {
            //method to save image
        }
    }

当我点击按钮时,我称之为updateOrRequestPermissions. 我错过了什么?

4

0 回答 0