Android-启动CameraIntent活动以使结果崩溃,而模拟器中没有信息

问题描述

我创建了一个使用相机的应用。所以我有一个CameraIntent作为活动开始。 startActivity(cameraIntent)在我拥有的所有设备和仿真器上都能正常工作,但是当我使用startActivityForResult(cameraIntent,1)时,在Pixel 2和Pixel 3XL API 29的仿真器上发生了 CameraApp崩溃。我在真正的华为设备和另一个仿真器(nexus API 30)上进行了尝试,并且可以正常工作。 我在logcat中找不到任何信息,所以我不知道在哪里可以找到错误的原因。我猜是API 29(或Pixel模拟器?),但是我还没有找到有关此问题的任何信息。

编辑:我尝试了许多版本和设备,但是此错误仅在使用API​​ 29的Pixel 2上发生。有人知道为什么吗?

这是我用来复制错误的应用程序的代码: MainActivity.kt


    private lateinit var button: Button

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

        button = findViewById(R.id.button)

        button.setonClickListener {
            val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            if (packageManager.resolveActivity(cameraIntent,PackageManager.MATCH_DEFAULT_ONLY) == null) {
                Toast.makeText(this,"no camera",Toast.LENGTH_SHORT).show()
                return@setonClickListener
            }

            startActivityForResult(cameraIntent,1)
        }

    }

activity_main.xml(只有一个简单的按钮)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

(对不起我的英语。) 谢谢您的帮助!

解决方法

我找到了答案:在API 29上,需要在应用程序内部授予相机授权,以启动相机意图。因此,我在AndroidManifest.xml中添加了<uses-permission android:name="android.permission.CAMERA" />,并在启动摄像头意图之前请求了摄像头许可。

,

确保相机权限附加在清单文件中,并且用户授予的权限是权限代码:

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

如果启用多个权限,则希望您阅读文档并使用此依赖项:

implementation 'com.karumi:dexter:6.2.1'