简体   繁体   中英

Call a contact in android

I have wrote an android app that uses voice recognition and save voice into a string.Now i can access to different part of this string and for example when i say call dad i need to retrieve dad's number from contacts.

   private void call() {
  Intent in=new Intent(Intent.ACTION_CALL,Uri.parse("0000000000"));
  try{
     startActivity(in);
  }

  catch (android.content.ActivityNotFoundException ex){
     Toast.makeText(getApplicationContext(),"yourActivity is not founded",Toast.LENGTH_SHORT).show();
  }

}

I know this function but instead of giving Uri.parse the actual number, i need to pass dad's number to it.For example something like Uri.parse(dad.PhoneNumber).How can i retrieve a phone number from contacts by using a name ? Thanks.

You need to obtain the number from a contact you know only the name, so:

    // Define the fields that the query will return
    String[] PROJECTION = new String[] {
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
    };

    ContentResolver cr = getContentResolver();

    // Execute the query and receive the cursor with the results
    Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, 
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " LIKE ?", 
                    new String[] { "Name of the Contact" },
                    null );

Change the "Name of the contact" with your contact name...

Now you can get the value from cursor

// First discover the index of the desired field (Number)
final int indexNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(indexNumber);

Then you can use your intent.

PS: The example uses a LIKE operator, because of this you can find more than one result in the cursor. Adapt to you necessity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM