[存档]获取通讯录信息并写到SD卡上
下面是代码,不过没有字母表的顺序排列:
package com.example.getcontacts; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.text.TextUtils; import android.widget.Toast; public class GetContacts extends Activity { private Context ctx = GetContacts.this ; private String filePath = Environment.getExternalStorageDirectory().getPath()+"/contacts.txt"; private static final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID,Phone.CONTACT_ID }; /**联系人显示名称**/ private static final int PHONES_DISPLAY_NAME_INDEX = 0; /**电话号码**/ private static final int PHONES_NUMBER_INDEX = 1; /**联系人的ID**/ private static final int PHONES_CONTACT_ID_INDEX = 3; /**联系人名称**/ private ArrayList<String> mContactsName = new ArrayList<String>(); private ArrayList<String> mContactsNumber = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_contacts); getPhoneContacts(); try { FileWriter fw = new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/ContactME.txt"); for(int k = 1 ; k < mContactsName.size() ; k++ ) { String name = mContactsName.get(k) ; String num = mContactsNumber.get(k)+ "\r\n" ; fw.write( name + num ); } fw.flush(); Toast.makeText(ctx, "asdasd", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void getPhoneContacts() { // ContentResolver resolver = context.getContentResolver(); // 获取手机联系人 Cursor phoneCursor = getContentResolver().query(Phone.CONTENT_URI,PHONES_PROJECTION, null, null, null); if (phoneCursor != null) { while (phoneCursor.moveToNext()) { //得到手机号码 String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX); //当手机号码为空的或者为空字段 跳过当前循环 if (TextUtils.isEmpty(phoneNumber)) continue; //得到联系人名称 String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX); mContactsName.add(contactName); mContactsNumber.add(phoneNumber); } phoneCursor.close(); } } }
别忘了权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>