当文件通过文件提供程序由其他应用程序共享时,我的应用程序中收到的 Uri 不可读。如果我尝试获取文件路径或从中创建文件,则它说文件不存在。示例 Uri 来自 whatsapp 是 content://com.whatsapp.provider.media/item/91836 .当我尝试从 Uri 读取位图时,它会给出安全异常。
代码行打开创建方法:
Uri mediaUri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mediaUri);
清单:
<activity
android:name=".ui.main.MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustNothing">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/mp4" />
<!--<data android:mimeType="video/*" />-->
</intent-filter>
</activity>
例外:
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.whatsapp.MediaProvider from ProcessRecord{fbda37f 23891:com.fayvo/u0a273} (pid=23891, uid=10273) that is not exported from UID 10133
at android.os.Parcel.createException(Parcel.java:1953)
at android.os.Parcel.readException(Parcel.java:1921)
at android.os.Parcel.readException(Parcel.java:1871)
at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:4159)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:6759)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2912)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1879)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1460)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1313)
at android.content.ContentResolver.openInputStream(ContentResolver.java:1033)
at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:919)
在这些情况下使用此方法对我有用:
private File readSharedContentUri(Uri contentUri) {
// Get content resolver.
ContentResolver contentResolver = getContentResolver();
File targetFile = null;
try {
InputStream inputStream = contentResolver.openInputStream(contentUri);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
targetFile = PathUtil.getFilePath(context, true, "received_media_" + System.currentTimeMillis(), CommonUtils.isMimeTypeOfImage(contentResolver.getType(contentUri)) ? ".jpg" : ".mp4");
inputStream.close();
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return targetFile;
}