CallerInfo.java revision a4d785688c2b5a63322cf0554c0e7f5ae046e544
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.internal.telephony; 18 19import android.content.Context; 20import android.database.Cursor; 21import android.graphics.drawable.Drawable; 22import android.net.Uri; 23import android.provider.ContactsContract.CommonDataKinds.Phone; 24import android.provider.ContactsContract.Data; 25import android.provider.ContactsContract.PhoneLookup; 26import android.provider.ContactsContract.RawContacts; 27import android.telephony.PhoneNumberUtils; 28import android.telephony.TelephonyManager; 29import android.text.TextUtils; 30import android.util.Log; 31 32 33/** 34 * Looks up caller information for the given phone number. 35 * 36 * {@hide} 37 */ 38public class CallerInfo { 39 private static final String TAG = "CallerInfo"; 40 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE); 41 42 public static final String UNKNOWN_NUMBER = "-1"; 43 public static final String PRIVATE_NUMBER = "-2"; 44 public static final String PAYPHONE_NUMBER = "-3"; 45 46 /** 47 * Please note that, any one of these member variables can be null, 48 * and any accesses to them should be prepared to handle such a case. 49 * 50 * Also, it is implied that phoneNumber is more often populated than 51 * name is, (think of calls being dialed/received using numbers where 52 * names are not known to the device), so phoneNumber should serve as 53 * a dependable fallback when name is unavailable. 54 * 55 * One other detail here is that this CallerInfo object reflects 56 * information found on a connection, it is an OUTPUT that serves 57 * mainly to display information to the user. In no way is this object 58 * used as input to make a connection, so we can choose to display 59 * whatever human-readable text makes sense to the user for a 60 * connection. This is especially relevant for the phone number field, 61 * since it is the one field that is most likely exposed to the user. 62 * 63 * As an example: 64 * 1. User dials "911" 65 * 2. Device recognizes that this is an emergency number 66 * 3. We use the "Emergency Number" string instead of "911" in the 67 * phoneNumber field. 68 * 69 * What we're really doing here is treating phoneNumber as an essential 70 * field here, NOT name. We're NOT always guaranteed to have a name 71 * for a connection, but the number should be displayable. 72 */ 73 public String name; 74 public String phoneNumber; 75 public String nomalizedNumber; 76 77 public String cnapName; 78 public int numberPresentation; 79 public int namePresentation; 80 public boolean contactExists; 81 82 public String phoneLabel; 83 /* Split up the phoneLabel into number type and label name */ 84 public int numberType; 85 public String numberLabel; 86 87 public int photoResource; 88 public long person_id; 89 public boolean needUpdate; 90 public Uri contactRefUri; 91 92 // fields to hold individual contact preference data, 93 // including the send to voicemail flag and the ringtone 94 // uri reference. 95 public Uri contactRingtoneUri; 96 public boolean shouldSendToVoicemail; 97 98 /** 99 * Drawable representing the caller image. This is essentially 100 * a cache for the image data tied into the connection / 101 * callerinfo object. The isCachedPhotoCurrent flag indicates 102 * if the image data needs to be reloaded. 103 */ 104 public Drawable cachedPhoto; 105 public boolean isCachedPhotoCurrent; 106 107 private boolean mIsEmergency; 108 private boolean mIsVoiceMail; 109 110 public CallerInfo() { 111 // TODO: Move all the basic initialization here? 112 mIsEmergency = false; 113 mIsVoiceMail = false; 114 } 115 116 /** 117 * getCallerInfo given a Cursor. 118 * @param context the context used to retrieve string constants 119 * @param contactRef the URI to attach to this CallerInfo object 120 * @param cursor the first object in the cursor is used to build the CallerInfo object. 121 * @return the CallerInfo which contains the caller id for the given 122 * number. The returned CallerInfo is null if no number is supplied. 123 */ 124 public static CallerInfo getCallerInfo(Context context, Uri contactRef, Cursor cursor) { 125 CallerInfo info = new CallerInfo(); 126 info.photoResource = 0; 127 info.phoneLabel = null; 128 info.numberType = 0; 129 info.numberLabel = null; 130 info.cachedPhoto = null; 131 info.isCachedPhotoCurrent = false; 132 info.contactExists = false; 133 134 if (VDBG) Log.v(TAG, "construct callerInfo from cursor"); 135 136 if (cursor != null) { 137 if (cursor.moveToFirst()) { 138 // TODO: photo_id is always available but not taken 139 // care of here. Maybe we should store it in the 140 // CallerInfo object as well. 141 142 int columnIndex; 143 144 // Look for the name 145 columnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME); 146 if (columnIndex != -1) { 147 info.name = cursor.getString(columnIndex); 148 } 149 150 // Look for the number 151 columnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER); 152 if (columnIndex != -1) { 153 info.phoneNumber = cursor.getString(columnIndex); 154 } 155 156 // Look for the normalized number 157 columnIndex = cursor.getColumnIndex(PhoneLookup.NORMALIZED_NUMBER); 158 if (columnIndex != -1) { 159 info.nomalizedNumber = cursor.getString(columnIndex); 160 } 161 162 // Look for the label/type combo 163 columnIndex = cursor.getColumnIndex(PhoneLookup.LABEL); 164 if (columnIndex != -1) { 165 int typeColumnIndex = cursor.getColumnIndex(PhoneLookup.TYPE); 166 if (typeColumnIndex != -1) { 167 info.numberType = cursor.getInt(typeColumnIndex); 168 info.numberLabel = cursor.getString(columnIndex); 169 info.phoneLabel = Phone.getDisplayLabel(context, 170 info.numberType, info.numberLabel) 171 .toString(); 172 } 173 } 174 175 // Look for the person_id. 176 columnIndex = getColumnIndexForPersonId(contactRef, cursor); 177 if (columnIndex != -1) { 178 info.person_id = cursor.getLong(columnIndex); 179 if (VDBG) Log.v(TAG, "==> got info.person_id: " + info.person_id); 180 } else { 181 // No valid columnIndex, so we can't look up person_id. 182 Log.w(TAG, "Couldn't find person_id column for " + contactRef); 183 // Watch out: this means that anything that depends on 184 // person_id will be broken (like contact photo lookups in 185 // the in-call UI, for example.) 186 } 187 188 // look for the custom ringtone, create from the string stored 189 // in the database. 190 columnIndex = cursor.getColumnIndex(PhoneLookup.CUSTOM_RINGTONE); 191 if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) { 192 info.contactRingtoneUri = Uri.parse(cursor.getString(columnIndex)); 193 } else { 194 info.contactRingtoneUri = null; 195 } 196 197 // look for the send to voicemail flag, set it to true only 198 // under certain circumstances. 199 columnIndex = cursor.getColumnIndex(PhoneLookup.SEND_TO_VOICEMAIL); 200 info.shouldSendToVoicemail = (columnIndex != -1) && 201 ((cursor.getInt(columnIndex)) == 1); 202 info.contactExists = true; 203 } 204 cursor.close(); 205 } 206 207 info.needUpdate = false; 208 info.name = normalize(info.name); 209 info.contactRefUri = contactRef; 210 211 return info; 212 } 213 214 /** 215 * getCallerInfo given a URI, look up in the call-log database 216 * for the uri unique key. 217 * @param context the context used to get the ContentResolver 218 * @param contactRef the URI used to lookup caller id 219 * @return the CallerInfo which contains the caller id for the given 220 * number. The returned CallerInfo is null if no number is supplied. 221 */ 222 public static CallerInfo getCallerInfo(Context context, Uri contactRef) { 223 224 return getCallerInfo(context, contactRef, 225 context.getContentResolver().query(contactRef, null, null, null, null)); 226 } 227 228 /** 229 * getCallerInfo given a phone number, look up in the call-log database 230 * for the matching caller id info. 231 * @param context the context used to get the ContentResolver 232 * @param number the phone number used to lookup caller id 233 * @return the CallerInfo which contains the caller id for the given 234 * number. The returned CallerInfo is null if no number is supplied. If 235 * a matching number is not found, then a generic caller info is returned, 236 * with all relevant fields empty or null. 237 */ 238 public static CallerInfo getCallerInfo(Context context, String number) { 239 if (TextUtils.isEmpty(number)) { 240 return null; 241 } 242 243 // Change the callerInfo number ONLY if it is an emergency number 244 // or if it is the voicemail number. If it is either, take a 245 // shortcut and skip the query. 246 if (PhoneNumberUtils.isEmergencyNumber(number)) { 247 return new CallerInfo().markAsEmergency(context); 248 } else if (PhoneNumberUtils.isVoiceMailNumber(number)) { 249 return new CallerInfo().markAsVoiceMail(); 250 } 251 252 Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); 253 254 CallerInfo info = getCallerInfo(context, contactUri); 255 info = doSecondaryLookupIfNecessary(context, number, info); 256 257 // if no query results were returned with a viable number, 258 // fill in the original number value we used to query with. 259 if (TextUtils.isEmpty(info.phoneNumber)) { 260 info.phoneNumber = number; 261 } 262 263 return info; 264 } 265 266 /** 267 * Performs another lookup if previous lookup fails and it's a SIP call 268 * and the peer's username is all numeric. Look up the username as it 269 * could be a PSTN number in the contact database. 270 * 271 * @param context the query context 272 * @param number the original phone number, could be a SIP URI 273 * @param previousResult the result of previous lookup 274 * @return previousResult if it's not the case 275 */ 276 static CallerInfo doSecondaryLookupIfNecessary(Context context, 277 String number, CallerInfo previousResult) { 278 if (!previousResult.contactExists 279 && PhoneNumberUtils.isUriNumber(number)) { 280 String username = number.substring(0, number.indexOf('@')); 281 if (PhoneNumberUtils.isGlobalPhoneNumber(username)) { 282 previousResult = getCallerInfo(context, 283 Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, 284 Uri.encode(username))); 285 } 286 } 287 return previousResult; 288 } 289 290 /** 291 * getCallerId: a convenience method to get the caller id for a given 292 * number. 293 * 294 * @param context the context used to get the ContentResolver. 295 * @param number a phone number. 296 * @return if the number belongs to a contact, the contact's name is 297 * returned; otherwise, the number itself is returned. 298 * 299 * TODO NOTE: This MAY need to refer to the Asynchronous Query API 300 * [startQuery()], instead of getCallerInfo, but since it looks like 301 * it is only being used by the provider calls in the messaging app: 302 * 1. android.provider.Telephony.Mms.getDisplayAddress() 303 * 2. android.provider.Telephony.Sms.getDisplayAddress() 304 * We may not need to make the change. 305 */ 306 public static String getCallerId(Context context, String number) { 307 CallerInfo info = getCallerInfo(context, number); 308 String callerID = null; 309 310 if (info != null) { 311 String name = info.name; 312 313 if (!TextUtils.isEmpty(name)) { 314 callerID = name; 315 } else { 316 callerID = number; 317 } 318 } 319 320 return callerID; 321 } 322 323 // Accessors 324 325 /** 326 * @return true if the caller info is an emergency number. 327 */ 328 public boolean isEmergencyNumber() { 329 return mIsEmergency; 330 } 331 332 /** 333 * @return true if the caller info is a voicemail number. 334 */ 335 public boolean isVoiceMailNumber() { 336 return mIsVoiceMail; 337 } 338 339 /** 340 * Mark this CallerInfo as an emergency call. 341 * @param context To lookup the localized 'Emergency Number' string. 342 * @return this instance. 343 */ 344 // TODO: Note we're setting the phone number here (refer to 345 // javadoc comments at the top of CallerInfo class) to a localized 346 // string 'Emergency Number'. This is pretty bad because we are 347 // making UI work here instead of just packaging the data. We 348 // should set the phone number to the dialed number and name to 349 // 'Emergency Number' and let the UI make the decision about what 350 // should be displayed. 351 /* package */ CallerInfo markAsEmergency(Context context) { 352 phoneNumber = context.getString( 353 com.android.internal.R.string.emergency_call_dialog_number_for_display); 354 photoResource = com.android.internal.R.drawable.picture_emergency; 355 mIsEmergency = true; 356 return this; 357 } 358 359 360 /** 361 * Mark this CallerInfo as a voicemail call. The voicemail label 362 * is obtained from the telephony manager. Caller must hold the 363 * READ_PHONE_STATE permission otherwise the phoneNumber will be 364 * set to null. 365 * @return this instance. 366 */ 367 // TODO: As in the emergency number handling, we end up writing a 368 // string in the phone number field. 369 /* package */ CallerInfo markAsVoiceMail() { 370 mIsVoiceMail = true; 371 372 try { 373 String voiceMailLabel = TelephonyManager.getDefault().getVoiceMailAlphaTag(); 374 375 phoneNumber = voiceMailLabel; 376 } catch (SecurityException se) { 377 // Should never happen: if this process does not have 378 // permission to retrieve VM tag, it should not have 379 // permission to retrieve VM number and would not call 380 // this method. 381 // Leave phoneNumber untouched. 382 Log.e(TAG, "Cannot access VoiceMail.", se); 383 } 384 // TODO: There is no voicemail picture? 385 // FIXME: FIND ANOTHER ICON 386 // photoResource = android.R.drawable.badge_voicemail; 387 return this; 388 } 389 390 private static String normalize(String s) { 391 if (s == null || s.length() > 0) { 392 return s; 393 } else { 394 return null; 395 } 396 } 397 398 /** 399 * Returns the column index to use to find the "person_id" field in 400 * the specified cursor, based on the contact URI that was originally 401 * queried. 402 * 403 * This is a helper function for the getCallerInfo() method that takes 404 * a Cursor. Looking up the person_id is nontrivial (compared to all 405 * the other CallerInfo fields) since the column we need to use 406 * depends on what query we originally ran. 407 * 408 * Watch out: be sure to not do any database access in this method, since 409 * it's run from the UI thread (see comments below for more info.) 410 * 411 * @return the columnIndex to use (with cursor.getLong()) to get the 412 * person_id, or -1 if we couldn't figure out what colum to use. 413 * 414 * TODO: Add a unittest for this method. (This is a little tricky to 415 * test, since we'll need a live contacts database to test against, 416 * preloaded with at least some phone numbers and SIP addresses. And 417 * we'll probably have to hardcode the column indexes we expect, so 418 * the test might break whenever the contacts schema changes. But we 419 * can at least make sure we handle all the URI patterns we claim to, 420 * and that the mime types match what we expect...) 421 */ 422 private static int getColumnIndexForPersonId(Uri contactRef, Cursor cursor) { 423 // TODO: This is pretty ugly now, see bug 2269240 for 424 // more details. The column to use depends upon the type of URL: 425 // - content://com.android.contacts/data/phones ==> use the "contact_id" column 426 // - content://com.android.contacts/phone_lookup ==> use the "_ID" column 427 // - content://com.android.contacts/data ==> use the "contact_id" column 428 // If it's none of the above, we leave columnIndex=-1 which means 429 // that the person_id field will be left unset. 430 // 431 // The logic here *used* to be based on the mime type of contactRef 432 // (for example Phone.CONTENT_ITEM_TYPE would tell us to use the 433 // RawContacts.CONTACT_ID column). But looking up the mime type requires 434 // a call to context.getContentResolver().getType(contactRef), which 435 // isn't safe to do from the UI thread since it can cause an ANR if 436 // the contacts provider is slow or blocked (like during a sync.) 437 // 438 // So instead, figure out the column to use for person_id by just 439 // looking at the URI itself. 440 441 if (VDBG) Log.v(TAG, "- getColumnIndexForPersonId: contactRef URI = '" 442 + contactRef + "'..."); 443 // Warning: Do not enable the following logging (due to ANR risk.) 444 // if (VDBG) Log.v(TAG, "- MIME type: " 445 // + context.getContentResolver().getType(contactRef)); 446 447 String url = contactRef.toString(); 448 String columnName = null; 449 if (url.startsWith("content://com.android.contacts/data/phones")) { 450 // Direct lookup in the Phone table. 451 // MIME type: Phone.CONTENT_ITEM_TYPE (= "vnd.android.cursor.item/phone_v2") 452 if (VDBG) Log.v(TAG, "'data/phones' URI; using RawContacts.CONTACT_ID"); 453 columnName = RawContacts.CONTACT_ID; 454 } else if (url.startsWith("content://com.android.contacts/data")) { 455 // Direct lookup in the Data table. 456 // MIME type: Data.CONTENT_TYPE (= "vnd.android.cursor.dir/data") 457 if (VDBG) Log.v(TAG, "'data' URI; using Data.CONTACT_ID"); 458 // (Note Data.CONTACT_ID and RawContacts.CONTACT_ID are equivalent.) 459 columnName = Data.CONTACT_ID; 460 } else if (url.startsWith("content://com.android.contacts/phone_lookup")) { 461 // Lookup in the PhoneLookup table, which provides "fuzzy matching" 462 // for phone numbers. 463 // MIME type: PhoneLookup.CONTENT_TYPE (= "vnd.android.cursor.dir/phone_lookup") 464 if (VDBG) Log.v(TAG, "'phone_lookup' URI; using PhoneLookup._ID"); 465 columnName = PhoneLookup._ID; 466 } else { 467 Log.w(TAG, "Unexpected prefix for contactRef '" + url + "'"); 468 } 469 int columnIndex = (columnName != null) ? cursor.getColumnIndex(columnName) : -1; 470 if (VDBG) Log.v(TAG, "==> Using column '" + columnName 471 + "' (columnIndex = " + columnIndex + ") for person_id lookup..."); 472 return columnIndex; 473 } 474 475 /** 476 * @return a string debug representation of this instance. 477 */ 478 public String toString() { 479 return new StringBuilder(384) 480 .append("\nname: " + /*name*/ "nnnnnn") 481 .append("\nphoneNumber: " + /*phoneNumber*/ "xxxxxxx") 482 .append("\ncnapName: " + cnapName) 483 .append("\nnumberPresentation: " + numberPresentation) 484 .append("\nnamePresentation: " + namePresentation) 485 .append("\ncontactExits: " + contactExists) 486 .append("\nphoneLabel: " + phoneLabel) 487 .append("\nnumberType: " + numberType) 488 .append("\nnumberLabel: " + numberLabel) 489 .append("\nphotoResource: " + photoResource) 490 .append("\nperson_id: " + person_id) 491 .append("\nneedUpdate: " + needUpdate) 492 .append("\ncontactRefUri: " + /*contactRefUri*/ "xxxxxxx") 493 .append("\ncontactRingtoneUri: " + /*contactRefUri*/ "xxxxxxx") 494 .append("\nshouldSendToVoicemail: " + shouldSendToVoicemail) 495 .append("\ncachedPhoto: " + cachedPhoto) 496 .append("\nisCachedPhotoCurrent: " + isCachedPhotoCurrent) 497 .append("\nemergency: " + mIsEmergency) 498 .append("\nvoicemail " + mIsVoiceMail) 499 .append("\ncontactExists " + contactExists) 500 .toString(); 501 } 502} 503