当其他应用程序通过FileProvider共享文件时,无法读取我的应用程序中收到的Uri。如果我尝试获取文件路径或从中创建文件,则表示文件不存在。样本Uri来自whatsapp,网址为 content://com.whatsapp.provider.media/item/91836 。当我尝试从Uri读取位图时,它会提供安全性例外。
代码行是onCreate方法:
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)
答案 0 :(得分:0)
在这种情况下,使用此方法对我有用:
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;
}