Thursday, January 15, 2009

Calling a Contact in Android

There will be a time where you might want to use the Caller on Android. Here is how you would do it, this article also introduces how to get an individual contact from your contact list. This is based on our previous article Clicking Items in ListActivity and Display Contact Names in Android.

protected void onListItemClick(ListView l, View v, int position, long id) {
  // GET THE ITEM THAT HAD BEEN TAPPED
  Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, id);
  Cursor c = managedQuery(uri, new String[] {
    People.NUMBER
  }, null, null, null);
  c.moveToFirst();

  // CALL THE NUMBER FROM THE PREVIOUS SCREEN\
  int phoneNumberIndex = c.getColumnIndex(People.NUMBER);
  Uri parsedPhoneNumber = Uri.parse("tel:"+c.getString(phoneNumberIndex)); 
  Intent i = new Intent(Intent.ACTION_CALL,parsedPhoneNumber);
  startActivity(i);

  super.onListItemClick(l, v, position, id);
}


Quick Explanation
// GET THE ITEM THAT HAD BEEN TAPPED
Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, id);
Cursor c = managedQuery(uri, new String[] {
People.NUMBER
}, null, null, null);
c.moveToFirst();
- Here we query our contacts with People.CONTENT_URI but on one specific contact. Then after we got the results we move the cursor to the first record.

- int phoneNumberIndex = c.getColumnIndex(People.NUMBER);
Uri parsedPhoneNumber = Uri.parse("tel:"+c.getString(phoneNumberIndex));

The first on is used to get the index of NUMBER in our fields, we do this coz c.getString arguement is the column id. Then to create a number that our caller accepts we need to pass it a Uri that starts with "tel:"

Intent i = new Intent(Intent.ACTION_CALL,parsedPhoneNumber);
startActivity(i);

Here we create a new Intent that would use the default caller and we pass the Uri of our phone number, then we start the calling with startActivity(i).


Update History
   Jan 17, 2012 - Visual Update
Post a Comment