Android - 在 android 图库中显示图片

Android - show image in android gallery

我需要打开一张照片,我有红色可以使用默认 android 图库,但我无法使用它。
我看了好几个论坛,最后我得到了这个代码,但是它打开了一个黑色图像。
我正在使用 api 最小值 16 和目标值 29,测试 api 29.
有人可以帮助我吗?
谢谢

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("content://"+"/storage/emulated/0/photo.jpg"), "image/*");
startActivity(intent);

已经尝试 Uri.fromFile() 但不起作用。

您可以改用 Uri.fromFile()

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/storage/emulated/0/photo.jpg")), "image/*");
startActivity(intent);

但是您会收到 FileURIExposed 错误,因此您需要在 oncreate() 中添加此代码

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build);

注意:不要使用硬编码路径使用 Environment

不是最佳答案,但效果很好

这是最终的工作代码,感谢大家让我知道 FileProvider

AndroidManifest.xml

<manifest>
    ...
    <application>
        ...
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.myproject.myapp.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>

res/xml/filepaths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="/" name="myInternalMemory" />
</paths>

MainActivity.java

Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.myproject.myapp.fileprovider", new File(filenamePath));
context.grantUriPermission("com.myproject.myapp.fileprovider", contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(contentUri);
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//support from Android 4.1 (API level 16) to Android 5.1 (API level 22) inclusive
intent.setClipData(ClipData.newRawUri("", contentUri));
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);