Android: 使用系统应用选择器打开/分享文件

  1. 使用应用选择器打开文件
// ACTION_VIEW Intent动作为查看
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(path);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    uri = FileProvider.getUriForFile(getContext(),
                    getContext().getPackageName() + ".fileprovider",
                    file);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
    uri = Uri.fromFile(file);
}
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension( extension);
//设置数据和描述类型
intent.setDataAndType(uri, mime);
//创建应用选择器 然后跳转
startActivity(Intent.createChooser(intent, "title"));

2. 分享文件

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Share Content.");
Intent chooserIntent = Intent.createChooser(shareIntent, "Chooser Title");
startActivity(chooserIntent);

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注