I have various PDFs in the Android/data/packagename folder of my app and need to be able to edit them. The opening via e.g. Adobe Reader works without any problems and the FileProvider works so far. When I close the PDF Editor, the changed file is not saved. I tried different PDF editors. Unfortunately I haven't found any other alternative so far. Many thanks for your help!
Provider in Manifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
provider_paths.xml
<paths>
<external-path name="external_files" path="."/>
</paths>
Java Code
public void openPDF(SetupFile setup) {
File pdfFile = new File(this.getExternalFilesDir(null).getAbsolutePath() + "/setups", setup.getFileName());
if (pdfFile.exists()) {
try {
Uri uri = FileProvider.getUriForFile(this.getContext(), this.getContext().getPackageName() + ".provider", pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(fThis.getActivity(), getString(R.string.error_no_pdf_editor), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), getString(R.string.error_file_not_exists), Toast.LENGTH_LONG).show();
}
}
You are asking to 'ACTION_VIEW' the file, hence the app honoring your intent will consider it can only read it.
Technically this means the FileProvider.openFile(android.net.Uri,java.lang.String) method will be called just once with "r" mode.
The solution is to use Intent.ACTION_EDIT
Intent intent = new Intent(Intent.ACTION_EDIT);
And so, when the 'editor app' has finish its job, you will see a second call to FileProvider.openFile with mode "rw":
-> your own/local app file will be saved ;-)