首页 > 解决方案 > 用相机拍照不起作用Android Studio

问题描述

我是 android studio 的新手,我正在尝试根据教程构建一个应用程序,但由于某种原因我的应用程序崩溃了。我已经搜索并尝试了很多想法,但仍然没有进展。

<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我使用这些权限和提供者看起来像这样。

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.example.android.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>

还有file_path.xml

<?xml version="1.0" encoding="utf-8"?
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Android/data/example.com.camera/files/Pictures" /
</paths>

我还创建了与教程中相同的图像视图和捕获按钮。我尝试调试它,发现这个函数发生了错误,并且代码卡在 if 语句上并且没有传递它。我发现了一些有助于通过 if(将 if 更改为这有助于 getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) 的东西,但是应用程序再次在 FileProvider.getUriForFile() 上崩溃...

 private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

代码只是该教程的复制粘贴,我只创建了视图和按钮。那么请问大家有没有遇到过类似的情况呢?如果有人可以帮助我解决这个问题,我将不胜感激。

标签: androidandroid-intentcamera

解决方案


我认为您正在启用范围存储的 Android 10 或 11 上尝试它。尝试将拍摄的照片保存在内部存储中,因此请更改

<external-files-path name="my_images" 
 path="Android/data/example.com.camera/files/Pictures" /

 <files-path   name="."  path="/" />

并将您的文件保存在 getFiles() 目录而不是外部存储中。如果您还想在图库中查看您拍摄的照片,您可以通过 InputStream() 和 OutputStream() 从 filesDir() 复制到外部存储


推荐阅读