随笔

作者: o简单生活o | 来源:发表于2022-03-13 22:12 被阅读0次
    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Build
    import androidx.activity.result.contract.ActivityResultContracts
    import androidx.core.app.ActivityCompat
    import androidx.fragment.app.Fragment
    
    class MyFragment : Fragment() {
    
        companion object {
            val TAG: String = MyFragment::class.java.simpleName
            var PERMISSIONS = arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }
    
        private val permReqLauncher =
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
                val granted = permissions.entries.all {
                    it.value == true
                }
                if (granted) {
                    displayCameraFragment()
                }
            }
    
        private fun takePhoto() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                displayCameraFragment()
            }
            activity?.let {
                if (hasPermissions(activity as Context, PERMISSIONS)) {
                    displayCameraFragment()
                } else {
                    permReqLauncher.launch(
                        PERMISSIONS
                    )
                }
            }
        }
    
        // util method
        private fun hasPermissions(context: Context, permissions: Array<String>): Boolean =
            permissions.all {
                ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
            }
    
        private fun displayCameraFragment() {
            // open camera fragment
        }
    }
    

    相关文章

      网友评论

          本文标题:随笔

          本文链接:https://www.haomeiwen.com/subject/qhiddrtx.html