将联系人导出为 VCF 文件

发布于 2024-12-16 00:41:19 字数 45 浏览 3 评论 0原文

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

I want to export the Phone contacts to External storage area. I didn't work with this type of method. Anyone guide me to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

醉生梦死 2024-12-23 00:41:19

在你的代码中,你编写了一个函数,但是这个函数是从哪里调用的呢? 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();
        }
    }
}

In your code, you wrote one function but from where is this function called? And what is the meaning of get(View view) function? This function is not being called so it can be removed.

I've edited my answer as per your requirements and tested it with 500 Contacts to save a single vCard file with 500 contacts in my sd card.

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();
        }
    }
}
喜爱皱眉﹌ 2024-12-23 00:41:19

Android Nougat 更新:

在 Nougat 更新之前,其他答案代码适用于很多人。

请注意:

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

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

方法 readBytes() 从 this 答案中获取。

Android Nougat Update :

Other answers code working for lots of people before Nougat update.

Please take care of :

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

is not working on Android Nougat.

fd.getDeclaredLength() is always return -1.

Please use below code for read bytes without any library :

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

The method readBytes() get from this answer.

娇柔作态 2024-12-23 00:41:19

试试这个。它的工作是为我创建所有联系人的 .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();
     }

 }
}

Try out this. its work for me to create a .vcf file of all contact and stored it into SDCARD.

make sure all permission are give properly.

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

 }
}
风向决定发型 2024-12-23 00:41:19

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

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

如果您可以迭代循环并获取联系人的 vCard 并将其存储在 SDCARD 中。

I have removed the exception and other error and below is my CODE :

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

If you can iterate through loop and get the vCard for the contacts and store it in the SDCARD.

梦亿 2024-12-23 00:41:19

我尝试了以上两个代码,也得到了 .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");
    }
}

第二种方法:

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

请不要忘记添加:

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

I tried above two codes and I got the .VCF file too, but it was containing only one contact. so here is Perfectly Edited and running code....you will get all contacts in .VCF file:

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

Second Method:

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

Please Don't forget to add :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
妄断弥空 2024-12-23 00:41:19

它适用于我,也适用于牛轧糖设备。非常感谢@pratik 和@sanat。

public static void getVCF(Context context)
    {

        final String vfile = "POContactsRestore.vcf";

        Cursor phones = context.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 = context.getContentResolver().openAssetFileDescriptor(uri, "r");
                FileInputStream fis = fd.createInputStream();
                byte[] buf = readBytes(fis);
                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();
            }

        }
    }

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

It's working for me and as well working in Nougat devices. Thank you so much @pratik and @sanat .

public static void getVCF(Context context)
    {

        final String vfile = "POContactsRestore.vcf";

        Cursor phones = context.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 = context.getContentResolver().openAssetFileDescriptor(uri, "r");
                FileInputStream fis = fd.createInputStream();
                byte[] buf = readBytes(fis);
                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();
            }

        }
    }

    public static 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();
    }
云仙小弟 2024-12-23 00:41:19
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>

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>

左秋 2024-12-23 00:41:19
private void convertToVcfFile(String contactId, File contactFile) {
    Cursor mCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null, ContactsContract.CommonDataKinds.Phone._ID + " = " + contactId,
            null, null);
    if(mCursor != null && mCursor.moveToFirst()) {
        do {
            String mLookupKey = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            Uri mUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, mLookupKey);
            try {
                AssetFileDescriptor mAssetFileDescriptor = getContentResolver().openAssetFileDescriptor(mUri, "r");
                if (mAssetFileDescriptor != null) {
                    FileInputStream mFileInputStream = mAssetFileDescriptor.createInputStream();
                    byte[] mBuffer = new byte[(int) mAssetFileDescriptor.getDeclaredLength()];
                    mFileInputStream.read(mBuffer);
                    String VCardString = new String(mBuffer);
                    FileOutputStream mFileOutputStream = new FileOutputStream(contactFile, true);
                    mFileOutputStream.write(VCardString.getBytes());
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } while (mCursor.moveToNext());
        mCursor.close();
    }
}
private void convertToVcfFile(String contactId, File contactFile) {
    Cursor mCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null, ContactsContract.CommonDataKinds.Phone._ID + " = " + contactId,
            null, null);
    if(mCursor != null && mCursor.moveToFirst()) {
        do {
            String mLookupKey = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            Uri mUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, mLookupKey);
            try {
                AssetFileDescriptor mAssetFileDescriptor = getContentResolver().openAssetFileDescriptor(mUri, "r");
                if (mAssetFileDescriptor != null) {
                    FileInputStream mFileInputStream = mAssetFileDescriptor.createInputStream();
                    byte[] mBuffer = new byte[(int) mAssetFileDescriptor.getDeclaredLength()];
                    mFileInputStream.read(mBuffer);
                    String VCardString = new String(mBuffer);
                    FileOutputStream mFileOutputStream = new FileOutputStream(contactFile, true);
                    mFileOutputStream.write(VCardString.getBytes());
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } while (mCursor.moveToNext());
        mCursor.close();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文