How to send sms using contacts in phonebook instea

2019-07-22 08:05发布

问题:

I'm sending sms to a person by writing his phone number but now I want to add functionality of getting number automatically from phone book contacts by selecting sender's contact.Can anyone give me some idea how to add that functionality in my application ? Thanks in avance.

回答1:

This can be done as follows:

  1. Load contacts from your phonebook (on a button click or on clicking on the EditText you use to collect phone number)

// Pick contacts when clicked

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);
    switch (reqCode) {
        case (1) :
            getContactInfo(data);
            edittext.setText(contactName); // Set text on your EditText
            break;
    }
}
  1. Method that actually gets all the contacts

This will load all the contacts when the user clicks the EditText.

public void getContactInfo(Intent intent) {
    String phoneNumber = null;
    String name = null;

    Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
    while (cursor.moveToNext()) {
        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
        name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

        String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

        if (hasPhone.equalsIgnoreCase("1"))
            hasPhone = "true";
        else
            hasPhone = "false";

        if (Boolean.parseBoolean(hasPhone)) {
            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
            while (phones.moveToNext()) {
                phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            }// end while
            phones.close();
        }// end if
    }// end while
    return arr;
}// end class


回答2:

I think you first need to access the contacts stored on the phone via the Contacts API. Then retrieve a phone number from a contact raw and use it to send your sms.