Issue
I have written a code that open a file like pdf. For that I used intent like the below one:
public void openFile(Context context, File file) {
String typeFile = "application/pdf";
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), typeFile);
PackageManager pm = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setType(typeFile);
Intent openInChooser = Intent.createChooser(intent, "Choose");
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
if (resInfo.size() > 0) {
try {
context.startActivity(openInChooser);
} catch (Throwable throwable) {
Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
// PDF apps are not installed
}
} else {
Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
}
}
}
My problem is when I run this code on Android 10 and 11, the Toast in else is executed but in older versions these codes work correctly.
So what should I do to open file in Android 10 and 11?
Solution
Your app should be crashing on Android 7.0+ with a FileUriExposedException
. You need to get rid of Uri.fromFile()
and switch to FileProvider
.
Also, you can get rid of queryIntentActivities()
. You do not need it, partly because there should always be a chooser, and partly because you have the try
/catch
block to catch the ActivityNotFoundException
if there is no chooser for some strange reason. If your reason for queryIntentActivities()
is to avoid an empty chooser, stop creating a chooser — the OS will add one automatically if one is appropriate. Alternatively, for Android 11+, you will need to deal with package visibility rules to be able to call queryIntentActivities()
. See this and this for more.
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.