In my application I'd like to show a help file (PDF) to the user. The help file is published as asset and on first request copied to the external storage. Adobe Acrobat Reader starts but does not show the file.
What am I missing ?
I use platform package 21 and Acrobat Reader 20.1.1 on Android 9.1.
Note: Via the file viewer I can see the file and on touching Adobe Acrobat Reader opens with the file. Adobe Acrobat Reader is set as default application with option "Always".
Here is the code:
public static void open(Activity activity)
{
// copy help file to external storage
String filename = "helpfile.pdf";
File pubFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+filename);
if(!pubFile.exists())
{
InputStream ims = null;
try {
ims = activity.getAssets().open(filename);
Files.copy(ims, pubFile.toPath(),StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
if(ims != null)
{
try {
ims.close();
pubFile.delete();
} catch (IOException e1) {
e1.printStackTrace();
Toast.makeText(activity, "Failed to copy help file to accessible folder.", Toast.LENGTH_SHORT);
return;
}
}
e.printStackTrace();
Toast.makeText(activity, "Failed to copy help file to accessible folder.", Toast.LENGTH_SHORT);
return;
}
}
// open the help file with application for PDF files (Adobe Acrobat)
if(pubFile.exists() && pubFile.canRead())
{
// EDIT Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(pubFile));
Intent intent = new Intent(Intent.ACTION_VIEW, FileProvider.getUriForFile(activity
, "com.myapp.fileprovider"
, pubFile)); // EDIT
intent.setType("application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
if (activities.size() > 0) {
activity.startActivity(intent);
} else {
Toast.makeText(activity, "No application to show help file.", Toast.LENGTH_SHORT);
}
}
}
EDIT
Here is what I did due to the recommendation of CommonsWare
Replaced Uri.fromFile(...) with FileProvider.getUriForFile(...) (see code above)
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myapp" android:versionCode="1" android:versionName="1.0">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.myapp.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</manifest>
- src\android\res\xml\file_paths.xml:
<paths>
<external-path name="external" path="." />
</paths>