我有一个文件的路径,我希望设备用另一个应用程序打开该文件
public static void openUrl(Context context, String path) {
Uri uriForFile;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
uriForFile = GenericFileProvider.getUriForFile(context,"xyz.provider",new File(path));
}else{
uriForFile = Uri.fromFile(new File(path));
}
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(fileExt(path).substring(1));
newIntent.setDataAndType(uriForFile, mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, R.string.msg_noHandlerForThisTypeOfFile, Toast.LENGTH_LONG).show();
}
}
以上代码在 api 23 及更低版本上运行良好
但是在 android 7 中,当我想打开一个 mp3 文件时,例如它 toast “播放器不支持这种类型的音频文件”
或者当我打开一张图片时,它会打开一个带有图库应用程序的空白页面。
最佳答案
替换:
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
与:
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_GRANT_READ_URI_PERMISSION);
目前,第三方应用对您的 GenericFileProvider
内容没有任何权利。
关于java - 如何在 API 24 及更高版本的另一个应用程序中打开文件 - android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45001337/