将联系人导出为VCF文件

Pra*_*mar 13 android vcf android-contacts

我想将手机通讯录导出到外部存储区域.我没有使用这种方法.有人指导我这样做吗?

sam*_*m_k 27

在你的代码中,你编写了一个函数但是从哪里调用了这个函数?get(View view)功能是什么意思?此函数未被调用,因此可以将其删除.

我根据您的要求编辑了我的答案,并使用500个联系人进行了测试,以便在我的SD卡中保存一个包含500个联系人的vCard文件.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


SAN*_*NAT 8

Android Nougat更新:

其他答案代码在Nougat更新之前为很多人工作.

请注意:

byte[] buf = new byte[(int) fd.getDeclaredLength()];
Run Code Online (Sandbox Code Playgroud)

不适用于Android Nougat.

fd.getDeclaredLength()始终返回-1.

请使用以下代码读取没有任何库的读取字节:

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();
}
Run Code Online (Sandbox Code Playgroud)

readBytes()方法来自这个答案.


Din*_*ati 7

我删除了异常和其他错误,下面是我的代码:

    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();
            }
Run Code Online (Sandbox Code Playgroud)

如果您可以遍历循环并获取联系人的vCard并将其存储在SDCARD中.


pra*_*tik 7

试试这个.它为我创建了一个所有联系人的.vcf文件,并将其存储到SDCARD中.

确保所有权限都得到妥善处理.

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();
     }

 }
}
Run Code Online (Sandbox Code Playgroud)


Cau*_*ues 6

我尝试了两个代码,我也得到了.VCF文件,但它只包含一个联系人.所以这里是完美编辑和运行代码....你将获得.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");
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种方法:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

请不要忘记添加:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)