CallLog.java revision b524741cb653d6a898431d2c3c7d54a543b5e577
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 17 18package android.provider; 19 20import android.content.ContentProvider; 21import android.content.ContentResolver; 22import android.content.ContentValues; 23import android.content.Context; 24import android.content.Intent; 25import android.content.pm.UserInfo; 26import android.database.Cursor; 27import android.location.Country; 28import android.location.CountryDetector; 29import android.net.Uri; 30import android.os.UserHandle; 31import android.os.UserManager; 32import android.provider.ContactsContract.CommonDataKinds.Callable; 33import android.provider.ContactsContract.CommonDataKinds.Phone; 34import android.provider.ContactsContract.Data; 35import android.provider.ContactsContract.DataUsageFeedback; 36import android.telecom.PhoneAccount; 37import android.telecom.PhoneAccountHandle; 38import android.telecom.TelecomManager; 39import android.telephony.PhoneNumberUtils; 40import android.text.TextUtils; 41import android.util.Log; 42 43import com.android.internal.telephony.CallerInfo; 44import com.android.internal.telephony.PhoneConstants; 45 46import java.util.List; 47 48/** 49 * The CallLog provider contains information about placed and received calls. 50 */ 51public class CallLog { 52 private static final String LOG_TAG = "CallLog"; 53 private static final boolean VERBOSE_LOG = false; // DON'T SUBMIT WITH TRUE. 54 55 public static final String AUTHORITY = "call_log"; 56 57 /** 58 * The content:// style URL for this provider 59 */ 60 public static final Uri CONTENT_URI = 61 Uri.parse("content://" + AUTHORITY); 62 63 64 /** 65 * The "shadow" provider stores calllog when the real calllog provider is encrypted. The 66 * real provider will alter copy from it when it starts, and remove the entries in the shadow. 67 * 68 * <p>See the comment in {@link Calls#addCall} for the details. 69 * 70 * @hide 71 */ 72 public static final String SHADOW_AUTHORITY = "call_log_shadow"; 73 74 /** 75 * Contains the recent calls. 76 */ 77 public static class Calls implements BaseColumns { 78 /** 79 * The content:// style URL for this table 80 */ 81 public static final Uri CONTENT_URI = 82 Uri.parse("content://call_log/calls"); 83 84 /** @hide */ 85 public static final Uri SHADOW_CONTENT_URI = 86 Uri.parse("content://call_log_shadow/calls"); 87 88 /** 89 * The content:// style URL for filtering this table on phone numbers 90 */ 91 public static final Uri CONTENT_FILTER_URI = 92 Uri.parse("content://call_log/calls/filter"); 93 94 /** 95 * Query parameter used to limit the number of call logs returned. 96 * <p> 97 * TYPE: integer 98 */ 99 public static final String LIMIT_PARAM_KEY = "limit"; 100 101 /** 102 * Query parameter used to specify the starting record to return. 103 * <p> 104 * TYPE: integer 105 */ 106 public static final String OFFSET_PARAM_KEY = "offset"; 107 108 /** 109 * An optional URI parameter which instructs the provider to allow the operation to be 110 * applied to voicemail records as well. 111 * <p> 112 * TYPE: Boolean 113 * <p> 114 * Using this parameter with a value of {@code true} will result in a security error if the 115 * calling package does not have appropriate permissions to access voicemails. 116 * 117 * @hide 118 */ 119 public static final String ALLOW_VOICEMAILS_PARAM_KEY = "allow_voicemails"; 120 121 /** 122 * An optional extra used with {@link #CONTENT_TYPE Calls.CONTENT_TYPE} and 123 * {@link Intent#ACTION_VIEW} to specify that the presented list of calls should be 124 * filtered for a particular call type. 125 * 126 * Applications implementing a call log UI should check for this extra, and display a 127 * filtered list of calls based on the specified call type. If not applicable within the 128 * application's UI, it should be silently ignored. 129 * 130 * <p> 131 * The following example brings up the call log, showing only missed calls. 132 * <pre> 133 * Intent intent = new Intent(Intent.ACTION_VIEW); 134 * intent.setType(CallLog.Calls.CONTENT_TYPE); 135 * intent.putExtra(CallLog.Calls.EXTRA_CALL_TYPE_FILTER, CallLog.Calls.MISSED_TYPE); 136 * startActivity(intent); 137 * </pre> 138 * </p> 139 */ 140 public static final String EXTRA_CALL_TYPE_FILTER = 141 "android.provider.extra.CALL_TYPE_FILTER"; 142 143 /** 144 * Content uri used to access call log entries, including voicemail records. You must have 145 * the READ_CALL_LOG and WRITE_CALL_LOG permissions to read and write to the call log, as 146 * well as READ_VOICEMAIL and WRITE_VOICEMAIL permissions to read and write voicemails. 147 */ 148 public static final Uri CONTENT_URI_WITH_VOICEMAIL = CONTENT_URI.buildUpon() 149 .appendQueryParameter(ALLOW_VOICEMAILS_PARAM_KEY, "true") 150 .build(); 151 152 /** 153 * The default sort order for this table 154 */ 155 public static final String DEFAULT_SORT_ORDER = "date DESC"; 156 157 /** 158 * The MIME type of {@link #CONTENT_URI} and {@link #CONTENT_FILTER_URI} 159 * providing a directory of calls. 160 */ 161 public static final String CONTENT_TYPE = "vnd.android.cursor.dir/calls"; 162 163 /** 164 * The MIME type of a {@link #CONTENT_URI} sub-directory of a single 165 * call. 166 */ 167 public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/calls"; 168 169 /** 170 * The type of the call (incoming, outgoing or missed). 171 * <P>Type: INTEGER (int)</P> 172 * 173 * <p> 174 * Allowed values: 175 * <ul> 176 * <li>{@link #INCOMING_TYPE}</li> 177 * <li>{@link #OUTGOING_TYPE}</li> 178 * <li>{@link #MISSED_TYPE}</li> 179 * <li>{@link #VOICEMAIL_TYPE}</li> 180 * <li>{@link #REJECTED_TYPE}</li> 181 * <li>{@link #BLOCKED_TYPE}</li> 182 * </ul> 183 * </p> 184 */ 185 public static final String TYPE = "type"; 186 187 /** Call log type for incoming calls. */ 188 public static final int INCOMING_TYPE = 1; 189 /** Call log type for outgoing calls. */ 190 public static final int OUTGOING_TYPE = 2; 191 /** Call log type for missed calls. */ 192 public static final int MISSED_TYPE = 3; 193 /** Call log type for voicemails. */ 194 public static final int VOICEMAIL_TYPE = 4; 195 /** Call log type for calls rejected by direct user action. */ 196 public static final int REJECTED_TYPE = 5; 197 /** Call log type for calls blocked automatically. */ 198 public static final int BLOCKED_TYPE = 6; 199 200 /** 201 * Bit-mask describing features of the call (e.g. video). 202 * 203 * <P>Type: INTEGER (int)</P> 204 */ 205 public static final String FEATURES = "features"; 206 207 /** Call had video. */ 208 public static final int FEATURES_VIDEO = 0x1; 209 210 /** 211 * The phone number as the user entered it. 212 * <P>Type: TEXT</P> 213 */ 214 public static final String NUMBER = "number"; 215 216 /** 217 * The number presenting rules set by the network. 218 * 219 * <p> 220 * Allowed values: 221 * <ul> 222 * <li>{@link #PRESENTATION_ALLOWED}</li> 223 * <li>{@link #PRESENTATION_RESTRICTED}</li> 224 * <li>{@link #PRESENTATION_UNKNOWN}</li> 225 * <li>{@link #PRESENTATION_PAYPHONE}</li> 226 * </ul> 227 * </p> 228 * 229 * <P>Type: INTEGER</P> 230 */ 231 public static final String NUMBER_PRESENTATION = "presentation"; 232 233 /** Number is allowed to display for caller id. */ 234 public static final int PRESENTATION_ALLOWED = 1; 235 /** Number is blocked by user. */ 236 public static final int PRESENTATION_RESTRICTED = 2; 237 /** Number is not specified or unknown by network. */ 238 public static final int PRESENTATION_UNKNOWN = 3; 239 /** Number is a pay phone. */ 240 public static final int PRESENTATION_PAYPHONE = 4; 241 242 /** 243 * The ISO 3166-1 two letters country code of the country where the 244 * user received or made the call. 245 * <P> 246 * Type: TEXT 247 * </P> 248 */ 249 public static final String COUNTRY_ISO = "countryiso"; 250 251 /** 252 * The date the call occured, in milliseconds since the epoch 253 * <P>Type: INTEGER (long)</P> 254 */ 255 public static final String DATE = "date"; 256 257 /** 258 * The duration of the call in seconds 259 * <P>Type: INTEGER (long)</P> 260 */ 261 public static final String DURATION = "duration"; 262 263 /** 264 * The data usage of the call in bytes. 265 * <P>Type: INTEGER (long)</P> 266 */ 267 public static final String DATA_USAGE = "data_usage"; 268 269 /** 270 * Whether or not the call has been acknowledged 271 * <P>Type: INTEGER (boolean)</P> 272 */ 273 public static final String NEW = "new"; 274 275 /** 276 * The cached name associated with the phone number, if it exists. 277 * This value is not guaranteed to be current, if the contact information 278 * associated with this number has changed. 279 * <P>Type: TEXT</P> 280 */ 281 public static final String CACHED_NAME = "name"; 282 283 /** 284 * The cached number type (Home, Work, etc) associated with the 285 * phone number, if it exists. 286 * This value is not guaranteed to be current, if the contact information 287 * associated with this number has changed. 288 * <P>Type: INTEGER</P> 289 */ 290 public static final String CACHED_NUMBER_TYPE = "numbertype"; 291 292 /** 293 * The cached number label, for a custom number type, associated with the 294 * phone number, if it exists. 295 * This value is not guaranteed to be current, if the contact information 296 * associated with this number has changed. 297 * <P>Type: TEXT</P> 298 */ 299 public static final String CACHED_NUMBER_LABEL = "numberlabel"; 300 301 /** 302 * URI of the voicemail entry. Populated only for {@link #VOICEMAIL_TYPE}. 303 * <P>Type: TEXT</P> 304 */ 305 public static final String VOICEMAIL_URI = "voicemail_uri"; 306 307 /** 308 * Transcription of the call or voicemail entry. This will only be populated for call log 309 * entries of type {@link #VOICEMAIL_TYPE} that have valid transcriptions. 310 */ 311 public static final String TRANSCRIPTION = "transcription"; 312 313 /** 314 * Whether this item has been read or otherwise consumed by the user. 315 * <p> 316 * Unlike the {@link #NEW} field, which requires the user to have acknowledged the 317 * existence of the entry, this implies the user has interacted with the entry. 318 * <P>Type: INTEGER (boolean)</P> 319 */ 320 public static final String IS_READ = "is_read"; 321 322 /** 323 * A geocoded location for the number associated with this call. 324 * <p> 325 * The string represents a city, state, or country associated with the number. 326 * <P>Type: TEXT</P> 327 */ 328 public static final String GEOCODED_LOCATION = "geocoded_location"; 329 330 /** 331 * The cached URI to look up the contact associated with the phone number, if it exists. 332 * This value may not be current if the contact information associated with this number 333 * has changed. 334 * <P>Type: TEXT</P> 335 */ 336 public static final String CACHED_LOOKUP_URI = "lookup_uri"; 337 338 /** 339 * The cached phone number of the contact which matches this entry, if it exists. 340 * This value may not be current if the contact information associated with this number 341 * has changed. 342 * <P>Type: TEXT</P> 343 */ 344 public static final String CACHED_MATCHED_NUMBER = "matched_number"; 345 346 /** 347 * The cached normalized(E164) version of the phone number, if it exists. 348 * This value may not be current if the contact information associated with this number 349 * has changed. 350 * <P>Type: TEXT</P> 351 */ 352 public static final String CACHED_NORMALIZED_NUMBER = "normalized_number"; 353 354 /** 355 * The cached photo id of the picture associated with the phone number, if it exists. 356 * This value may not be current if the contact information associated with this number 357 * has changed. 358 * <P>Type: INTEGER (long)</P> 359 */ 360 public static final String CACHED_PHOTO_ID = "photo_id"; 361 362 /** 363 * The cached photo URI of the picture associated with the phone number, if it exists. 364 * This value may not be current if the contact information associated with this number 365 * has changed. 366 * <P>Type: TEXT (URI)</P> 367 */ 368 public static final String CACHED_PHOTO_URI = "photo_uri"; 369 370 /** 371 * The cached phone number, formatted with formatting rules based on the country the 372 * user was in when the call was made or received. 373 * This value is not guaranteed to be present, and may not be current if the contact 374 * information associated with this number 375 * has changed. 376 * <P>Type: TEXT</P> 377 */ 378 public static final String CACHED_FORMATTED_NUMBER = "formatted_number"; 379 380 // Note: PHONE_ACCOUNT_* constant values are "subscription_*" due to a historic naming 381 // that was encoded into call log databases. 382 383 /** 384 * The component name of the account used to place or receive the call; in string form. 385 * <P>Type: TEXT</P> 386 */ 387 public static final String PHONE_ACCOUNT_COMPONENT_NAME = "subscription_component_name"; 388 389 /** 390 * The identifier for the account used to place or receive the call. 391 * <P>Type: TEXT</P> 392 */ 393 public static final String PHONE_ACCOUNT_ID = "subscription_id"; 394 395 /** 396 * The address associated with the account used to place or receive the call; in string 397 * form. For SIM-based calls, this is the user's own phone number. 398 * <P>Type: TEXT</P> 399 * 400 * @hide 401 */ 402 public static final String PHONE_ACCOUNT_ADDRESS = "phone_account_address"; 403 404 /** 405 * Indicates that the entry will be hidden from all queries until the associated 406 * {@link android.telecom.PhoneAccount} is registered with the system. 407 * <P>Type: INTEGER</P> 408 * 409 * @hide 410 */ 411 public static final String PHONE_ACCOUNT_HIDDEN = "phone_account_hidden"; 412 413 /** 414 * The subscription ID used to place this call. This is no longer used and has been 415 * replaced with PHONE_ACCOUNT_COMPONENT_NAME/PHONE_ACCOUNT_ID. 416 * For ContactsProvider internal use only. 417 * <P>Type: INTEGER</P> 418 * 419 * @Deprecated 420 * @hide 421 */ 422 public static final String SUB_ID = "sub_id"; 423 424 /** 425 * The post-dial portion of a dialed number, including any digits dialed after a 426 * {@link TelecomManager#DTMF_CHARACTER_PAUSE} or a {@link 427 * TelecomManager#DTMF_CHARACTER_WAIT} and these characters themselves. 428 * <P>Type: TEXT</P> 429 */ 430 public static final String POST_DIAL_DIGITS = "post_dial_digits"; 431 432 /** 433 * Indicates that the entry will be copied from primary user to other users. 434 * <P>Type: INTEGER</P> 435 * 436 * @hide 437 */ 438 public static final String ADD_FOR_ALL_USERS = "add_for_all_users"; 439 440 /** 441 * The date the row is last inserted, updated, or marked as deleted, in milliseconds 442 * since the epoch. Read only. 443 * <P>Type: INTEGER (long)</P> 444 */ 445 public static final String LAST_MODIFIED = "last_modified"; 446 447 /** 448 * If a successful call is made that is longer than this duration, update the phone number 449 * in the ContactsProvider with the normalized version of the number, based on the user's 450 * current country code. 451 */ 452 private static final int MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS = 1000 * 10; 453 454 /** 455 * Adds a call to the call log. 456 * 457 * @param ci the CallerInfo object to get the target contact from. Can be null 458 * if the contact is unknown. 459 * @param context the context used to get the ContentResolver 460 * @param number the phone number to be added to the calls db 461 * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which 462 * is set by the network and denotes the number presenting rules for 463 * "allowed", "payphone", "restricted" or "unknown" 464 * @param callType enumerated values for "incoming", "outgoing", or "missed" 465 * @param features features of the call (e.g. Video). 466 * @param accountHandle The accountHandle object identifying the provider of the call 467 * @param start time stamp for the call in milliseconds 468 * @param duration call duration in seconds 469 * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for 470 * the call. 471 * @result The URI of the call log entry belonging to the user that made or received this 472 * call. 473 * {@hide} 474 */ 475 public static Uri addCall(CallerInfo ci, Context context, String number, 476 int presentation, int callType, int features, PhoneAccountHandle accountHandle, 477 long start, int duration, Long dataUsage) { 478 return addCall(ci, context, number, /* postDialDigits =*/ "", presentation, 479 callType, features, accountHandle, 480 start, duration, dataUsage, /* addForAllUsers =*/ false, 481 /* userToBeInsertedTo =*/ null, /* is_read =*/ false); 482 } 483 484 485 /** 486 * Adds a call to the call log. 487 * 488 * @param ci the CallerInfo object to get the target contact from. Can be null 489 * if the contact is unknown. 490 * @param context the context used to get the ContentResolver 491 * @param number the phone number to be added to the calls db 492 * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which 493 * is set by the network and denotes the number presenting rules for 494 * "allowed", "payphone", "restricted" or "unknown" 495 * @param callType enumerated values for "incoming", "outgoing", or "missed" 496 * @param features features of the call (e.g. Video). 497 * @param accountHandle The accountHandle object identifying the provider of the call 498 * @param start time stamp for the call in milliseconds 499 * @param duration call duration in seconds 500 * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for 501 * the call. 502 * @param addForAllUsers If true, the call is added to the call log of all currently 503 * running users. The caller must have the MANAGE_USERS permission if this is true. 504 * @param userToBeInsertedTo {@link UserHandle} of user that the call is going to be 505 * inserted to. null if it is inserted to the current user. The 506 * value is ignored if @{link addForAllUsers} is true. 507 * @result The URI of the call log entry belonging to the user that made or received this 508 * call. 509 * {@hide} 510 */ 511 public static Uri addCall(CallerInfo ci, Context context, String number, 512 String postDialDigits, int presentation, int callType, int features, 513 PhoneAccountHandle accountHandle, long start, int duration, Long dataUsage, 514 boolean addForAllUsers, UserHandle userToBeInsertedTo) { 515 return addCall(ci, context, number, postDialDigits, presentation, callType, features, 516 accountHandle, start, duration, dataUsage, addForAllUsers, userToBeInsertedTo, 517 /* is_read =*/ false); 518 } 519 520 /** 521 * Adds a call to the call log. 522 * 523 * @param ci the CallerInfo object to get the target contact from. Can be null 524 * if the contact is unknown. 525 * @param context the context used to get the ContentResolver 526 * @param number the phone number to be added to the calls db 527 * @param postDialDigits the post-dial digits that were dialed after the number, 528 * if it was outgoing. Otherwise it is ''. 529 * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which 530 * is set by the network and denotes the number presenting rules for 531 * "allowed", "payphone", "restricted" or "unknown" 532 * @param callType enumerated values for "incoming", "outgoing", or "missed" 533 * @param features features of the call (e.g. Video). 534 * @param accountHandle The accountHandle object identifying the provider of the call 535 * @param start time stamp for the call in milliseconds 536 * @param duration call duration in seconds 537 * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for 538 * the call. 539 * @param addForAllUsers If true, the call is added to the call log of all currently 540 * running users. The caller must have the MANAGE_USERS permission if this is true. 541 * @param userToBeInsertedTo {@link UserHandle} of user that the call is going to be 542 * inserted to. null if it is inserted to the current user. The 543 * value is ignored if @{link addForAllUsers} is true. 544 * @param is_read Flag to show if the missed call log has been read by the user or not. 545 * Used for call log restore of missed calls. 546 * 547 * @result The URI of the call log entry belonging to the user that made or received this 548 * call. This could be of the shadow provider. Do not return it to non-system apps, 549 * as they don't have permissions. 550 * {@hide} 551 */ 552 public static Uri addCall(CallerInfo ci, Context context, String number, 553 String postDialDigits, int presentation, int callType, int features, 554 PhoneAccountHandle accountHandle, long start, int duration, Long dataUsage, 555 boolean addForAllUsers, UserHandle userToBeInsertedTo, boolean is_read) { 556 if (VERBOSE_LOG) { 557 Log.v(LOG_TAG, String.format("Add call: number=%s, user=%s, for all=%s", 558 number, userToBeInsertedTo, addForAllUsers)); 559 } 560 final ContentResolver resolver = context.getContentResolver(); 561 int numberPresentation = PRESENTATION_ALLOWED; 562 563 TelecomManager tm = null; 564 try { 565 tm = TelecomManager.from(context); 566 } catch (UnsupportedOperationException e) {} 567 568 String accountAddress = null; 569 if (tm != null && accountHandle != null) { 570 PhoneAccount account = tm.getPhoneAccount(accountHandle); 571 if (account != null) { 572 Uri address = account.getSubscriptionAddress(); 573 if (address != null) { 574 accountAddress = address.getSchemeSpecificPart(); 575 } 576 } 577 } 578 579 // Remap network specified number presentation types 580 // PhoneConstants.PRESENTATION_xxx to calllog number presentation types 581 // Calls.PRESENTATION_xxx, in order to insulate the persistent calllog 582 // from any future radio changes. 583 // If the number field is empty set the presentation type to Unknown. 584 if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) { 585 numberPresentation = PRESENTATION_RESTRICTED; 586 } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) { 587 numberPresentation = PRESENTATION_PAYPHONE; 588 } else if (TextUtils.isEmpty(number) 589 || presentation == PhoneConstants.PRESENTATION_UNKNOWN) { 590 numberPresentation = PRESENTATION_UNKNOWN; 591 } 592 if (numberPresentation != PRESENTATION_ALLOWED) { 593 number = ""; 594 if (ci != null) { 595 ci.name = ""; 596 } 597 } 598 599 // accountHandle information 600 String accountComponentString = null; 601 String accountId = null; 602 if (accountHandle != null) { 603 accountComponentString = accountHandle.getComponentName().flattenToString(); 604 accountId = accountHandle.getId(); 605 } 606 607 ContentValues values = new ContentValues(6); 608 609 values.put(NUMBER, number); 610 values.put(POST_DIAL_DIGITS, postDialDigits); 611 values.put(NUMBER_PRESENTATION, Integer.valueOf(numberPresentation)); 612 values.put(TYPE, Integer.valueOf(callType)); 613 values.put(FEATURES, features); 614 values.put(DATE, Long.valueOf(start)); 615 values.put(DURATION, Long.valueOf(duration)); 616 if (dataUsage != null) { 617 values.put(DATA_USAGE, dataUsage); 618 } 619 values.put(PHONE_ACCOUNT_COMPONENT_NAME, accountComponentString); 620 values.put(PHONE_ACCOUNT_ID, accountId); 621 values.put(PHONE_ACCOUNT_ADDRESS, accountAddress); 622 values.put(NEW, Integer.valueOf(1)); 623 values.put(ADD_FOR_ALL_USERS, addForAllUsers ? 1 : 0); 624 625 if (callType == MISSED_TYPE) { 626 values.put(IS_READ, Integer.valueOf(is_read ? 1 : 0)); 627 } 628 629 if ((ci != null) && (ci.contactIdOrZero > 0)) { 630 // Update usage information for the number associated with the contact ID. 631 // We need to use both the number and the ID for obtaining a data ID since other 632 // contacts may have the same number. 633 634 final Cursor cursor; 635 636 // We should prefer normalized one (probably coming from 637 // Phone.NORMALIZED_NUMBER column) first. If it isn't available try others. 638 if (ci.normalizedNumber != null) { 639 final String normalizedPhoneNumber = ci.normalizedNumber; 640 cursor = resolver.query(Phone.CONTENT_URI, 641 new String[] { Phone._ID }, 642 Phone.CONTACT_ID + " =? AND " + Phone.NORMALIZED_NUMBER + " =?", 643 new String[] { String.valueOf(ci.contactIdOrZero), 644 normalizedPhoneNumber}, 645 null); 646 } else { 647 final String phoneNumber = ci.phoneNumber != null ? ci.phoneNumber : number; 648 cursor = resolver.query( 649 Uri.withAppendedPath(Callable.CONTENT_FILTER_URI, 650 Uri.encode(phoneNumber)), 651 new String[] { Phone._ID }, 652 Phone.CONTACT_ID + " =?", 653 new String[] { String.valueOf(ci.contactIdOrZero) }, 654 null); 655 } 656 657 if (cursor != null) { 658 try { 659 if (cursor.getCount() > 0 && cursor.moveToFirst()) { 660 final String dataId = cursor.getString(0); 661 updateDataUsageStatForData(resolver, dataId); 662 if (duration >= MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS 663 && callType == Calls.OUTGOING_TYPE 664 && TextUtils.isEmpty(ci.normalizedNumber)) { 665 updateNormalizedNumber(context, resolver, dataId, number); 666 } 667 } 668 } finally { 669 cursor.close(); 670 } 671 } 672 } 673 674 /* 675 Writing the calllog works in the following way: 676 - All user entries 677 - if user-0 is encrypted, insert to user-0's shadow only. 678 (other users should also be encrypted, so nothing to do for other users.) 679 - if user-0 is decrypted, insert to user-0's real provider, as well as 680 all other users that are running and decrypted and should have calllog. 681 682 - Single user entry. 683 - If the target user is encryted, insert to its shadow. 684 - Otherwise insert to its real provider. 685 686 When the (real) calllog provider starts, it copies entries that it missed from 687 elsewhere. 688 - When user-0's (real) provider starts, it copies from user-0's shadow, and clears 689 the shadow. 690 691 - When other users (real) providers start, unless it shouldn't have calllog entries, 692 - Copy from the user's shadow, and clears the shadow. 693 - Copy from user-0's entries that are FOR_ALL_USERS = 1. (and don't clear it.) 694 */ 695 696 Uri result = null; 697 698 final UserManager userManager = context.getSystemService(UserManager.class); 699 final int currentUserId = userManager.getUserHandle(); 700 701 if (addForAllUsers) { 702 // First, insert to the system user. 703 final Uri uriForSystem = addEntryAndRemoveExpiredEntries( 704 context, userManager, UserHandle.SYSTEM, values); 705 if (uriForSystem == null 706 || SHADOW_AUTHORITY.equals(uriForSystem.getAuthority())) { 707 // This means the system user is still encrypted and the entry has inserted 708 // into the shadow. This means other users are still all encrypted. 709 // Nothing further to do; just return null. 710 return null; 711 } 712 if (UserHandle.USER_SYSTEM == currentUserId) { 713 result = uriForSystem; 714 } 715 716 // Otherwise, insert to all other users that are running and unlocked. 717 718 final List<UserInfo> users = userManager.getUsers(true); 719 720 final int count = users.size(); 721 for (int i = 0; i < count; i++) { 722 final UserInfo userInfo = users.get(i); 723 final UserHandle userHandle = userInfo.getUserHandle(); 724 final int userId = userHandle.getIdentifier(); 725 726 if (userHandle.isSystem()) { 727 // Already written. 728 continue; 729 } 730 731 if (!shouldHaveSharedCallLogEntries(context, userManager, userId)) { 732 // Shouldn't have calllog entries. 733 continue; 734 } 735 736 // For other users, we write only when they're running *and* decrypted. 737 // Other providers will copy from the system user's real provider, when they 738 // start. 739 if (userManager.isUserRunning(userHandle) 740 && userManager.isUserUnlocked(userHandle)) { 741 final Uri uri = addEntryAndRemoveExpiredEntries(context, userManager, 742 userHandle, values); 743 if (userId == currentUserId) { 744 result = uri; 745 } 746 } 747 } 748 } else { 749 // Single-user entry. Just write to that user, assuming it's running. If the 750 // user is encrypted, we write to the shadow calllog. 751 752 final UserHandle targetUserHandle = userToBeInsertedTo != null 753 ? userToBeInsertedTo 754 : UserHandle.of(currentUserId); 755 result = addEntryAndRemoveExpiredEntries(context, userManager, targetUserHandle, 756 values); 757 } 758 return result; 759 } 760 761 /** @hide */ 762 public static boolean shouldHaveSharedCallLogEntries(Context context, 763 UserManager userManager, int userId) { 764 if (userManager.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, 765 UserHandle.of(userId))) { 766 return false; 767 } 768 final UserInfo userInfo = userManager.getUserInfo(userId); 769 return userInfo != null && !userInfo.isManagedProfile(); 770 } 771 772 /** 773 * Query the call log database for the last dialed number. 774 * @param context Used to get the content resolver. 775 * @return The last phone number dialed (outgoing) or an empty 776 * string if none exist yet. 777 */ 778 public static String getLastOutgoingCall(Context context) { 779 final ContentResolver resolver = context.getContentResolver(); 780 Cursor c = null; 781 try { 782 c = resolver.query( 783 CONTENT_URI, 784 new String[] {NUMBER}, 785 TYPE + " = " + OUTGOING_TYPE, 786 null, 787 DEFAULT_SORT_ORDER + " LIMIT 1"); 788 if (c == null || !c.moveToFirst()) { 789 return ""; 790 } 791 return c.getString(0); 792 } finally { 793 if (c != null) c.close(); 794 } 795 } 796 797 private static Uri addEntryAndRemoveExpiredEntries(Context context, UserManager userManager, 798 UserHandle user, ContentValues values) { 799 final ContentResolver resolver = context.getContentResolver(); 800 801 final Uri uri = ContentProvider.maybeAddUserId( 802 userManager.isUserUnlocked(user) ? CONTENT_URI : SHADOW_CONTENT_URI, 803 user.getIdentifier()); 804 805 if (VERBOSE_LOG) { 806 Log.v(LOG_TAG, String.format("Inserting to %s", uri)); 807 } 808 809 try { 810 final Uri result = resolver.insert(uri, values); 811 resolver.delete(uri, "_id IN " + 812 "(SELECT _id FROM calls ORDER BY " + DEFAULT_SORT_ORDER 813 + " LIMIT -1 OFFSET 500)", null); 814 return result; 815 } catch (IllegalArgumentException e) { 816 Log.w(LOG_TAG, "Failed to insert calllog", e); 817 // Even though we make sure the target user is running and decrypted before calling 818 // this method, there's a chance that the user just got shut down, in which case 819 // we'll still get "IllegalArgumentException: Unknown URL content://call_log/calls". 820 return null; 821 } 822 } 823 824 private static void updateDataUsageStatForData(ContentResolver resolver, String dataId) { 825 final Uri feedbackUri = DataUsageFeedback.FEEDBACK_URI.buildUpon() 826 .appendPath(dataId) 827 .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, 828 DataUsageFeedback.USAGE_TYPE_CALL) 829 .build(); 830 resolver.update(feedbackUri, new ContentValues(), null, null); 831 } 832 833 /* 834 * Update the normalized phone number for the given dataId in the ContactsProvider, based 835 * on the user's current country. 836 */ 837 private static void updateNormalizedNumber(Context context, ContentResolver resolver, 838 String dataId, String number) { 839 if (TextUtils.isEmpty(number) || TextUtils.isEmpty(dataId)) { 840 return; 841 } 842 final String countryIso = getCurrentCountryIso(context); 843 if (TextUtils.isEmpty(countryIso)) { 844 return; 845 } 846 final String normalizedNumber = PhoneNumberUtils.formatNumberToE164(number, 847 getCurrentCountryIso(context)); 848 if (TextUtils.isEmpty(normalizedNumber)) { 849 return; 850 } 851 final ContentValues values = new ContentValues(); 852 values.put(Phone.NORMALIZED_NUMBER, normalizedNumber); 853 resolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[] {dataId}); 854 } 855 856 private static String getCurrentCountryIso(Context context) { 857 String countryIso = null; 858 final CountryDetector detector = (CountryDetector) context.getSystemService( 859 Context.COUNTRY_DETECTOR); 860 if (detector != null) { 861 final Country country = detector.detectCountry(); 862 if (country != null) { 863 countryIso = country.getCountryIso(); 864 } 865 } 866 return countryIso; 867 } 868 } 869} 870