打开第三方应用选择并过滤掉不想被打开的应用

来源:互联网 发布:linux wget 404 编辑:程序博客网 时间:2024/05/14 21:22

由于最近做项目时,客户需要打开各种文档,比如ppt,ppts,doc,docx,pdf,txt等文件,当用户没有安装打开这些文件的第三方程序时,会自动调用QQ,让用户感觉不好,这里我们做了一下过滤。
File file = new File(“文件名”);
// 文件file的MIME类型 打开
Intent intent = new Intent(Intent.ACTION_VIEW);
String fileName= file.getAbsolutePath();
String type=”“;
//这里例举了各种文档格式的所需的Type值
if (fileName.endsWith(“txt”)) {
type=”text/plain”;
} else if (fileName.endsWith(“doc”)) {
type=”application/msword”;
} else if (fileName.endsWith(“docx”)) {
type=”application/vnd.openxmlformats-officedocument.wordprocessingml.document”;
} else if (fileName.endsWith(“pptx”)) {
type=”application/vnd.openxmlformats-officedocument.presentationml.presentation”;
} else if (fileName.endsWith(“ppt”)) {
type=”application/vnd.ms-powerpoint”;
} else if (fileName.endsWith(“xls”)) {
type=”application/vnd.ms-excel”;
} else if (fileName.endsWith(“xlsx”)) {
type=”application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”;
} else if (fileName.endsWith(“pdf”)) {
type= “application/pdf”;
}
intent.setDataAndType(Uri.fromFile(file), type);

List resInfo = getPackageManager().queryIntentActivities(intent, 0);
if (!resInfo.isEmpty()) {
List targetedShareIntents = new ArrayList();
for (ResolveInfo info : resInfo) {
Intent targeted = new Intent(Intent.ACTION_VIEW);
targeted.setDataAndType(Uri.fromFile(file), type);
ActivityInfo activityInfo = info.activityInfo;
//在这里根据包名过滤掉不想选择的应用,比如QQ
if (activityInfo.packageName.contains(“com.tencent.mobileqq”)) {
continue;
}
targeted.setPackage(activityInfo.packageName);
targetedShareIntents.add(targeted);
}
if (targetedShareIntents.size()!=0){
Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0),”请你选择以下应用打开”);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
startActivity(chooserIntent);
}else {
Toast.makeText(this, “没有可选程序”, Toast.LENGTH_SHORT).show();
}
“`

0 0