android 动作图像捕获输出为0字节

s4chpxco  于 2023-01-28  发布在  Android
关注(0)|答案(2)|浏览(154)

我在运行Android 11的CAT S42上拍摄照片时遇到了问题。我的代码在旧手机上运行良好,所以我怀疑这是Android版本的问题。以下代码创建了JPG文件,但它总是零字节:

private void startCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            File mNewPhoto = new File(getFilesDir(), "data-input-image.jpg");
            mNewPhoto.delete();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mNewPhoto));
            startActivityForResult(intent, 1);
        }
    }

我一直在尝试使用不同的保存位置和权限,但无法修复。
我在清单中获得了这些权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
xtfmy6hx

xtfmy6hx1#

不要使用Uri.fromFile()获取URI。
而是使用文件提供者.getUriForFile()。

dgenwo3n

dgenwo3n2#

    • 安卓清单. xml**
<application>
      ...
      <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
 </application>
    • 文件路径. xml**
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path
        name="files"
        path="." />
    <external-path
        name="external"
        path="." />
</paths>
    • Java代码**
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
String filename = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath() + "/wallpaper.jpg";
Uri fileProvider = FileProvider.getUriForFile(this, getPackageName() + ".fileProvider", new File(filename));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileProvider);
Intent chooserIntent = Intent.createChooser(cameraIntent, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{cameraIntent});
chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(chooserIntent, 1);

相关问题