无法使用targetSdk 29在应用程序中获取ContentResolver.openInputStream(Uri uri),并使用API​​ 29在设备上获取compileSdk 29

时间:2020-07-14 03:38:44

标签: android android-contentresolver android-10.0 android-9.0-pie scoped-storage

我有两个应用程序在 Android 10(API 29)设备上运行。从第一个应用程序(“发送者”),我将放置在电话文件系统上的uri文件的图片jpg发送给

Intent intent = new Intent(Intent.ACTION_VIEW);        
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
String mimeType = AppUtils.getFileMimeType(uri, context);
intent.setDataAndType(uri, "image/jpeg");
if (intent.resolveActivity(context.getPackageManager()) != null)
    context.startActivity(Intent.createChooser(intent, "Open with"));

在第二个应用程序(“接收器”)中,我尝试从InputStream上方打开uri

context.getContentResolver().openInputStream(uri);

并得到此异常结果:

java.lang.SecurityException: Permission Denial: reading com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/tree/primary%3AMovies%2FNew/document/primary%3AMovies%2FNew%2FPanorama.jpg from pid=30753, uid=10487 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
    at android.os.Parcel.createException(Parcel.java:2071)
    at android.os.Parcel.readException(Parcel.java:2039)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
    at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:151)
    at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:705)
    at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1687)
    at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1503)
    at android.content.ContentResolver.openInputStream(ContentResolver.java:1187)

如果这两个应用程序在 Android 9(API 28)设备上运行,则没有问题。在 Android 10(API 29)上,有关通过Intent.ACTION_VIEWContentResolver.openInputStream从第三方应用访问uri的内容有何更改??

“发件人”应用具有

compileSdkVersion 30
targetSdkVersion 30

“接收器”应用具有

compileSdkVersion 29
targetSdkVersion 29

android:requestLegacyExternalStorage="true"中的Manifest

1 个答案:

答案 0 :(得分:0)

当“发件人”在 Android 10(API 29)上发送Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION时,应该添加类似intent的符号,但不需要它的原因尚不清楚Android 9(API 28)

Intent intent = new Intent(Intent.ACTION_VIEW);        
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
String mimeType = AppUtils.getFileMimeType(uri, context);
intent.setDataAndType(uri, "image/jpeg");
if (intent.resolveActivity(context.getPackageManager()) != null)
    context.startActivity(Intent.createChooser(intent, "Open with"));