获取通讯录

package com.landa.android;

import org.json.JSONArray;
import org.json.JSONObject;

import android.AndroidConstant;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;

//获取获取手机联系人类
public class ContactsScan extends Scan{


private ScanCallBack callBack;

public static final String type = AndroidConstant.SCANTYPE_CONTACTS;
private boolean running = false;

public ContactsScan(ScanCallBack callBack){
this.callBack = callBack;
}
public boolean isRunning(){
return running;
}
public void scan(Context ctx) {
running = true;
//ContactsContract.Contacts.CONTENT_URI content://com.android.contacts/data
Cursor cursor = ctx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); // 获取手机联系人

StringBuilder jsonString = new StringBuilder();
JSONArray jArray = new JSONArray();
try{
if(cursor == null || cursor.getCount() <= 0){
// if (this.callBack != null) {
// this.callBack.onScanStart(0);
// }
return;
}
// if (this.callBack != null) {
// this.callBack.onScanStart(cursor.getCount());
// }
jsonString.append("{");
jsonString.append(""" + "APPID" + "":");
jsonString.append(""" + "187xxxxxx" + "",");
jsonString.append(""" + "type" + "":");
jsonString.append(""" + type + "",");
jsonString.append(""" + "success" + "":");
jsonString.append(""" + "true" + "",");
jsonString.append(""" + "errorMessage" + "":");
jsonString.append(""" + "null" + "",");
jsonString.append(""" + "data" + "":");

while (cursor.moveToNext()) {
int indexPeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME); // people name
int indexPhoneNum = cursor.getColumnIndex(Phone.NUMBER); // phone number

String strPeopleName = cursor.getString(indexPeopleName);
String strPhoneNum = cursor.getString(indexPhoneNum);
JSONObject person = new JSONObject();
person.put("name", strPeopleName);
person.put("phone", strPhoneNum);
boolean last = cursor.isLast();
jArray.put(person);
if (this.callBack != null) {
//this.callBack.onScanInfoMsg(type, person.toString(), last);
}
}
if(!cursor.isClosed()){
cursor.close();
cursor = null;
}
}catch(Exception e){
e.printStackTrace();
}
finally{
running = false;
// if (this.callBack != null) {
// this.callBack.onScanFinish();
// }
if (this.callBack != null) {
// this.callBack.onScan(type, jArray.toString());
jsonString.append(jArray.toString());
jsonString.append("}");

this.callBack.onScanInfoMsg(AndroidConstant.SCANTYPE_CALLS, jsonString.toString() , false);
}
}

}

}

有兴趣请加android技术群:207833859

原文地址:https://www.cnblogs.com/xinanheishao/p/4720722.html