Reputation: 3806
I'm trying to view/open a couple of files I've downloaded to the app storage, but for some reason the spawned action-view activity does not have permission to open the file. Below the fileEntity.getFile()
returns a File instance.
Uri uri = Uri.fromFile(fileEntity.getFile());
Debugger.message("Viewing file of type " + file.mime + " at " + uri);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, fileEntity.mime);
startActivity(intent);
Outputs:
10:44:10.161 5660 com.app VERBOSE Message Viewing file of type application/pdf at file:///data/user/0/com.app/files/1_lol.pdf
10:44:10.421 2551 #2551 ERROR DisplayData openFd: java.io.FileNotFoundException: Permission denied
10:44:10.421 2551 #2551 ERROR PdfLoader Can't load file (doesn't open) Display Data [PDF : 1_lol.pdf] +FileOpenable, uri: file:///data/user/0/com.app/files/1_lol.pdf
This is how I save the file originally, which seem to work:
File file = fileEntity.getFile();
FileOutputStream fos = new FileOutputStream(file);
HttpResponse response = getClient().rawRequest(fileEntity.url);
response.getEntity().writeTo(fos);
response.getEntity().consumeContent();
fos.flush();
fos.close();
The problem is that the file once downloaded can't be opened.
Am I missing something, or have I not understood how internal storage works?
I have these permissions in android manifest;
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Edit So, from all the examples in the android documentation I failed to find any resources about the FileProvider
in the appcompat library. Following the instructions here helped solving the issue.
Upvotes: 3
Views: 2527
Reputation: 520
The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);
And for function: getUriFromFile
private Uri getUriFromFile(File file){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return Uri.fromFile(file);
}else {
return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
}
}
Upvotes: 2