Android Kotlin 中最新的相机权限?

问题描述 投票:0回答:1

私人乐趣 showImagePicDialog() { val options = arrayOf("拍照", "拍摄视频", "选择照片", "选择视频") val builder = AlertDialog.Builder(requireContext()) builder.setTitle("从...选择帖子") builder.setItems(options) { 对话框,其中 -> 当(哪个){ 0 -> 拍摄照片() 1 -> 采取视频() 2 -> 选择照片() 3 -> 选择视频() } } builder.create().show() }

private fun takePhoto() {
    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    startActivityForResult(cameraIntent, 1000)
}

private fun takeVideo() {
    val cameraIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
    startActivityForResult(cameraIntent, 1001)
}

private fun choosePhoto() {
    val cameraIntent = Intent(Intent.ACTION_GET_CONTENT)
    cameraIntent.type = "image/*"
    if (cameraIntent.resolveActivity(requireActivity().packageManager) != null) {
        startActivityForResult(cameraIntent, 1002)
    }
}

private fun chooseVideo() {
    val intent = Intent(Intent.ACTION_GET_CONTENT)
    intent.type = "video/*"
    startActivityForResult(intent, 1003)
}


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    when (requestCode) {

        1000 -> {
            if (resultCode == Activity.RESULT_OK) {
                takePhotoBitmap = data?.extras?.get("data") as? Bitmap
                if (takePhotoBitmap != null) {
                    binding.sImgUploadPost.setImageBitmap(takePhotoBitmap)
                }
            } else {
                requireContext().showToast("Photo capture was canceled or failed")
            }
        }

        1001 -> {
            if (resultCode == Activity.RESULT_OK) {
                takeVideoURI = data?.data
                if (takeVideoURI != null) {
                    // Handle the captured video URI
                    // For example, you can display it in a VideoView
                    binding.sVidUploadPost.setVideoURI(takeVideoURI)
                    binding.sVidUploadPost.start()
                }
            } else {
                // Video recording was canceled or failed
                requireContext().showToast("Video recording was canceled or failed")
            }
        }

        1002 -> {
            if (resultCode == Activity.RESULT_OK && data != null && data.data != null) {
                choosePhotoURI = data?.data

                if (choosePhotoURI != null) {
                    Glide.with(this).load(choosePhotoURI).centerCrop()
                        .transition(DrawableTransitionOptions.withCrossFade())
                        .into(binding.sImgUploadPost)
                }
            } else {
                requireContext().showToast("Photo selection was canceled or failed")
            }
        }

        1003 -> {
            if (resultCode == Activity.RESULT_OK && data != null && data.data != null) {
                chooseVideoURI = data?.data
                if (chooseVideoURI != null) {
                    // Handle the selected video URI
                    // For example, you can display it in a VideoView
                    binding.sVidUploadPost.setVideoURI(chooseVideoURI)
                    binding.sVidUploadPost.start()
                }
            } else {
                requireContext().showToast("Video selection was canceled or failed")
            }
        }
    }
}

startActivityForResult 和 super.onActivityResult(requestCode, resultCode, data) 已弃用,可以解决这个问题吗?

android kotlin android-intent
1个回答
0
投票

private val takePictureLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { 结果 -> if (结果.resultCode == RESULT_OK) { // 照片拍摄并保存成功 // 在 ImageView 中显示捕获的图像 appCompatImageView.setImageURI(Uri.parse(currentPhotoPath)) } 别的 { // 照片拍摄失败或被取消 Toast.makeText(this, "照片拍摄失败或被取消", Toast.LENGTH_SHORT) 。展示() } }

private val pickImageLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK && result.data != null) {
            val selectedImageUri: Uri? = result.data?.data
            if (selectedImageUri != null) {
                // Set the selected image to the ImageView
                appCompatImageView.setImageURI(selectedImageUri)
            } else {
                Toast.makeText(this, "Failed to load image", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "Image selection canceled", Toast.LENGTH_SHORT).show()
        }
    }

private val takeVideoLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // Video recording was successful
            val videoUri = result.data?.data
            if (videoUri != null) {
                setVideoToVideoView(videoUri)
            }
        } else {
            // Video recording failed or was canceled
            Toast.makeText(this, "Video recording failed or was canceled", Toast.LENGTH_SHORT)
                .show()
        }
    }

private val pickVideoLauncher =
    registerForActivityResult(ActivityResultContracts.GetContent()) { videoUri ->
        if (videoUri != null) {
            // Set the selected video to the VideoView
            appCompatVideoView.setVideoURI(videoUri)
            appCompatVideoView.start()
        }
    }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    takePicture = findViewById(R.id.btnTakePicture)
    appCompatImageView = findViewById(R.id.appCompatImageView)
    choosePicture = findViewById(R.id.btnChoosePicture)
    takeVideo = findViewById(R.id.btnTakeVideo)
    appCompatVideoView = findViewById(R.id.appCompatVideoView)
    btnChooseVideo = findViewById(R.id.btnChooseVideo)

    takePicture.setOnClickListener {

        if (!hasPermissions(this, *REQUIRED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, ALL_PERMISSIONS)
        } else {
            Toast.makeText(this, "All Permissions Granted", Toast.LENGTH_SHORT).show()
            Handler(Looper.getMainLooper()).postDelayed({ startCamera() }, 1000)
        }
    }

    choosePicture.setOnClickListener {

        val galleryIntent =
            Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        pickImageLauncher.launch(galleryIntent)
    }

    takeVideo.setOnClickListener {

        if (!hasPermissions(this, *REQUIRED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, ALL_PERMISSIONS)
        } else {
            Toast.makeText(this, "All Permissions Granted", Toast.LENGTH_SHORT).show()
            startVideoRecording()
        }
    }

    btnChooseVideo.setOnClickListener {
        pickVideoLauncher.launch("video/*")
    }

}

private fun startVideoRecording() {
    if (!isRecording) {
        val videoFile = createTempVideoFile()
        videoUri = FileProvider.getUriForFile(
            this, "com.example.makecameraapplication.provider", videoFile
        )
        val videoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
        videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri)
        takeVideoLauncher.launch(videoIntent)
        isRecording = true
    } else {
        stopVideoRecording()
    }
}

private fun stopVideoRecording() {
    isRecording = false
    Toast.makeText(this, "Video recording stopped", Toast.LENGTH_SHORT).show()
}

private fun createTempVideoFile(): File {
    val timeStamp: String = System.currentTimeMillis().toString()
    val storageDir: File? =
        getExternalFilesDir(Environment.DIRECTORY_MOVIES) // Store in Movies directory
    return File.createTempFile(
        "VIDEO_${timeStamp}_", ".mp4", storageDir
    ).apply {
        currentVideoPath = absolutePath
    }
}


private fun setVideoToVideoView(videoUri: Uri) {
    appCompatVideoView.setVideoURI(Uri.parse(currentVideoPath))
    appCompatVideoView.start()
}


private fun hasPermissions(context: Context, vararg permissions: String): Boolean =
    permissions.all {
        ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
    }

private fun createTempImageFile(): File {
    val timeStamp: String = System.currentTimeMillis().toString()
    val storageDir: File? = getExternalFilesDir(null)
    return File.createTempFile(
        "JPEG_${timeStamp}_", ".jpg", storageDir
    ).apply {
        currentPhotoPath = absolutePath
    }
}

private fun startCamera() {
    val imageFile = createTempImageFile()
    val photoURI: Uri = FileProvider.getUriForFile(
        this, "com.example.makecameraapplication.provider", imageFile
    )
    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
    takePictureLauncher.launch(cameraIntent)
}

private fun finishActivity() {
    Toast.makeText(
        this, "You must grant all required permissions to continue", Toast.LENGTH_SHORT
    ).show()/* finish()*/
}

override fun onRequestPermissionsResult(
    requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    when (requestCode) {
        ALL_PERMISSIONS -> {
            if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                startCamera()
            } else {
                finishActivity()
            }
        }
    }
}

companion object {
    const val ALL_PERMISSIONS = 10
    private val REQUIRED_PERMISSIONS = mutableListOf(
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
    ).apply {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }.toTypedArray()
}
© www.soinside.com 2019 - 2024. All rights reserved.