微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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应用程序开发的现代书籍.

原文地址:https://www.jb51.cc/android/309863.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐