使用Android Nougat在图库中打开图像
我想在Android Nougat的库中打开已保存的图片,但我得到的是一个黑色图库页面,上面写着无法加载照片。
I want to open a saved image in gallery on Android Nougat but what I get is a black gallery page with message "Can't load the photo".
这是我的代码:
清单
<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上尝试并且效果很好)。
Maybe I generate a wrong path for the image, but with old version it works (I tried on Marshmallow and works great).
有人可以帮助我吗?谢谢。
Can someone help me? Thanks.
在 else
块中> onClick(),在 Intent
上调用 setData()
后设置 Uri ,在 Intent
上调用 addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
。
In your else
block in onClick()
, after calling setData()
on your Intent
to set the Uri
, call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
on the Intent
.
目前,其他应用程序无权使用 Uri
标识的内容。添加 FLAG_GRANT_READ_URI_PERMISSION
执行此操作。
As it stands, the other app has no rights to work with the content identified by the Uri
. Adding FLAG_GRANT_READ_URI_PERMISSION
does this.
这包含在 FileProvider
文档,以及现代书籍Android应用开发。
This is covered in the FileProvider
documentation, along with modern books on Android app development.