使用联系人应用程序直接打开 .vcf vCard 文件 [英] Open .vcf vCard file directly with contacts app
问题描述
我正在尝试以编程方式启动联系人应用程序以导入包含大量联系人的大型 .vcf 文件.以下代码几乎完美运行.
I'm trying to programmatically start the contacts app to import a big .vcf file with a lot of contacts. The following code works almost perfect.
String vcfMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("vcf");
Intent openVcfIntent = new Intent(Intent.ACTION_VIEW);
openVcfIntent.setDataAndType(Uri.fromFile(savedVCardFile), vcfMimeType);
startActivity(openVcfIntent);
唯一的问题是 Android 会显示一个应用选择器对话框,不仅显示联系人应用,还显示 Dropbox(或任何其他处理 vCard 文件的应用).我想防止这种行为并直接使用联系人应用打开文件,以便自动开始导入.
The only problem is that Android shows an app chooser dialog, showing not only the contacts app, but also Dropbox (or any other app that handles vCard files). I want to prevent this behavior and directly open the file with the contacts app, so that the import starts automatically.
我已经尝试了在 StackOverflow 上发现的一些东西,但没有成功,例如设置:
I've tried several things found on StackOverflow with no luck, such as setting:
openVcfIntent.setComponent(new ComponentName("com.android.contacts", "com.android.contacts.DialtactsContactsEntryActivity"));
openVcfIntent.setAction("android.intent.action.MAIN");
openVcfIntent.addCategory("android.intent.category.LAUNCHER");
openVcfIntent.addCategory("android.intent.category.DEFAULT");
关于如何解决这个问题的任何想法?
Any ideas on how to approach the issue?
推荐答案
回答我自己的问题.感谢 关于显式意图的答案.
Answering my own question. I finally found a way to automatically open a vCard with the contacts app, thanks to this answer about explicit intents.
private void openBackup(File savedVCard)
{
try
{
String vcfMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("vcf");
Intent openVcfIntent = new Intent(Intent.ACTION_VIEW);
openVcfIntent.setDataAndType(Uri.fromFile(savedVCard), vcfMimeType);
// Try to explicitly specify activity in charge of opening the vCard so that the user doesn't have to choose
// https://stackoverflow.com/questions/6827407/how-to-customize-share-intent-in-android/9229654#9229654
try
{
if (getActivity().getPackageManager() != null)
{
List<ResolveInfo> resolveInfos = getActivity().getPackageManager().queryIntentActivities(openVcfIntent, 0);
if (resolveInfos != null)
{
for (ResolveInfo resolveInfo : resolveInfos)
{
ActivityInfo activityInfo = resolveInfo.activityInfo;
if (activityInfo != null)
{
String packageName = activityInfo.packageName;
String name = activityInfo.name;
// Find the needed Activity based on Android source files: http://grepcode.com/search?query=ImportVCardActivity&start=0&entity=type&n=
if (packageName != null && packageName.equals("com.android.contacts") && name != null && name.contains("ImportVCardActivity"))
{
openVcfIntent.setPackage(packageName);
break;
}
}
}
}
}
}
catch (Exception ignored)
{
}
startActivity(openVcfIntent);
}
catch (Exception exception)
{
// No app for openning .vcf files installed (unlikely)
}
}
这篇关于使用联系人应用程序直接打开 .vcf vCard 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!