如果我理解你的問題,你需要開始一個活動的結果。你通過點擊一個按鈕然後onActivityResult開始你的活動(聯繫人應用程序) - >你得到你想要的數據。
例如:
private static final int REQUEST_CONTACT = 1;
private static final int RESULT_OK = -1;
private static final int RESULT_CANCELED = 0;
private Uri mInfo;
private Context mContext;
Button startContactsApp = (Button)findViewByid(...);
startContactsApp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() { // you need a thread because this operation takes plenty of time
@Override
public void run() {
Intent contactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
contactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // to display contacts who have phone number
startActivityForResult(contactIntent, REQUEST_CONTACT);
}
}).start();
}
});
結果:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CONTACT){
if(resultCode == RESULT_OK && data != null){
mInfo = data.getData();
String name = getContactNameAgenda(); // the name you need
String phone = getContactPhoneNumberAgenda(); //the number you need
Toast.makeText(mContext,"CONTACT ADDED !",Toast.LENGTH_SHORT).show();
}
else if (resultCode == RESULT_CANCELED){
Toast.makeText(getActivity(),"CANCELLED OR SOME ERROR OCCURRED !",Toast.LENGTH_SHORT).show();
}
}
在這裏,你會得到的名稱,並從所選擇的聯繫人的電話號碼:
private String getContactNameAgenda(){
Cursor cursor = mContext.getContentResolver().query(mInfo, null,
null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
cursor.close();
return name;
}
private String getContactPhoneNumberAgenda(){
Cursor cursor = mContext.getContentResolver().query(mInfo, new String[]{ContactsContract.Contacts._ID},
null, null, null);
cursor.moveToFirst();
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
cursor.close();
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone._ID + " = ? AND " + // Phone._ID is for the database ; Phone.CONTACT_ID is for contact when you are not querying that table
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{id},
null);
cursorPhone.moveToFirst();
String number = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
cursorPhone.close();
return number;
}
我希望這會幫助你。