Exportar los contactos como archivo VCF

Quiero exportar los contactos del teléfono al área de almacenamiento externo. No trabajé con este tipo de método. ¿Alguien me guía para hacer esto?

En su código, escribió una función, pero ¿de dónde se llama esta función? ¿Y cuál es el significado de la función get(View view) ? Esta función no se está llamando así que se puede quitar.

He editado mi respuesta según sus necesidades y lo he probado con 500 contactos para guardar un único archivo vCard con 500 contactos en mi tarjeta SD.

 package com.vcard; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import android.app.Activity; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.ContactsContract; import android.util.Log; import android.view.View; public class VCardActivity extends Activity { Cursor cursor; ArrayList<String> vCard ; String vfile; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf"; /**This Function For Vcard And here i take one Array List in Which i store every Vcard String of Every Conatact * Here i take one Cursor and this cursor is not null and its count>0 than i repeat one loop up to cursor.getcount() means Up to number of phone contacts. * And in Every Loop i can make vcard string and store in Array list which i declared as a Global. * And in Every Loop i move cursor next and print log in logcat. * */ getVcardString(); } private void getVcardString() { // TODO Auto-generated method stub vCard = new ArrayList<String>(); cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); if(cursor!=null&&cursor.getCount()>0) { cursor.moveToFirst(); for(int i =0;i<cursor.getCount();i++) { get(cursor); Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i)); cursor.moveToNext(); } } else { Log.d("TAG", "No Contacts in Your Phone"); } } public void get(Cursor cursor) { //cursor.moveToFirst(); String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = this.getContentResolver().openAssetFileDescriptor(uri, "r"); // Your Complex Code and you used function without loop so how can you get all Contacts Vcard.?? /* FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String VCard = new String(buf); String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; FileOutputStream out = new FileOutputStream(path); out.write(VCard.toString().getBytes()); Log.d("Vcard", VCard);*/ FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String vcardstring= new String(buf); vCard.add(vcardstring); String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false); mFileOutputStream.write(vcardstring.toString().getBytes()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } 

He quitado la excepción y el otro error y abajo soy mi CÓDIGO:

  private final String vfile = "POContactsRestore.vcf"; Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); phones.moveToFirst(); String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = this.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String vCard = new String(buf); String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; FileOutputStream mFileOutputStream = new FileOutputStream(path, false); mFileOutputStream.write(vCard.toString().getBytes()); Log.d("Vcard", vCard); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } 

Si puede iterar a través de bucle y obtener la vCard para los contactos y almacenar en el SDCARD.

Prueba esto. Su trabajo para mí para crear un archivo .vcf de todos los contactos y lo almacenó en SDCARD.

Asegúrese de que todos los permisos se den correctamente.

 public static void getVCF() { final String vfile = "POContactsRestore.vcf"; Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null); phones.moveToFirst(); for(int i =0;i<phones.getCount();i++) { String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String VCard = new String(buf); String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; FileOutputStream mFileOutputStream = new FileOutputStream(path, true); mFileOutputStream.write(VCard.toString().getBytes()); phones.moveToNext(); Log.d("Vcard", VCard); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } 

He intentado por encima de dos códigos y tengo el archivo .VCF también, pero estaba conteniendo sólo un contacto. Así que aquí está perfectamente editado y ejecutando código …. obtendrá todos los contactos en el archivo .VCF:

 private void getVcardString() throws IOException { // TODO Auto-generated method stub vCard = new ArrayList<String>(); // Its global.... cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); if(cursor!=null&&cursor.getCount()>0) { int i; String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false); cursor.moveToFirst(); for(i = 0;i<cursor.getCount();i++) { get(cursor); Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i)); cursor.moveToNext(); mFileOutputStream.write(vCard.get(i).toString().getBytes()); } mFileOutputStream.close(); cursor.close(); } else { Log.d("TAG", "No Contacts in Your Phone"); } } 

Segundo método:

 private void get(Cursor cursor2) { String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = this.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String vcardstring= new String(buf); vCard.add(vcardstring); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } 

Por favor, no olvide agregar:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

Actualización del turrón de Android:

El código de otras respuestas funciona para mucha gente antes de actualizar el turrón.

Por favor cuide de:

 byte[] buf = new byte[(int) fd.getDeclaredLength()]; 

No está trabajando en Android Nougat .

Fd.getDeclaredLength () siempre es return -1.

Utilice por favor debajo código para los bytes leídos sin ninguna biblioteca:

 byte[] buf = readBytes(fis); public byte[] readBytes(InputStream inputStream) throws IOException { // this dynamically extends to take the bytes you read ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); // this is storage overwritten on each iteration with bytes int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; // we need to know how may bytes were read to write them to the byteBuffer int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } // and then we can return your byte array. return byteBuffer.toByteArray(); } 

El método readBytes () obtiene de esta respuesta.

 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.ContactsContract; import android.app.Activity; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.util.Log; public class Contacts extends Activity{ Cursor cursor; ArrayList<String> vCard ; String vfile; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { getVcardString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void getVcardString() throws IOException { final String vfile = "POContactsRestore.vcf"; // TODO Auto-generated method stub vCard = new ArrayList<String>(); cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); if(cursor!=null&&cursor.getCount()>0) { int i; String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile; FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false); cursor.moveToFirst(); for(i = 0;i<cursor.getCount();i++) { get(cursor); Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i)); cursor.moveToNext(); mFileOutputStream.write(vCard.get(i).toString().getBytes()); } mFileOutputStream.close(); cursor.close(); } else { Log.d("TAG", "No Contacts in Your Phone"); } } private void get(Cursor cursor2) { String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = this.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String vcardstring= new String(buf); vCard.add(vcardstring); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.anthem.contactbackup" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="5" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".Con" android:label="@string/title_activity_contact_backup" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> 

  • Cómo comparar una Lista de Arrays con un contacto móvil
  • Usando la casilla de verificación para filtrar contactos y obtener el número de teléfono
  • AutoCompletar TextView con los contactos
  • ListView de los contactos
  • Desea crear un nuevo grupo en los contactos mediante programación
  • Consulta a ContactsContract.Contacts.CONTENT_FILTER_URI no considera todos los contactos
  • Cómo seleccionar contactos exclusivos de android
  • El permiso de Android 6.0 (Marshmallow) READ_CONTACTS permite leer el nombre del contacto cuando se deniega el permiso
  • Cómo obtener el número de teléfono de los contactos mediante ContentProvider - Android
  • Cómo obtener el número de contacto específico mediante el uso de Id de contacto
  • Selecciona varios contactos de la agenda telefónica en android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.