使用Android Nougat在图库中打开图片

我想在 Android Nougat上的库中打开已保存的图像,但我得到的是一个黑色的图库页面,上面写着“无法加载照片”.

那是我的代码

表现

<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>

provider_paths.xml

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

DrawView中生成的路径

public static boolean save(Bitmap bitmap){
    Date Now = new Date();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy'_'HH:mm");

    File folder = new File(Environment.getExternalStorageDirectory() +
            File.separator + "Crash");
    if (!folder.exists()) {
        folder.mkdirs();
    }

    FileOutputStream fos = null;
    try {
        lastimagePath = new File(Environment.getExternalStorageDirectory().toString() + "/Crash/" + simpleDateFormat.format(Now) + ".jpg");
        fos = new FileOutputStream(lastimagePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);

        fos.flush();
        fos.close();
        fos = null;
        return true;
    } catch (IOException e) {
        e.printstacktrace();
        return false;
    }

    finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {}
        }
    }
}

打开图像侦听器

private class OpenImageListener implements View.OnClickListener{

    @Override
    public void onClick(View v) {
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + DrawView.getLastimagePath().getAbsolutePath()),"image/*");
            startActivity(intent);
        } else {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri photoUri = FileProvider.getUriForFile(MainActivity.this,BuildConfig.APPLICATION_ID + ".provider",DrawView.getLastimagePath());
            intent.setData(photoUri);
            startActivity(intent);
        }
    }
}

也许我为图像生成了一条错误的路径,但是旧的版本它可以工作(我在Marshmallow上试过并且效果很好).

有人能帮我吗?谢谢.

解决方法

在onClick()的else块中,在Intent上调用setData()来设置Uri之后,在Intent上调用addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION).

目前,其他应用程序无权使用Uri标识的内容.添加FLAG_GRANT_READ_URI_PERMISSION可以做到这一点.

这在the FileProvider documentation中有所介绍,还有关于Android应用程序开发的现代书籍.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...