Thursday, February 24, 2011

Getting the Contact Info someone cal you

On android when someone call you or you receive a message, a non formatted number would be shown to you and for you to find out whom that number is, you have to use Contacts.Phones.CONTENT_FILTER_URL on your query. This article is based on Get Phone State When Someone is calling using BroadcastReceiver Example

public class MyPhoneStateListener extends PhoneStateListener {
  private String[] projection = new String[] {
    People._ID, People.NAME, People.NUMBER
  };
  public void onCallStateChanged(int state,String incomingNumber){
    switch(state)
    {
      case TelephonyManager.CALL_STATE_IDLE:
        Log.d("DEBUG", "IDLE");
      break;
      case TelephonyManager.CALL_STATE_OFFHOOK:
        if(!incomingNumber.equals("")){
          handleCall(incomingCall);
        }
      break;
      case TelephonyManager.CALL_STATE_RINGING:
        Log.d("DEBUG", "RINGING");
      break;
    }
  }
  public void handleCall(String incomingCall){
    Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL,
incomingNumber);
    contactsCursor = context.getContentResolver().query(contactUri,
projection, null , null, People.NAME + " ASC");
    if(contactsCursor.moveToFirst()){
      int phoneNameIndex = contactsCursor.getColumnIndex(People.NAME);
      String phoneNameStr = contactsCursor.getString(phoneNameIndex);
      Log.d("DEBUG",phoneNameStr + " is calling");
    }else{
      Log.d("DEBUG","Not a contact");
    }
  }
}

No comments:

Post a Comment