android - 用相机拍照不起作用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);
}
}
}
代码只是该教程的复制粘贴,我只创建了视图和按钮。那么请问大家有没有遇到过类似的情况呢?如果有人可以帮助我解决这个问题,我将不胜感激。
解决方案
我认为您正在启用范围存储的 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() 复制到外部存储
推荐阅读
- json - 使用 API 的 post 方法将图像上传到基于 Laravel 的服务器
- java - JdbcSQLException:唯一索引或主键违规
- android - 为什么 Android 的 allowBackup 不起作用?
- php - 验证 reCaptcha v2 复选框是否已勾选
- angular - 为什么我的 Angular 代码没有按顺序打印/运行?
- php - 将 xampp 升级到最新版本和 php 7.1,但 php 在我的计算机中仍然是 php 5.6
- highcharts - x 轴上标签的宽度,在 Highcharts 中具有分组类别
- c - 无法连接到 Twitch IRC 服务器,IP 地址问题,C 语言
- python - 具有自定义持续时间的计时器/倒计时?
- c# - OpenXmlSDK 无法读取手动创建的 xlsx 文件:'指定的包无效。主要部分不见了。