这几天研究手机中vCard联系人的导入,直接调用系统程序静默导入,不弹出选择框。
刚开始没有头绪,从网上找的资料如下:
Uri uri = Uri.parse("file:///mnt/sdcard/vcard.vcf");
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setType("text/x-vcard");
startActivity(intent);
这样的方法确实可以,可是会经常弹出选择框,让你自己去选择一次文件,比较烦,不是想要的结果。经过不懈的努力,终于得到了想要的结果。
代码如下:
Uri uri = Uri.parse("file:///mnt/sdcard/mVcard.vcf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/x-vcard");
//android系统版本不同,所以系统中的activity也会不同。
intent.setComponent(
new ComponentName("com.android.contacts","com.android.contacts.vcard.ImportVCardActivity"));
try{
startActivity(intent);
}catch(ActivityNotFoundException e){
intent.setComponent(
new ComponentName("com.android.contacts","com.android.contacts.ImportVCardActivity"));
startActivity(intent);
}
好了,结束,总算是完成了一件事,可以轻松一下了。
android 4.4 kitkat导入联系人又发生了变化,重新添加以下代码
intent.setComponent(
new ComponentName("com.android.contacts","com.android.contacts.common.vcard.ImportVCardActivity"));
startActivity(intent);
4.4系统导入vcard成功。
完善代码,确保不同的系统都能够适配,所以在最后加上系统默认的,以免出错。
Uri uri = Uri.parse("file:///mnt/sdcard/mVcard.vcf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/x-vcard");
//android系统版本不同,所以系统中的activity也会不同。
try{
intent.setComponent(
startActivity(intent);new ComponentName("com.android.contacts","com.android.contacts.vcard.ImportVCardActivity"));
}catch(Exception e){
try{
intent.setComponent(
new ComponentName("com.android.contacts","com.android.contacts.ImportVCardActivity"));
startActivity(intent);
}catch(Exception e){try{
intent.setComponent(
new ComponentName("com.android.contacts","com.android.contacts.common.vcard.ImportVCardActivity"));
startActivity(intent);
}catch(Exception e){
intent.setComponent(null);
startActivity(intent);
}
}
}