FileProvider授权异常:无法在其他应用打开文件求助
Hey there! Let's dig into why other apps can't access the file you're sharing via FileProvider—this is a super common gotcha for folks new to Android's file sharing system, so don't beat yourself up over it.
The Core Problem: Overwritten Intent Flags
Looking at your code, the main issue is how you're setting Intent flags. Every time you call setFlags(), it replaces all existing flags on the Intent. So when you do:
openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); openIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); openIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Only the last flag (FLAG_ACTIVITY_NO_HISTORY) sticks—your read/write permissions get completely overwritten. That's why other apps don't have permission to open the file!
Fixed Code
Replace those setFlags() calls with addFlags() to append flags instead of replacing them:
File fileToOpen = new File(Environment.getExternalStorageDirectory(), path); // First, double-check the file exists to avoid unnecessary errors if (!fileToOpen.exists()) { // Handle missing file (e.g., show a toast to the user) return; } Uri contentUri = FileProvider.getUriForFile(this, "me.albie.share", fileToOpen); Intent openIntent = new Intent(Intent.ACTION_VIEW); // Use addFlags() to keep all permissions and activity flags openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); openIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); openIntent.setDataAndType(contentUri, "application/pdf"); openIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); PackageManager pm = this.getPackageManager(); if (openIntent.resolveActivity(pm) != null) { this.startActivity(Intent.createChooser(openIntent, "Open file")); }
Quick Additional Checks
Just to cover all bases, make sure these are in order too:
- FileProvider Dependency: If you're using a newer AndroidX project, your Manifest should reference
androidx.core.content.FileProviderinstead of the support library version. Double-check that theandroid:namein your provider tag matches your project's setup. - Path Configuration: Your
file_paths.xmllooks correct—external-path name="external_files" path="/"grants access to the entire external storage, which should work for your file location. - Android 10+ Scoped Storage: If your app targets API 30 or higher, ensure you've requested the
READ_EXTERNAL_STORAGEpermission (for public files) or use MediaStore if you're dealing with media files.
That should fix the permission issue! Let me know if you run into any other snags.
内容的提问来源于stack exchange,提问作者Kevin Walter

