CallLog.java revision 1bf206b766654ea9c4e9bc7a703a9d5f1d30ab72
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         * Call log type for a call which was answered on another device.  Used in situations where
201         * a call rings on multiple devices simultaneously and it ended up being answered on a
202         * device other than the current one.
203         * @hide
204         */
205        public static final int ANSWERED_EXTERNALLY_TYPE = 7;
206
207        /**
208         * Bit-mask describing features of the call (e.g. video).
209         *
210         * <P>Type: INTEGER (int)</P>
211         */
212        public static final String FEATURES = "features";
213
214        /** Call had video. */
215        public static final int FEATURES_VIDEO = 0x1;
216
217        /**
218         * Call was pulled externally.
219         * @hide
220         */
221        public static final int FEATURES_PULLED_EXTERNALLY = 0x2;
222
223        /**
224         * The phone number as the user entered it.
225         * <P>Type: TEXT</P>
226         */
227        public static final String NUMBER = "number";
228
229        /**
230         * The number presenting rules set by the network.
231         *
232         * <p>
233         * Allowed values:
234         * <ul>
235         * <li>{@link #PRESENTATION_ALLOWED}</li>
236         * <li>{@link #PRESENTATION_RESTRICTED}</li>
237         * <li>{@link #PRESENTATION_UNKNOWN}</li>
238         * <li>{@link #PRESENTATION_PAYPHONE}</li>
239         * </ul>
240         * </p>
241         *
242         * <P>Type: INTEGER</P>
243         */
244        public static final String NUMBER_PRESENTATION = "presentation";
245
246        /** Number is allowed to display for caller id. */
247        public static final int PRESENTATION_ALLOWED = 1;
248        /** Number is blocked by user. */
249        public static final int PRESENTATION_RESTRICTED = 2;
250        /** Number is not specified or unknown by network. */
251        public static final int PRESENTATION_UNKNOWN = 3;
252        /** Number is a pay phone. */
253        public static final int PRESENTATION_PAYPHONE = 4;
254
255        /**
256         * The ISO 3166-1 two letters country code of the country where the
257         * user received or made the call.
258         * <P>
259         * Type: TEXT
260         * </P>
261         */
262        public static final String COUNTRY_ISO = "countryiso";
263
264        /**
265         * The date the call occured, in milliseconds since the epoch
266         * <P>Type: INTEGER (long)</P>
267         */
268        public static final String DATE = "date";
269
270        /**
271         * The duration of the call in seconds
272         * <P>Type: INTEGER (long)</P>
273         */
274        public static final String DURATION = "duration";
275
276        /**
277         * The data usage of the call in bytes.
278         * <P>Type: INTEGER (long)</P>
279         */
280        public static final String DATA_USAGE = "data_usage";
281
282        /**
283         * Whether or not the call has been acknowledged
284         * <P>Type: INTEGER (boolean)</P>
285         */
286        public static final String NEW = "new";
287
288        /**
289         * The cached name associated with the phone number, if it exists.
290         * This value is not guaranteed to be current, if the contact information
291         * associated with this number has changed.
292         * <P>Type: TEXT</P>
293         */
294        public static final String CACHED_NAME = "name";
295
296        /**
297         * The cached number type (Home, Work, etc) associated with the
298         * phone number, if it exists.
299         * This value is not guaranteed to be current, if the contact information
300         * associated with this number has changed.
301         * <P>Type: INTEGER</P>
302         */
303        public static final String CACHED_NUMBER_TYPE = "numbertype";
304
305        /**
306         * The cached number label, for a custom number type, associated with the
307         * phone number, if it exists.
308         * This value is not guaranteed to be current, if the contact information
309         * associated with this number has changed.
310         * <P>Type: TEXT</P>
311         */
312        public static final String CACHED_NUMBER_LABEL = "numberlabel";
313
314        /**
315         * URI of the voicemail entry. Populated only for {@link #VOICEMAIL_TYPE}.
316         * <P>Type: TEXT</P>
317         */
318        public static final String VOICEMAIL_URI = "voicemail_uri";
319
320        /**
321         * Transcription of the call or voicemail entry. This will only be populated for call log
322         * entries of type {@link #VOICEMAIL_TYPE} that have valid transcriptions.
323         */
324        public static final String TRANSCRIPTION = "transcription";
325
326        /**
327         * Whether this item has been read or otherwise consumed by the user.
328         * <p>
329         * Unlike the {@link #NEW} field, which requires the user to have acknowledged the
330         * existence of the entry, this implies the user has interacted with the entry.
331         * <P>Type: INTEGER (boolean)</P>
332         */
333        public static final String IS_READ = "is_read";
334
335        /**
336         * A geocoded location for the number associated with this call.
337         * <p>
338         * The string represents a city, state, or country associated with the number.
339         * <P>Type: TEXT</P>
340         */
341        public static final String GEOCODED_LOCATION = "geocoded_location";
342
343        /**
344         * The cached URI to look up the contact associated with the phone number, if it exists.
345         * This value may not be current if the contact information associated with this number
346         * has changed.
347         * <P>Type: TEXT</P>
348         */
349        public static final String CACHED_LOOKUP_URI = "lookup_uri";
350
351        /**
352         * The cached phone number of the contact which matches this entry, if it exists.
353         * This value may not be current if the contact information associated with this number
354         * has changed.
355         * <P>Type: TEXT</P>
356         */
357        public static final String CACHED_MATCHED_NUMBER = "matched_number";
358
359        /**
360         * The cached normalized(E164) version of the phone number, if it exists.
361         * This value may not be current if the contact information associated with this number
362         * has changed.
363         * <P>Type: TEXT</P>
364         */
365        public static final String CACHED_NORMALIZED_NUMBER = "normalized_number";
366
367        /**
368         * The cached photo id of the picture associated with the phone number, if it exists.
369         * This value may not be current if the contact information associated with this number
370         * has changed.
371         * <P>Type: INTEGER (long)</P>
372         */
373        public static final String CACHED_PHOTO_ID = "photo_id";
374
375        /**
376         * The cached photo URI of the picture associated with the phone number, if it exists.
377         * This value may not be current if the contact information associated with this number
378         * has changed.
379         * <P>Type: TEXT (URI)</P>
380         */
381        public static final String CACHED_PHOTO_URI = "photo_uri";
382
383        /**
384         * The cached phone number, formatted with formatting rules based on the country the
385         * user was in when the call was made or received.
386         * This value is not guaranteed to be present, and may not be current if the contact
387         * information associated with this number
388         * has changed.
389         * <P>Type: TEXT</P>
390         */
391        public static final String CACHED_FORMATTED_NUMBER = "formatted_number";
392
393        // Note: PHONE_ACCOUNT_* constant values are "subscription_*" due to a historic naming
394        // that was encoded into call log databases.
395
396        /**
397         * The component name of the account used to place or receive the call; in string form.
398         * <P>Type: TEXT</P>
399         */
400        public static final String PHONE_ACCOUNT_COMPONENT_NAME = "subscription_component_name";
401
402        /**
403         * The identifier for the account used to place or receive the call.
404         * <P>Type: TEXT</P>
405         */
406        public static final String PHONE_ACCOUNT_ID = "subscription_id";
407
408        /**
409         * The address associated with the account used to place or receive the call; in string
410         * form. For SIM-based calls, this is the user's own phone number.
411         * <P>Type: TEXT</P>
412         *
413         * @hide
414         */
415        public static final String PHONE_ACCOUNT_ADDRESS = "phone_account_address";
416
417        /**
418         * Indicates that the entry will be hidden from all queries until the associated
419         * {@link android.telecom.PhoneAccount} is registered with the system.
420         * <P>Type: INTEGER</P>
421         *
422         * @hide
423         */
424        public static final String PHONE_ACCOUNT_HIDDEN = "phone_account_hidden";
425
426        /**
427         * The subscription ID used to place this call.  This is no longer used and has been
428         * replaced with PHONE_ACCOUNT_COMPONENT_NAME/PHONE_ACCOUNT_ID.
429         * For ContactsProvider internal use only.
430         * <P>Type: INTEGER</P>
431         *
432         * @Deprecated
433         * @hide
434         */
435        public static final String SUB_ID = "sub_id";
436
437        /**
438         * The post-dial portion of a dialed number, including any digits dialed after a
439         * {@link TelecomManager#DTMF_CHARACTER_PAUSE} or a {@link
440         * TelecomManager#DTMF_CHARACTER_WAIT} and these characters themselves.
441         * <P>Type: TEXT</P>
442         */
443        public static final String POST_DIAL_DIGITS = "post_dial_digits";
444
445        /**
446         * For an incoming call, the secondary line number the call was received via.
447         * When a SIM card has multiple phone numbers associated with it, the via number indicates
448         * which of the numbers associated with the SIM was called.
449         */
450        public static final String VIA_NUMBER = "via_number";
451
452        /**
453         * Indicates that the entry will be copied from primary user to other users.
454         * <P>Type: INTEGER</P>
455         *
456         * @hide
457         */
458        public static final String ADD_FOR_ALL_USERS = "add_for_all_users";
459
460        /**
461         * The date the row is last inserted, updated, or marked as deleted, in milliseconds
462         * since the epoch. Read only.
463         * <P>Type: INTEGER (long)</P>
464         */
465        public static final String LAST_MODIFIED = "last_modified";
466
467        /**
468         * If a successful call is made that is longer than this duration, update the phone number
469         * in the ContactsProvider with the normalized version of the number, based on the user's
470         * current country code.
471         */
472        private static final int MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS = 1000 * 10;
473
474        /**
475         * Adds a call to the call log.
476         *
477         * @param ci the CallerInfo object to get the target contact from.  Can be null
478         * if the contact is unknown.
479         * @param context the context used to get the ContentResolver
480         * @param number the phone number to be added to the calls db
481         * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
482         *        is set by the network and denotes the number presenting rules for
483         *        "allowed", "payphone", "restricted" or "unknown"
484         * @param callType enumerated values for "incoming", "outgoing", or "missed"
485         * @param features features of the call (e.g. Video).
486         * @param accountHandle The accountHandle object identifying the provider of the call
487         * @param start time stamp for the call in milliseconds
488         * @param duration call duration in seconds
489         * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
490         *                  the call.
491         * @result The URI of the call log entry belonging to the user that made or received this
492         *        call.
493         * {@hide}
494         */
495        public static Uri addCall(CallerInfo ci, Context context, String number,
496                int presentation, int callType, int features, PhoneAccountHandle accountHandle,
497                long start, int duration, Long dataUsage) {
498            return addCall(ci, context, number, /* postDialDigits =*/ "", /* viaNumber =*/ "",
499                    presentation, callType, features, accountHandle, start, duration,
500                    dataUsage, /* addForAllUsers =*/ false, /* userToBeInsertedTo =*/ null,
501                    /* is_read =*/ false);
502        }
503
504
505        /**
506         * Adds a call to the call log.
507         *
508         * @param ci the CallerInfo object to get the target contact from.  Can be null
509         * if the contact is unknown.
510         * @param context the context used to get the ContentResolver
511         * @param number the phone number to be added to the calls db
512         * @param viaNumber the secondary number that the incoming call received with. If the
513         *       call was received with the SIM assigned number, then this field must be ''.
514         * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
515         *        is set by the network and denotes the number presenting rules for
516         *        "allowed", "payphone", "restricted" or "unknown"
517         * @param callType enumerated values for "incoming", "outgoing", or "missed"
518         * @param features features of the call (e.g. Video).
519         * @param accountHandle The accountHandle object identifying the provider of the call
520         * @param start time stamp for the call in milliseconds
521         * @param duration call duration in seconds
522         * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
523         *                  the call.
524         * @param addForAllUsers If true, the call is added to the call log of all currently
525         *        running users. The caller must have the MANAGE_USERS permission if this is true.
526         * @param userToBeInsertedTo {@link UserHandle} of user that the call is going to be
527         *                           inserted to. null if it is inserted to the current user. The
528         *                           value is ignored if @{link addForAllUsers} is true.
529         * @result The URI of the call log entry belonging to the user that made or received this
530         *        call.
531         * {@hide}
532         */
533        public static Uri addCall(CallerInfo ci, Context context, String number,
534                String postDialDigits, String viaNumber, int presentation, int callType,
535                int features, PhoneAccountHandle accountHandle, long start, int duration,
536                Long dataUsage, boolean addForAllUsers, UserHandle userToBeInsertedTo) {
537            return addCall(ci, context, number, postDialDigits, viaNumber, presentation, callType,
538                    features, accountHandle, start, duration, dataUsage, addForAllUsers,
539                    userToBeInsertedTo, /* is_read =*/ false);
540        }
541
542        /**
543         * Adds a call to the call log.
544         *
545         * @param ci the CallerInfo object to get the target contact from.  Can be null
546         * if the contact is unknown.
547         * @param context the context used to get the ContentResolver
548         * @param number the phone number to be added to the calls db
549         * @param postDialDigits the post-dial digits that were dialed after the number,
550         *        if it was outgoing. Otherwise it is ''.
551         * @param viaNumber the secondary number that the incoming call received with. If the
552         *        call was received with the SIM assigned number, then this field must be ''.
553         * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
554         *        is set by the network and denotes the number presenting rules for
555         *        "allowed", "payphone", "restricted" or "unknown"
556         * @param callType enumerated values for "incoming", "outgoing", or "missed"
557         * @param features features of the call (e.g. Video).
558         * @param accountHandle The accountHandle object identifying the provider of the call
559         * @param start time stamp for the call in milliseconds
560         * @param duration call duration in seconds
561         * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
562         *                  the call.
563         * @param addForAllUsers If true, the call is added to the call log of all currently
564         *        running users. The caller must have the MANAGE_USERS permission if this is true.
565         * @param userToBeInsertedTo {@link UserHandle} of user that the call is going to be
566         *                           inserted to. null if it is inserted to the current user. The
567         *                           value is ignored if @{link addForAllUsers} is true.
568         * @param is_read Flag to show if the missed call log has been read by the user or not.
569         *                Used for call log restore of missed calls.
570         *
571         * @result The URI of the call log entry belonging to the user that made or received this
572         *        call.  This could be of the shadow provider.  Do not return it to non-system apps,
573         *        as they don't have permissions.
574         * {@hide}
575         */
576        public static Uri addCall(CallerInfo ci, Context context, String number,
577                String postDialDigits, String viaNumber, int presentation, int callType,
578                int features, PhoneAccountHandle accountHandle, long start, int duration,
579                Long dataUsage, boolean addForAllUsers, UserHandle userToBeInsertedTo,
580                boolean is_read) {
581            if (VERBOSE_LOG) {
582                Log.v(LOG_TAG, String.format("Add call: number=%s, user=%s, for all=%s",
583                        number, userToBeInsertedTo, addForAllUsers));
584            }
585            final ContentResolver resolver = context.getContentResolver();
586            int numberPresentation = PRESENTATION_ALLOWED;
587
588            TelecomManager tm = null;
589            try {
590                tm = TelecomManager.from(context);
591            } catch (UnsupportedOperationException e) {}
592
593            String accountAddress = null;
594            if (tm != null && accountHandle != null) {
595                PhoneAccount account = tm.getPhoneAccount(accountHandle);
596                if (account != null) {
597                    Uri address = account.getSubscriptionAddress();
598                    if (address != null) {
599                        accountAddress = address.getSchemeSpecificPart();
600                    }
601                }
602            }
603
604            // Remap network specified number presentation types
605            // PhoneConstants.PRESENTATION_xxx to calllog number presentation types
606            // Calls.PRESENTATION_xxx, in order to insulate the persistent calllog
607            // from any future radio changes.
608            // If the number field is empty set the presentation type to Unknown.
609            if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
610                numberPresentation = PRESENTATION_RESTRICTED;
611            } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
612                numberPresentation = PRESENTATION_PAYPHONE;
613            } else if (TextUtils.isEmpty(number)
614                    || presentation == PhoneConstants.PRESENTATION_UNKNOWN) {
615                numberPresentation = PRESENTATION_UNKNOWN;
616            }
617            if (numberPresentation != PRESENTATION_ALLOWED) {
618                number = "";
619                if (ci != null) {
620                    ci.name = "";
621                }
622            }
623
624            // accountHandle information
625            String accountComponentString = null;
626            String accountId = null;
627            if (accountHandle != null) {
628                accountComponentString = accountHandle.getComponentName().flattenToString();
629                accountId = accountHandle.getId();
630            }
631
632            ContentValues values = new ContentValues(6);
633
634            values.put(NUMBER, number);
635            values.put(POST_DIAL_DIGITS, postDialDigits);
636            values.put(VIA_NUMBER, viaNumber);
637            values.put(NUMBER_PRESENTATION, Integer.valueOf(numberPresentation));
638            values.put(TYPE, Integer.valueOf(callType));
639            values.put(FEATURES, features);
640            values.put(DATE, Long.valueOf(start));
641            values.put(DURATION, Long.valueOf(duration));
642            if (dataUsage != null) {
643                values.put(DATA_USAGE, dataUsage);
644            }
645            values.put(PHONE_ACCOUNT_COMPONENT_NAME, accountComponentString);
646            values.put(PHONE_ACCOUNT_ID, accountId);
647            values.put(PHONE_ACCOUNT_ADDRESS, accountAddress);
648            values.put(NEW, Integer.valueOf(1));
649            values.put(ADD_FOR_ALL_USERS, addForAllUsers ? 1 : 0);
650
651            if (callType == MISSED_TYPE) {
652                values.put(IS_READ, Integer.valueOf(is_read ? 1 : 0));
653            }
654
655            if ((ci != null) && (ci.contactIdOrZero > 0)) {
656                // Update usage information for the number associated with the contact ID.
657                // We need to use both the number and the ID for obtaining a data ID since other
658                // contacts may have the same number.
659
660                final Cursor cursor;
661
662                // We should prefer normalized one (probably coming from
663                // Phone.NORMALIZED_NUMBER column) first. If it isn't available try others.
664                if (ci.normalizedNumber != null) {
665                    final String normalizedPhoneNumber = ci.normalizedNumber;
666                    cursor = resolver.query(Phone.CONTENT_URI,
667                            new String[] { Phone._ID },
668                            Phone.CONTACT_ID + " =? AND " + Phone.NORMALIZED_NUMBER + " =?",
669                            new String[] { String.valueOf(ci.contactIdOrZero),
670                                    normalizedPhoneNumber},
671                            null);
672                } else {
673                    final String phoneNumber = ci.phoneNumber != null ? ci.phoneNumber : number;
674                    cursor = resolver.query(
675                            Uri.withAppendedPath(Callable.CONTENT_FILTER_URI,
676                                    Uri.encode(phoneNumber)),
677                            new String[] { Phone._ID },
678                            Phone.CONTACT_ID + " =?",
679                            new String[] { String.valueOf(ci.contactIdOrZero) },
680                            null);
681                }
682
683                if (cursor != null) {
684                    try {
685                        if (cursor.getCount() > 0 && cursor.moveToFirst()) {
686                            final String dataId = cursor.getString(0);
687                            updateDataUsageStatForData(resolver, dataId);
688                            if (duration >= MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS
689                                    && callType == Calls.OUTGOING_TYPE
690                                    && TextUtils.isEmpty(ci.normalizedNumber)) {
691                                updateNormalizedNumber(context, resolver, dataId, number);
692                            }
693                        }
694                    } finally {
695                        cursor.close();
696                    }
697                }
698            }
699
700            /*
701                Writing the calllog works in the following way:
702                - All user entries
703                    - if user-0 is encrypted, insert to user-0's shadow only.
704                      (other users should also be encrypted, so nothing to do for other users.)
705                    - if user-0 is decrypted, insert to user-0's real provider, as well as
706                      all other users that are running and decrypted and should have calllog.
707
708                - Single user entry.
709                    - If the target user is encryted, insert to its shadow.
710                    - Otherwise insert to its real provider.
711
712                When the (real) calllog provider starts, it copies entries that it missed from
713                elsewhere.
714                - When user-0's (real) provider starts, it copies from user-0's shadow, and clears
715                  the shadow.
716
717                - When other users (real) providers start, unless it shouldn't have calllog entries,
718                     - Copy from the user's shadow, and clears the shadow.
719                     - Copy from user-0's entries that are FOR_ALL_USERS = 1.  (and don't clear it.)
720             */
721
722            Uri result = null;
723
724            final UserManager userManager = context.getSystemService(UserManager.class);
725            final int currentUserId = userManager.getUserHandle();
726
727            if (addForAllUsers) {
728                // First, insert to the system user.
729                final Uri uriForSystem = addEntryAndRemoveExpiredEntries(
730                        context, userManager, UserHandle.SYSTEM, values);
731                if (uriForSystem == null
732                        || SHADOW_AUTHORITY.equals(uriForSystem.getAuthority())) {
733                    // This means the system user is still encrypted and the entry has inserted
734                    // into the shadow.  This means other users are still all encrypted.
735                    // Nothing further to do; just return null.
736                    return null;
737                }
738                if (UserHandle.USER_SYSTEM == currentUserId) {
739                    result = uriForSystem;
740                }
741
742                // Otherwise, insert to all other users that are running and unlocked.
743
744                final List<UserInfo> users = userManager.getUsers(true);
745
746                final int count = users.size();
747                for (int i = 0; i < count; i++) {
748                    final UserInfo userInfo = users.get(i);
749                    final UserHandle userHandle = userInfo.getUserHandle();
750                    final int userId = userHandle.getIdentifier();
751
752                    if (userHandle.isSystem()) {
753                        // Already written.
754                        continue;
755                    }
756
757                    if (!shouldHaveSharedCallLogEntries(context, userManager, userId)) {
758                        // Shouldn't have calllog entries.
759                        continue;
760                    }
761
762                    // For other users, we write only when they're running *and* decrypted.
763                    // Other providers will copy from the system user's real provider, when they
764                    // start.
765                    if (userManager.isUserRunning(userHandle)
766                            && userManager.isUserUnlocked(userHandle)) {
767                        final Uri uri = addEntryAndRemoveExpiredEntries(context, userManager,
768                                userHandle, values);
769                        if (userId == currentUserId) {
770                            result = uri;
771                        }
772                    }
773                }
774            } else {
775                // Single-user entry. Just write to that user, assuming it's running.  If the
776                // user is encrypted, we write to the shadow calllog.
777
778                final UserHandle targetUserHandle = userToBeInsertedTo != null
779                        ? userToBeInsertedTo
780                        : UserHandle.of(currentUserId);
781                result = addEntryAndRemoveExpiredEntries(context, userManager, targetUserHandle,
782                        values);
783            }
784            return result;
785        }
786
787        /** @hide */
788        public static boolean shouldHaveSharedCallLogEntries(Context context,
789                UserManager userManager, int userId) {
790            if (userManager.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS,
791                    UserHandle.of(userId))) {
792                return false;
793            }
794            final UserInfo userInfo = userManager.getUserInfo(userId);
795            return userInfo != null && !userInfo.isManagedProfile();
796        }
797
798        /**
799         * Query the call log database for the last dialed number.
800         * @param context Used to get the content resolver.
801         * @return The last phone number dialed (outgoing) or an empty
802         * string if none exist yet.
803         */
804        public static String getLastOutgoingCall(Context context) {
805            final ContentResolver resolver = context.getContentResolver();
806            Cursor c = null;
807            try {
808                c = resolver.query(
809                    CONTENT_URI,
810                    new String[] {NUMBER},
811                    TYPE + " = " + OUTGOING_TYPE,
812                    null,
813                    DEFAULT_SORT_ORDER + " LIMIT 1");
814                if (c == null || !c.moveToFirst()) {
815                    return "";
816                }
817                return c.getString(0);
818            } finally {
819                if (c != null) c.close();
820            }
821        }
822
823        private static Uri addEntryAndRemoveExpiredEntries(Context context, UserManager userManager,
824                UserHandle user, ContentValues values) {
825            final ContentResolver resolver = context.getContentResolver();
826
827            final Uri uri = ContentProvider.maybeAddUserId(
828                    userManager.isUserUnlocked(user) ? CONTENT_URI : SHADOW_CONTENT_URI,
829                    user.getIdentifier());
830
831            if (VERBOSE_LOG) {
832                Log.v(LOG_TAG, String.format("Inserting to %s", uri));
833            }
834
835            try {
836                final Uri result = resolver.insert(uri, values);
837                resolver.delete(uri, "_id IN " +
838                        "(SELECT _id FROM calls ORDER BY " + DEFAULT_SORT_ORDER
839                        + " LIMIT -1 OFFSET 500)", null);
840                return result;
841            } catch (IllegalArgumentException e) {
842                Log.w(LOG_TAG, "Failed to insert calllog", e);
843                // Even though we make sure the target user is running and decrypted before calling
844                // this method, there's a chance that the user just got shut down, in which case
845                // we'll still get "IllegalArgumentException: Unknown URL content://call_log/calls".
846                return null;
847            }
848        }
849
850        private static void updateDataUsageStatForData(ContentResolver resolver, String dataId) {
851            final Uri feedbackUri = DataUsageFeedback.FEEDBACK_URI.buildUpon()
852                    .appendPath(dataId)
853                    .appendQueryParameter(DataUsageFeedback.USAGE_TYPE,
854                                DataUsageFeedback.USAGE_TYPE_CALL)
855                    .build();
856            resolver.update(feedbackUri, new ContentValues(), null, null);
857        }
858
859        /*
860         * Update the normalized phone number for the given dataId in the ContactsProvider, based
861         * on the user's current country.
862         */
863        private static void updateNormalizedNumber(Context context, ContentResolver resolver,
864                String dataId, String number) {
865            if (TextUtils.isEmpty(number) || TextUtils.isEmpty(dataId)) {
866                return;
867            }
868            final String countryIso = getCurrentCountryIso(context);
869            if (TextUtils.isEmpty(countryIso)) {
870                return;
871            }
872            final String normalizedNumber = PhoneNumberUtils.formatNumberToE164(number,
873                    getCurrentCountryIso(context));
874            if (TextUtils.isEmpty(normalizedNumber)) {
875                return;
876            }
877            final ContentValues values = new ContentValues();
878            values.put(Phone.NORMALIZED_NUMBER, normalizedNumber);
879            resolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[] {dataId});
880        }
881
882        private static String getCurrentCountryIso(Context context) {
883            String countryIso = null;
884            final CountryDetector detector = (CountryDetector) context.getSystemService(
885                    Context.COUNTRY_DETECTOR);
886            if (detector != null) {
887                final Country country = detector.detectCountry();
888                if (country != null) {
889                    countryIso = country.getCountryIso();
890                }
891            }
892            return countryIso;
893        }
894    }
895}
896