调用系统的分享功能
//分享文件时调用
public static void shareFiles(String filesPath) {
Uri uri = Uri.parse("file://" + filesPath);
Intent intent = new Intent();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = GenericFileProvider.getUriForFile(App.getContext(), "org.test.provider.GenericFileProvider", new File(filesPath));
intent.setDataAndType(contentUri, getMIMEType(filesPath));
} else {
intent.setDataAndType(uri, getMIMEType(filesPath));
}
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
App.getContext().startActivity(Intent.createChooser(intent, "分享"));
} catch (Exception e) {
e.printStackTrace();
}
}
调用系统的打开功能
//打开文件时调用
public static void openFiles(String filesPath) {
Uri uri = Uri.parse("file://" + filesPath);
Intent intent = new Intent();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Uri contentUri = GenericFileProvider.getUriForFile(App.getContext(), "org.test.provider.GenericFileProvider", new File(filesPath));
intent.setDataAndType(contentUri, getMIMEType(filesPath));
} else {
intent.setDataAndType(uri, getMIMEType(filesPath));
}
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
App.getContext().startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMIMEType(String filePath) {
File file = new File(filePath);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
return type;
}