问题
Using a FilePicker I am able to have the user choose a file to upload, pass it to an IntentService, and upload it immediately via that intentService if device has network. But if there is no network, I need to save the Uri and attempt upload later once the devices gets network. This re-attempt is failing. It throws "Permission denial" exception when I try to start the service during the re-attempt. Please let me know what might be wrong. Appreciate your help.
FILEPICKER
-----------
openFilePickDialog = new Intent();
openFilePickDialog.setType("*/*");
openFilePickDialog.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(openFilePickDialog, "Select File"), PickFileId);
During re-attempt of upload
----------------------------
Intent iUploadService = new Intent(context, UploadService.class);
String uriString = pendingUpload.uriString;
iUploadService.setData(Uri.parse(uriString));
iUploadService.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
iUploadService.putExtra(UploadService.ACTION, UploadService.ACTION_UPLOAD);
context.startService(iUploadService);
Stacktrace
-----------
java.lang.SecurityException: UID 10140 does not have permission to content://com.android.externalstorage.documents/document/primary%3AAndroid%2Fdata%2Fcom.aaaa.bbbb%2Ffiles%2FFolder%2FAttachments%2F1587129056397_IMG-20200414-WA0004.jpg [user 0]; you could 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.os.Parcel.readException(Parcel.java:1987)
at android.app.IActivityManager$Stub$Proxy.startService(IActivityManager.java:5166)
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1601)
at android.app.ContextImpl.startService(ContextImpl.java:1571)
at android.content.ContextWrapper.startService(ContextWrapper.java:669)
回答1:
Dont use ACTION_GET_CONTENT as as you have seen the permission to read does not live long.
Instead use ACTION_OPEN_DOCUMENT and take persistable uri permission in onActivityResult.
来源:https://stackoverflow.com/questions/61318414/android-10-able-to-upload-a-uri-directly-but-fails-with-permission-denial-exc