2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package android.provider;
20 import android.content.ContentProvider;
21 import android.content.ContentResolver;
22 import android.content.ContentValues;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.pm.UserInfo;
26 import android.database.Cursor;
27 import android.location.Country;
28 import android.location.CountryDetector;
29 import android.net.Uri;
30 import android.os.UserHandle;
31 import android.os.UserManager;
32 import android.provider.ContactsContract.CommonDataKinds.Callable;
33 import android.provider.ContactsContract.CommonDataKinds.Phone;
34 import android.provider.ContactsContract.Data;
35 import android.provider.ContactsContract.DataUsageFeedback;
36 import android.telecom.PhoneAccount;
37 import android.telecom.PhoneAccountHandle;
38 import android.telecom.TelecomManager;
39 import android.telephony.PhoneNumberUtils;
40 import android.text.TextUtils;
41 import android.util.Log;
43 import com.android.internal.telephony.CallerInfo;
44 import com.android.internal.telephony.PhoneConstants;
46 import java.util.List;
49 * The CallLog provider contains information about placed and received calls.
51 public class CallLog {
52 private static final String LOG_TAG = "CallLog";
53 private static final boolean VERBOSE_LOG = false; // DON'T SUBMIT WITH TRUE.
55 public static final String AUTHORITY = "call_log";
58 * The content:// style URL for this provider
60 public static final Uri CONTENT_URI =
61 Uri.parse("content://" + AUTHORITY);
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.
68 * <p>See the comment in {@link Calls#addCall} for the details.
72 public static final String SHADOW_AUTHORITY = "call_log_shadow";
75 * Contains the recent calls.
77 public static class Calls implements BaseColumns {
79 * The content:// style URL for this table
81 public static final Uri CONTENT_URI =
82 Uri.parse("content://call_log/calls");
85 public static final Uri SHADOW_CONTENT_URI =
86 Uri.parse("content://call_log_shadow/calls");
89 * The content:// style URL for filtering this table on phone numbers
91 public static final Uri CONTENT_FILTER_URI =
92 Uri.parse("content://call_log/calls/filter");
95 * Query parameter used to limit the number of call logs returned.
99 public static final String LIMIT_PARAM_KEY = "limit";
102 * Query parameter used to specify the starting record to return.
106 public static final String OFFSET_PARAM_KEY = "offset";
109 * An optional URI parameter which instructs the provider to allow the operation to be
110 * applied to voicemail records as well.
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.
119 public static final String ALLOW_VOICEMAILS_PARAM_KEY = "allow_voicemails";
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.
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.
131 * The following example brings up the call log, showing only missed calls.
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);
140 public static final String EXTRA_CALL_TYPE_FILTER =
141 "android.provider.extra.CALL_TYPE_FILTER";
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.
148 public static final Uri CONTENT_URI_WITH_VOICEMAIL = CONTENT_URI.buildUpon()
149 .appendQueryParameter(ALLOW_VOICEMAILS_PARAM_KEY, "true")
153 * The default sort order for this table
155 public static final String DEFAULT_SORT_ORDER = "date DESC";
158 * The MIME type of {@link #CONTENT_URI} and {@link #CONTENT_FILTER_URI}
159 * providing a directory of calls.
161 public static final String CONTENT_TYPE = "vnd.android.cursor.dir/calls";
164 * The MIME type of a {@link #CONTENT_URI} sub-directory of a single
167 public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/calls";
170 * The type of the call (incoming, outgoing or missed).
171 * <P>Type: INTEGER (int)</P>
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 * <li>{@link #ANSWERED_EXTERNALLY_TYPE}</li>
186 public static final String TYPE = "type";
188 /** Call log type for incoming calls. */
189 public static final int INCOMING_TYPE = 1;
190 /** Call log type for outgoing calls. */
191 public static final int OUTGOING_TYPE = 2;
192 /** Call log type for missed calls. */
193 public static final int MISSED_TYPE = 3;
194 /** Call log type for voicemails. */
195 public static final int VOICEMAIL_TYPE = 4;
196 /** Call log type for calls rejected by direct user action. */
197 public static final int REJECTED_TYPE = 5;
198 /** Call log type for calls blocked automatically. */
199 public static final int BLOCKED_TYPE = 6;
201 * Call log type for a call which was answered on another device. Used in situations where
202 * a call rings on multiple devices simultaneously and it ended up being answered on a
203 * device other than the current one.
205 public static final int ANSWERED_EXTERNALLY_TYPE = 7;
208 * Bit-mask describing features of the call (e.g. video).
210 * <P>Type: INTEGER (int)</P>
212 public static final String FEATURES = "features";
214 /** Call had video. */
215 public static final int FEATURES_VIDEO = 0x1;
217 /** Call was pulled externally. */
218 public static final int FEATURES_PULLED_EXTERNALLY = 0x2;
221 public static final int FEATURES_HD_CALL = 0x4;
223 /** Call was WIFI call. */
224 public static final int FEATURES_WIFI = 0x8;
227 * The phone number as the user entered it.
230 public static final String NUMBER = "number";
233 * The number presenting rules set by the network.
238 * <li>{@link #PRESENTATION_ALLOWED}</li>
239 * <li>{@link #PRESENTATION_RESTRICTED}</li>
240 * <li>{@link #PRESENTATION_UNKNOWN}</li>
241 * <li>{@link #PRESENTATION_PAYPHONE}</li>
245 * <P>Type: INTEGER</P>
247 public static final String NUMBER_PRESENTATION = "presentation";
249 /** Number is allowed to display for caller id. */
250 public static final int PRESENTATION_ALLOWED = 1;
251 /** Number is blocked by user. */
252 public static final int PRESENTATION_RESTRICTED = 2;
253 /** Number is not specified or unknown by network. */
254 public static final int PRESENTATION_UNKNOWN = 3;
255 /** Number is a pay phone. */
256 public static final int PRESENTATION_PAYPHONE = 4;
259 * The ISO 3166-1 two letters country code of the country where the
260 * user received or made the call.
265 public static final String COUNTRY_ISO = "countryiso";
268 * The date the call occured, in milliseconds since the epoch
269 * <P>Type: INTEGER (long)</P>
271 public static final String DATE = "date";
274 * The duration of the call in seconds
275 * <P>Type: INTEGER (long)</P>
277 public static final String DURATION = "duration";
280 * The data usage of the call in bytes.
281 * <P>Type: INTEGER (long)</P>
283 public static final String DATA_USAGE = "data_usage";
286 * Whether or not the call has been acknowledged
287 * <P>Type: INTEGER (boolean)</P>
289 public static final String NEW = "new";
292 * The cached name associated with the phone number, if it exists.
294 * <p>This value is typically filled in by the dialer app for the caching purpose,
295 * so it's not guaranteed to be present, and may not be current if the contact
296 * information associated with this number has changed.
299 public static final String CACHED_NAME = "name";
302 * The cached number type (Home, Work, etc) associated with the
303 * phone number, if it exists.
305 * <p>This value is typically filled in by the dialer app for the caching purpose,
306 * so it's not guaranteed to be present, and may not be current if the contact
307 * information associated with this number has changed.
308 * <P>Type: INTEGER</P>
310 public static final String CACHED_NUMBER_TYPE = "numbertype";
313 * The cached number label, for a custom number type, associated with the
314 * phone number, if it exists.
316 * <p>This value is typically filled in by the dialer app for the caching purpose,
317 * so it's not guaranteed to be present, and may not be current if the contact
318 * information associated with this number has changed.
321 public static final String CACHED_NUMBER_LABEL = "numberlabel";
324 * URI of the voicemail entry. Populated only for {@link #VOICEMAIL_TYPE}.
327 public static final String VOICEMAIL_URI = "voicemail_uri";
330 * Transcription of the call or voicemail entry. This will only be populated for call log
331 * entries of type {@link #VOICEMAIL_TYPE} that have valid transcriptions.
333 public static final String TRANSCRIPTION = "transcription";
336 * State of voicemail transcription entry. This will only be populated for call log
337 * entries of type {@link #VOICEMAIL_TYPE}.
340 public static final String TRANSCRIPTION_STATE = "transcription_state";
343 * Whether this item has been read or otherwise consumed by the user.
345 * Unlike the {@link #NEW} field, which requires the user to have acknowledged the
346 * existence of the entry, this implies the user has interacted with the entry.
347 * <P>Type: INTEGER (boolean)</P>
349 public static final String IS_READ = "is_read";
352 * A geocoded location for the number associated with this call.
354 * The string represents a city, state, or country associated with the number.
357 public static final String GEOCODED_LOCATION = "geocoded_location";
360 * The cached URI to look up the contact associated with the phone number, if it exists.
362 * <p>This value is typically filled in by the dialer app for the caching purpose,
363 * so it's not guaranteed to be present, and may not be current if the contact
364 * information associated with this number has changed.
367 public static final String CACHED_LOOKUP_URI = "lookup_uri";
370 * The cached phone number of the contact which matches this entry, if it exists.
372 * <p>This value is typically filled in by the dialer app for the caching purpose,
373 * so it's not guaranteed to be present, and may not be current if the contact
374 * information associated with this number has changed.
377 public static final String CACHED_MATCHED_NUMBER = "matched_number";
380 * The cached normalized(E164) version of the phone number, if it exists.
382 * <p>This value is typically filled in by the dialer app for the caching purpose,
383 * so it's not guaranteed to be present, and may not be current if the contact
384 * information associated with this number has changed.
387 public static final String CACHED_NORMALIZED_NUMBER = "normalized_number";
390 * The cached photo id of the picture associated with the phone number, if it exists.
392 * <p>This value is typically filled in by the dialer app for the caching purpose,
393 * so it's not guaranteed to be present, and may not be current if the contact
394 * information associated with this number has changed.
395 * <P>Type: INTEGER (long)</P>
397 public static final String CACHED_PHOTO_ID = "photo_id";
400 * The cached photo URI of the picture associated with the phone number, if it exists.
402 * <p>This value is typically filled in by the dialer app for the caching purpose,
403 * so it's not guaranteed to be present, and may not be current if the contact
404 * information associated with this number has changed.
405 * <P>Type: TEXT (URI)</P>
407 public static final String CACHED_PHOTO_URI = "photo_uri";
410 * The cached phone number, formatted with formatting rules based on the country the
411 * user was in when the call was made or received.
413 * <p>This value is typically filled in by the dialer app for the caching purpose,
414 * so it's not guaranteed to be present, and may not be current if the contact
415 * information associated with this number has changed.
418 public static final String CACHED_FORMATTED_NUMBER = "formatted_number";
420 // Note: PHONE_ACCOUNT_* constant values are "subscription_*" due to a historic naming
421 // that was encoded into call log databases.
424 * The component name of the account used to place or receive the call; in string form.
427 public static final String PHONE_ACCOUNT_COMPONENT_NAME = "subscription_component_name";
430 * The identifier for the account used to place or receive the call.
433 public static final String PHONE_ACCOUNT_ID = "subscription_id";
436 * The address associated with the account used to place or receive the call; in string
437 * form. For SIM-based calls, this is the user's own phone number.
442 public static final String PHONE_ACCOUNT_ADDRESS = "phone_account_address";
445 * Indicates that the entry will be hidden from all queries until the associated
446 * {@link android.telecom.PhoneAccount} is registered with the system.
447 * <P>Type: INTEGER</P>
451 public static final String PHONE_ACCOUNT_HIDDEN = "phone_account_hidden";
454 * The subscription ID used to place this call. This is no longer used and has been
455 * replaced with PHONE_ACCOUNT_COMPONENT_NAME/PHONE_ACCOUNT_ID.
456 * For ContactsProvider internal use only.
457 * <P>Type: INTEGER</P>
462 public static final String SUB_ID = "sub_id";
465 * The post-dial portion of a dialed number, including any digits dialed after a
466 * {@link TelecomManager#DTMF_CHARACTER_PAUSE} or a {@link
467 * TelecomManager#DTMF_CHARACTER_WAIT} and these characters themselves.
470 public static final String POST_DIAL_DIGITS = "post_dial_digits";
473 * For an incoming call, the secondary line number the call was received via.
474 * When a SIM card has multiple phone numbers associated with it, the via number indicates
475 * which of the numbers associated with the SIM was called.
477 public static final String VIA_NUMBER = "via_number";
480 * Indicates that the entry will be copied from primary user to other users.
481 * <P>Type: INTEGER</P>
485 public static final String ADD_FOR_ALL_USERS = "add_for_all_users";
488 * The date the row is last inserted, updated, or marked as deleted, in milliseconds
489 * since the epoch. Read only.
490 * <P>Type: INTEGER (long)</P>
492 public static final String LAST_MODIFIED = "last_modified";
495 * If a successful call is made that is longer than this duration, update the phone number
496 * in the ContactsProvider with the normalized version of the number, based on the user's
497 * current country code.
499 private static final int MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS = 1000 * 10;
502 * Adds a call to the call log.
504 * @param ci the CallerInfo object to get the target contact from. Can be null
505 * if the contact is unknown.
506 * @param context the context used to get the ContentResolver
507 * @param number the phone number to be added to the calls db
508 * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
509 * is set by the network and denotes the number presenting rules for
510 * "allowed", "payphone", "restricted" or "unknown"
511 * @param callType enumerated values for "incoming", "outgoing", or "missed"
512 * @param features features of the call (e.g. Video).
513 * @param accountHandle The accountHandle object identifying the provider of the call
514 * @param start time stamp for the call in milliseconds
515 * @param duration call duration in seconds
516 * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
518 * @result The URI of the call log entry belonging to the user that made or received this
522 public static Uri addCall(CallerInfo ci, Context context, String number,
523 int presentation, int callType, int features, PhoneAccountHandle accountHandle,
524 long start, int duration, Long dataUsage) {
525 return addCall(ci, context, number, /* postDialDigits =*/ "", /* viaNumber =*/ "",
526 presentation, callType, features, accountHandle, start, duration,
527 dataUsage, /* addForAllUsers =*/ false, /* userToBeInsertedTo =*/ null,
528 /* is_read =*/ false);
533 * Adds a call to the call log.
535 * @param ci the CallerInfo object to get the target contact from. Can be null
536 * if the contact is unknown.
537 * @param context the context used to get the ContentResolver
538 * @param number the phone number to be added to the calls db
539 * @param viaNumber the secondary number that the incoming call received with. If the
540 * call was received with the SIM assigned number, then this field must be ''.
541 * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
542 * is set by the network and denotes the number presenting rules for
543 * "allowed", "payphone", "restricted" or "unknown"
544 * @param callType enumerated values for "incoming", "outgoing", or "missed"
545 * @param features features of the call (e.g. Video).
546 * @param accountHandle The accountHandle object identifying the provider of the call
547 * @param start time stamp for the call in milliseconds
548 * @param duration call duration in seconds
549 * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
551 * @param addForAllUsers If true, the call is added to the call log of all currently
552 * running users. The caller must have the MANAGE_USERS permission if this is true.
553 * @param userToBeInsertedTo {@link UserHandle} of user that the call is going to be
554 * inserted to. null if it is inserted to the current user. The
555 * value is ignored if @{link addForAllUsers} is true.
556 * @result The URI of the call log entry belonging to the user that made or received this
560 public static Uri addCall(CallerInfo ci, Context context, String number,
561 String postDialDigits, String viaNumber, int presentation, int callType,
562 int features, PhoneAccountHandle accountHandle, long start, int duration,
563 Long dataUsage, boolean addForAllUsers, UserHandle userToBeInsertedTo) {
564 return addCall(ci, context, number, postDialDigits, viaNumber, presentation, callType,
565 features, accountHandle, start, duration, dataUsage, addForAllUsers,
566 userToBeInsertedTo, /* is_read =*/ false);
570 * Adds a call to the call log.
572 * @param ci the CallerInfo object to get the target contact from. Can be null
573 * if the contact is unknown.
574 * @param context the context used to get the ContentResolver
575 * @param number the phone number to be added to the calls db
576 * @param postDialDigits the post-dial digits that were dialed after the number,
577 * if it was outgoing. Otherwise it is ''.
578 * @param viaNumber the secondary number that the incoming call received with. If the
579 * call was received with the SIM assigned number, then this field must be ''.
580 * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
581 * is set by the network and denotes the number presenting rules for
582 * "allowed", "payphone", "restricted" or "unknown"
583 * @param callType enumerated values for "incoming", "outgoing", or "missed"
584 * @param features features of the call (e.g. Video).
585 * @param accountHandle The accountHandle object identifying the provider of the call
586 * @param start time stamp for the call in milliseconds
587 * @param duration call duration in seconds
588 * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
590 * @param addForAllUsers If true, the call is added to the call log of all currently
591 * running users. The caller must have the MANAGE_USERS permission if this is true.
592 * @param userToBeInsertedTo {@link UserHandle} of user that the call is going to be
593 * inserted to. null if it is inserted to the current user. The
594 * value is ignored if @{link addForAllUsers} is true.
595 * @param is_read Flag to show if the missed call log has been read by the user or not.
596 * Used for call log restore of missed calls.
598 * @result The URI of the call log entry belonging to the user that made or received this
599 * call. This could be of the shadow provider. Do not return it to non-system apps,
600 * as they don't have permissions.
603 public static Uri addCall(CallerInfo ci, Context context, String number,
604 String postDialDigits, String viaNumber, int presentation, int callType,
605 int features, PhoneAccountHandle accountHandle, long start, int duration,
606 Long dataUsage, boolean addForAllUsers, UserHandle userToBeInsertedTo,
609 Log.v(LOG_TAG, String.format("Add call: number=%s, user=%s, for all=%s",
610 number, userToBeInsertedTo, addForAllUsers));
612 final ContentResolver resolver = context.getContentResolver();
613 int numberPresentation = PRESENTATION_ALLOWED;
615 TelecomManager tm = null;
617 tm = TelecomManager.from(context);
618 } catch (UnsupportedOperationException e) {}
620 String accountAddress = null;
621 if (tm != null && accountHandle != null) {
622 PhoneAccount account = tm.getPhoneAccount(accountHandle);
623 if (account != null) {
624 Uri address = account.getSubscriptionAddress();
625 if (address != null) {
626 accountAddress = address.getSchemeSpecificPart();
631 // Remap network specified number presentation types
632 // PhoneConstants.PRESENTATION_xxx to calllog number presentation types
633 // Calls.PRESENTATION_xxx, in order to insulate the persistent calllog
634 // from any future radio changes.
635 // If the number field is empty set the presentation type to Unknown.
636 if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
637 numberPresentation = PRESENTATION_RESTRICTED;
638 } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
639 numberPresentation = PRESENTATION_PAYPHONE;
640 } else if (TextUtils.isEmpty(number)
641 || presentation == PhoneConstants.PRESENTATION_UNKNOWN) {
642 numberPresentation = PRESENTATION_UNKNOWN;
644 if (numberPresentation != PRESENTATION_ALLOWED) {
651 // accountHandle information
652 String accountComponentString = null;
653 String accountId = null;
654 if (accountHandle != null) {
655 accountComponentString = accountHandle.getComponentName().flattenToString();
656 accountId = accountHandle.getId();
659 ContentValues values = new ContentValues(6);
661 values.put(NUMBER, number);
662 values.put(POST_DIAL_DIGITS, postDialDigits);
663 values.put(VIA_NUMBER, viaNumber);
664 values.put(NUMBER_PRESENTATION, Integer.valueOf(numberPresentation));
665 values.put(TYPE, Integer.valueOf(callType));
666 values.put(FEATURES, features);
667 values.put(DATE, Long.valueOf(start));
668 values.put(DURATION, Long.valueOf(duration));
669 if (dataUsage != null) {
670 values.put(DATA_USAGE, dataUsage);
672 values.put(PHONE_ACCOUNT_COMPONENT_NAME, accountComponentString);
673 values.put(PHONE_ACCOUNT_ID, accountId);
674 values.put(PHONE_ACCOUNT_ADDRESS, accountAddress);
675 values.put(NEW, Integer.valueOf(1));
676 values.put(ADD_FOR_ALL_USERS, addForAllUsers ? 1 : 0);
678 if (callType == MISSED_TYPE) {
679 values.put(IS_READ, Integer.valueOf(is_read ? 1 : 0));
682 if ((ci != null) && (ci.contactIdOrZero > 0)) {
683 // Update usage information for the number associated with the contact ID.
684 // We need to use both the number and the ID for obtaining a data ID since other
685 // contacts may have the same number.
689 // We should prefer normalized one (probably coming from
690 // Phone.NORMALIZED_NUMBER column) first. If it isn't available try others.
691 if (ci.normalizedNumber != null) {
692 final String normalizedPhoneNumber = ci.normalizedNumber;
693 cursor = resolver.query(Phone.CONTENT_URI,
694 new String[] { Phone._ID },
695 Phone.CONTACT_ID + " =? AND " + Phone.NORMALIZED_NUMBER + " =?",
696 new String[] { String.valueOf(ci.contactIdOrZero),
697 normalizedPhoneNumber},
700 final String phoneNumber = ci.phoneNumber != null ? ci.phoneNumber : number;
701 cursor = resolver.query(
702 Uri.withAppendedPath(Callable.CONTENT_FILTER_URI,
703 Uri.encode(phoneNumber)),
704 new String[] { Phone._ID },
705 Phone.CONTACT_ID + " =?",
706 new String[] { String.valueOf(ci.contactIdOrZero) },
710 if (cursor != null) {
712 if (cursor.getCount() > 0 && cursor.moveToFirst()) {
713 final String dataId = cursor.getString(0);
714 updateDataUsageStatForData(resolver, dataId);
715 if (duration >= MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS
716 && callType == Calls.OUTGOING_TYPE
717 && TextUtils.isEmpty(ci.normalizedNumber)) {
718 updateNormalizedNumber(context, resolver, dataId, number);
728 Writing the calllog works in the following way:
730 - if user-0 is encrypted, insert to user-0's shadow only.
731 (other users should also be encrypted, so nothing to do for other users.)
732 - if user-0 is decrypted, insert to user-0's real provider, as well as
733 all other users that are running and decrypted and should have calllog.
736 - If the target user is encryted, insert to its shadow.
737 - Otherwise insert to its real provider.
739 When the (real) calllog provider starts, it copies entries that it missed from
741 - When user-0's (real) provider starts, it copies from user-0's shadow, and clears
744 - When other users (real) providers start, unless it shouldn't have calllog entries,
745 - Copy from the user's shadow, and clears the shadow.
746 - Copy from user-0's entries that are FOR_ALL_USERS = 1. (and don't clear it.)
751 final UserManager userManager = context.getSystemService(UserManager.class);
752 final int currentUserId = userManager.getUserHandle();
754 if (addForAllUsers) {
755 // First, insert to the system user.
756 final Uri uriForSystem = addEntryAndRemoveExpiredEntries(
757 context, userManager, UserHandle.SYSTEM, values);
758 if (uriForSystem == null
759 || SHADOW_AUTHORITY.equals(uriForSystem.getAuthority())) {
760 // This means the system user is still encrypted and the entry has inserted
761 // into the shadow. This means other users are still all encrypted.
762 // Nothing further to do; just return null.
765 if (UserHandle.USER_SYSTEM == currentUserId) {
766 result = uriForSystem;
769 // Otherwise, insert to all other users that are running and unlocked.
771 final List<UserInfo> users = userManager.getUsers(true);
773 final int count = users.size();
774 for (int i = 0; i < count; i++) {
775 final UserInfo userInfo = users.get(i);
776 final UserHandle userHandle = userInfo.getUserHandle();
777 final int userId = userHandle.getIdentifier();
779 if (userHandle.isSystem()) {
784 if (!shouldHaveSharedCallLogEntries(context, userManager, userId)) {
785 // Shouldn't have calllog entries.
789 // For other users, we write only when they're running *and* decrypted.
790 // Other providers will copy from the system user's real provider, when they
792 if (userManager.isUserRunning(userHandle)
793 && userManager.isUserUnlocked(userHandle)) {
794 final Uri uri = addEntryAndRemoveExpiredEntries(context, userManager,
796 if (userId == currentUserId) {
802 // Single-user entry. Just write to that user, assuming it's running. If the
803 // user is encrypted, we write to the shadow calllog.
805 final UserHandle targetUserHandle = userToBeInsertedTo != null
807 : UserHandle.of(currentUserId);
808 result = addEntryAndRemoveExpiredEntries(context, userManager, targetUserHandle,
815 public static boolean shouldHaveSharedCallLogEntries(Context context,
816 UserManager userManager, int userId) {
817 if (userManager.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS,
818 UserHandle.of(userId))) {
821 final UserInfo userInfo = userManager.getUserInfo(userId);
822 return userInfo != null && !userInfo.isManagedProfile();
826 * Query the call log database for the last dialed number.
827 * @param context Used to get the content resolver.
828 * @return The last phone number dialed (outgoing) or an empty
829 * string if none exist yet.
831 public static String getLastOutgoingCall(Context context) {
832 final ContentResolver resolver = context.getContentResolver();
837 new String[] {NUMBER},
838 TYPE + " = " + OUTGOING_TYPE,
840 DEFAULT_SORT_ORDER + " LIMIT 1");
841 if (c == null || !c.moveToFirst()) {
844 return c.getString(0);
846 if (c != null) c.close();
850 private static Uri addEntryAndRemoveExpiredEntries(Context context, UserManager userManager,
851 UserHandle user, ContentValues values) {
852 final ContentResolver resolver = context.getContentResolver();
854 // Since we're doing this operation on behalf of an app, we only
855 // want to use the actual "unlocked" state.
856 final Uri uri = ContentProvider.maybeAddUserId(
857 userManager.isUserUnlocked(user) ? CONTENT_URI : SHADOW_CONTENT_URI,
858 user.getIdentifier());
861 Log.v(LOG_TAG, String.format("Inserting to %s", uri));
865 // When cleaning up the call log, try to delete older call long entries on a per
866 // PhoneAccount basis first. There can be multiple ConnectionServices causing
867 // the addition of entries in the call log. With the introduction of Self-Managed
868 // ConnectionServices, we want to ensure that a misbehaving self-managed CS cannot
869 // spam the call log with its own entries, causing entries from Telephony to be
871 final Uri result = resolver.insert(uri, values);
872 if (values.containsKey(PHONE_ACCOUNT_ID)
873 && !TextUtils.isEmpty(values.getAsString(PHONE_ACCOUNT_ID))
874 && values.containsKey(PHONE_ACCOUNT_COMPONENT_NAME)
875 && !TextUtils.isEmpty(values.getAsString(PHONE_ACCOUNT_COMPONENT_NAME))) {
876 // Only purge entries for the same phone account.
877 resolver.delete(uri, "_id IN " +
878 "(SELECT _id FROM calls"
879 + " WHERE " + PHONE_ACCOUNT_COMPONENT_NAME + " = ?"
880 + " AND " + PHONE_ACCOUNT_ID + " = ?"
881 + " ORDER BY " + DEFAULT_SORT_ORDER
882 + " LIMIT -1 OFFSET 500)", new String[] {
883 values.getAsString(PHONE_ACCOUNT_COMPONENT_NAME),
884 values.getAsString(PHONE_ACCOUNT_ID)
887 // No valid phone account specified, so default to the old behavior.
888 resolver.delete(uri, "_id IN " +
889 "(SELECT _id FROM calls ORDER BY " + DEFAULT_SORT_ORDER
890 + " LIMIT -1 OFFSET 500)", null);
894 } catch (IllegalArgumentException e) {
895 Log.w(LOG_TAG, "Failed to insert calllog", e);
896 // Even though we make sure the target user is running and decrypted before calling
897 // this method, there's a chance that the user just got shut down, in which case
898 // we'll still get "IllegalArgumentException: Unknown URL content://call_log/calls".
903 private static void updateDataUsageStatForData(ContentResolver resolver, String dataId) {
904 final Uri feedbackUri = DataUsageFeedback.FEEDBACK_URI.buildUpon()
906 .appendQueryParameter(DataUsageFeedback.USAGE_TYPE,
907 DataUsageFeedback.USAGE_TYPE_CALL)
909 resolver.update(feedbackUri, new ContentValues(), null, null);
913 * Update the normalized phone number for the given dataId in the ContactsProvider, based
914 * on the user's current country.
916 private static void updateNormalizedNumber(Context context, ContentResolver resolver,
917 String dataId, String number) {
918 if (TextUtils.isEmpty(number) || TextUtils.isEmpty(dataId)) {
921 final String countryIso = getCurrentCountryIso(context);
922 if (TextUtils.isEmpty(countryIso)) {
925 final String normalizedNumber = PhoneNumberUtils.formatNumberToE164(number,
926 getCurrentCountryIso(context));
927 if (TextUtils.isEmpty(normalizedNumber)) {
930 final ContentValues values = new ContentValues();
931 values.put(Phone.NORMALIZED_NUMBER, normalizedNumber);
932 resolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[] {dataId});
935 private static String getCurrentCountryIso(Context context) {
936 String countryIso = null;
937 final CountryDetector detector = (CountryDetector) context.getSystemService(
938 Context.COUNTRY_DETECTOR);
939 if (detector != null) {
940 final Country country = detector.detectCountry();
941 if (country != null) {
942 countryIso = country.getCountryIso();