android - 如何使用 intent.ACTION_VIEW 显示图像

标签 android android-intent android-5.1.1-lollipop android-7.1-nougat

我的语法可以在 android 5.1 上运行,但不能在 android 7.1 上运行....

File file = new File(Environment.getExternalStorageDirectory(), "Pictures/1481853170451.jpg");
Toast.makeText(MainActivity.this, file.getPath(), Toast.LENGTH_LONG).show();
Uri path = Uri.fromFile(file);

if (file.exists()) {
  Intent intent = new Intent();
  intent.setAction(android.content.Intent.ACTION_VIEW);
  intent.setDataAndType(path, "image/*");
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {                       
  this.startActivity(intent);
} catch (ActivityNotFoundException e) {
}

谁能告诉我可能的答案。提前谢谢你....

最佳答案

步骤如下

1) 在 AndroidManifest.xml 中,在 application 标签内添加以下 provider

 <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

2) 使用以下示例内容在 res/xml 文件夹中创建 provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="internal_files" path="DATA/TITLE/"/>
</paths>

3) 在Activity中创建图片文件,路径如下所示

  context.getFilesDir() + File.separator + "DATA" + File.separator + "TITLE"+ File.separator + "sample_image_file"

4) 使用以下代码打开图像文件

 Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri photoURI = FileProvider.getUriForFile(context,
                    BuildConfig.APPLICATION_ID + ".provider",
                    new File(context.getFilesDir() + File.separator + "DATA" + File.separator + "TITLE"+ File.separator + "sample_image_file"));
            intent.setDataAndType(photoURI,"image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(Intent.createChooser(intent, "View using"));

关于android - 如何使用 intent.ACTION_VIEW 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42288227/

相关文章:

android - 在 android 上使用 com.android.camera.action.CROP 裁剪保存的图像

android - 相机闪光灯 LED 快速(100Hz 或以上)闪烁

java - 解析后应使用哪种数据结构来存储 XML 的不同标记值

android - 在android中使用sqlite的正则表达式

android - Intent 过滤器 url 在标签后被截断

android - Intent 在ActivityResult 上返回空值

android - 如何在 Android Lollipop 上更改 3g/4g DNS

android - ImageView 共享元素转换(在 Activity 之间)以错误的 scaleType 开始

android - 使用 Runtime.exec(...) 运行 dpm

android - 谷歌地图绘制路线更新运动