CallLog.java revision 52e77501845cd472a7aa0bf680efb017fa97cece
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.telecomm.PhoneAccountHandle;
37import android.telephony.PhoneNumberUtils;
38import android.text.TextUtils;
39
40import com.android.internal.telephony.CallerInfo;
41import com.android.internal.telephony.PhoneConstants;
42
43import java.util.List;
44
45/**
46 * The CallLog provider contains information about placed and received calls.
47 */
48public class CallLog {
49    public static final String AUTHORITY = "call_log";
50
51    /**
52     * The content:// style URL for this provider
53     */
54    public static final Uri CONTENT_URI =
55        Uri.parse("content://" + AUTHORITY);
56
57    /**
58     * Contains the recent calls.
59     */
60    public static class Calls implements BaseColumns {
61        /**
62         * The content:// style URL for this table
63         */
64        public static final Uri CONTENT_URI =
65                Uri.parse("content://call_log/calls");
66
67        /**
68         * The content:// style URL for filtering this table on phone numbers
69         */
70        public static final Uri CONTENT_FILTER_URI =
71                Uri.parse("content://call_log/calls/filter");
72
73        /**
74         * Query parameter used to limit the number of call logs returned.
75         * <p>
76         * TYPE: integer
77         */
78        public static final String LIMIT_PARAM_KEY = "limit";
79
80        /**
81         * Query parameter used to specify the starting record to return.
82         * <p>
83         * TYPE: integer
84         */
85        public static final String OFFSET_PARAM_KEY = "offset";
86
87        /**
88         * An optional URI parameter which instructs the provider to allow the operation to be
89         * applied to voicemail records as well.
90         * <p>
91         * TYPE: Boolean
92         * <p>
93         * Using this parameter with a value of {@code true} will result in a security error if the
94         * calling package does not have appropriate permissions to access voicemails.
95         *
96         * @hide
97         */
98        public static final String ALLOW_VOICEMAILS_PARAM_KEY = "allow_voicemails";
99
100        /**
101         * An optional extra used with {@link #CONTENT_TYPE Calls.CONTENT_TYPE} and
102         * {@link Intent#ACTION_VIEW} to specify that the presented list of calls should be
103         * filtered for a particular call type.
104         *
105         * Applications implementing a call log UI should check for this extra, and display a
106         * filtered list of calls based on the specified call type. If not applicable within the
107         * application's UI, it should be silently ignored.
108         *
109         * <p>
110         * The following example brings up the call log, showing only missed calls.
111         * <pre>
112         * Intent intent = new Intent(Intent.ACTION_VIEW);
113         * intent.setType(CallLog.Calls.CONTENT_TYPE);
114         * intent.putExtra(CallLog.Calls.EXTRA_CALL_TYPE_FILTER, CallLog.Calls.MISSED_TYPE);
115         * startActivity(intent);
116         * </pre>
117         * </p>
118         */
119        public static final String EXTRA_CALL_TYPE_FILTER
120                = "android.provider.extra.call_type_filter";
121
122        /**
123         * Content uri used to access call log entries, including voicemail records. You must have
124         * the READ_CALL_LOG and WRITE_CALL_LOG permissions to read and write to the call log, as
125         * well as READ_VOICEMAIL and WRITE_VOICEMAIL permissions to read and write voicemails.
126         */
127        public static final Uri CONTENT_URI_WITH_VOICEMAIL = CONTENT_URI.buildUpon()
128                .appendQueryParameter(ALLOW_VOICEMAILS_PARAM_KEY, "true")
129                .build();
130
131        /**
132         * The default sort order for this table
133         */
134        public static final String DEFAULT_SORT_ORDER = "date DESC";
135
136        /**
137         * The MIME type of {@link #CONTENT_URI} and {@link #CONTENT_FILTER_URI}
138         * providing a directory of calls.
139         */
140        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/calls";
141
142        /**
143         * The MIME type of a {@link #CONTENT_URI} sub-directory of a single
144         * call.
145         */
146        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/calls";
147
148        /**
149         * The type of the call (incoming, outgoing or missed).
150         * <P>Type: INTEGER (int)</P>
151         */
152        public static final String TYPE = "type";
153
154        /** Call log type for incoming calls. */
155        public static final int INCOMING_TYPE = 1;
156        /** Call log type for outgoing calls. */
157        public static final int OUTGOING_TYPE = 2;
158        /** Call log type for missed calls. */
159        public static final int MISSED_TYPE = 3;
160        /** Call log type for voicemails. */
161        public static final int VOICEMAIL_TYPE = 4;
162
163        /**
164         * Bit-mask describing features of the call (e.g. video).
165         *
166         * <P>Type: INTEGER (int)</P>
167         */
168        public static final String FEATURES = "features";
169
170        /** Call had no associated features (e.g. voice-only). */
171        public static final int FEATURES_NONE = 0x0;
172        /** Call had video. */
173        public static final int FEATURES_VIDEO = 0x1;
174
175        /**
176         * The phone number as the user entered it.
177         * <P>Type: TEXT</P>
178         */
179        public static final String NUMBER = "number";
180
181        /**
182         * The number presenting rules set by the network.
183         *
184         * <p>
185         * Allowed values:
186         * <ul>
187         * <li>{@link #PRESENTATION_ALLOWED}</li>
188         * <li>{@link #PRESENTATION_RESTRICTED}</li>
189         * <li>{@link #PRESENTATION_UNKNOWN}</li>
190         * <li>{@link #PRESENTATION_PAYPHONE}</li>
191         * </ul>
192         * </p>
193         *
194         * <P>Type: INTEGER</P>
195         */
196        public static final String NUMBER_PRESENTATION = "presentation";
197
198        /** Number is allowed to display for caller id. */
199        public static final int PRESENTATION_ALLOWED = 1;
200        /** Number is blocked by user. */
201        public static final int PRESENTATION_RESTRICTED = 2;
202        /** Number is not specified or unknown by network. */
203        public static final int PRESENTATION_UNKNOWN = 3;
204        /** Number is a pay phone. */
205        public static final int PRESENTATION_PAYPHONE = 4;
206
207        /**
208         * The ISO 3166-1 two letters country code of the country where the
209         * user received or made the call.
210         * <P>
211         * Type: TEXT
212         * </P>
213         */
214        public static final String COUNTRY_ISO = "countryiso";
215
216        /**
217         * The date the call occured, in milliseconds since the epoch
218         * <P>Type: INTEGER (long)</P>
219         */
220        public static final String DATE = "date";
221
222        /**
223         * The duration of the call in seconds
224         * <P>Type: INTEGER (long)</P>
225         */
226        public static final String DURATION = "duration";
227
228        /**
229         * The data usage of the call in bytes.
230         * <P>Type: INTEGER (long)</P>
231         */
232        public static final String DATA_USAGE = "data_usage";
233
234        /**
235         * Whether or not the call has been acknowledged
236         * <P>Type: INTEGER (boolean)</P>
237         */
238        public static final String NEW = "new";
239
240        /**
241         * The cached name associated with the phone number, if it exists.
242         * This value is not guaranteed to be current, if the contact information
243         * associated with this number has changed.
244         * <P>Type: TEXT</P>
245         */
246        public static final String CACHED_NAME = "name";
247
248        /**
249         * The cached number type (Home, Work, etc) associated with the
250         * phone number, if it exists.
251         * This value is not guaranteed to be current, if the contact information
252         * associated with this number has changed.
253         * <P>Type: INTEGER</P>
254         */
255        public static final String CACHED_NUMBER_TYPE = "numbertype";
256
257        /**
258         * The cached number label, for a custom number type, associated with the
259         * phone number, if it exists.
260         * This value is not guaranteed to be current, if the contact information
261         * associated with this number has changed.
262         * <P>Type: TEXT</P>
263         */
264        public static final String CACHED_NUMBER_LABEL = "numberlabel";
265
266        /**
267         * URI of the voicemail entry. Populated only for {@link #VOICEMAIL_TYPE}.
268         * <P>Type: TEXT</P>
269         */
270        public static final String VOICEMAIL_URI = "voicemail_uri";
271
272        /**
273         * Transcription of the call or voicemail entry. This will only be populated for call log
274         * entries of type {@link #VOICEMAIL_TYPE} that have valid transcriptions.
275         */
276        public static final String TRANSCRIPTION = "transcription";
277
278        /**
279         * Whether this item has been read or otherwise consumed by the user.
280         * <p>
281         * Unlike the {@link #NEW} field, which requires the user to have acknowledged the
282         * existence of the entry, this implies the user has interacted with the entry.
283         * <P>Type: INTEGER (boolean)</P>
284         */
285        public static final String IS_READ = "is_read";
286
287        /**
288         * A geocoded location for the number associated with this call.
289         * <p>
290         * The string represents a city, state, or country associated with the number.
291         * <P>Type: TEXT</P>
292         */
293        public static final String GEOCODED_LOCATION = "geocoded_location";
294
295        /**
296         * The cached URI to look up the contact associated with the phone number, if it exists.
297         * This value may not be current if the contact information associated with this number
298         * has changed.
299         * <P>Type: TEXT</P>
300         */
301        public static final String CACHED_LOOKUP_URI = "lookup_uri";
302
303        /**
304         * The cached phone number of the contact which matches this entry, if it exists.
305         * This value may not be current if the contact information associated with this number
306         * has changed.
307         * <P>Type: TEXT</P>
308         */
309        public static final String CACHED_MATCHED_NUMBER = "matched_number";
310
311        /**
312         * The cached normalized(E164) version of the phone number, if it exists.
313         * This value may not be current if the contact information associated with this number
314         * has changed.
315         * <P>Type: TEXT</P>
316         */
317        public static final String CACHED_NORMALIZED_NUMBER = "normalized_number";
318
319        /**
320         * The cached photo id of the picture associated with the phone number, if it exists.
321         * This value may not be current if the contact information associated with this number
322         * has changed.
323         * <P>Type: INTEGER (long)</P>
324         */
325        public static final String CACHED_PHOTO_ID = "photo_id";
326
327        /**
328         * The cached phone number, formatted with formatting rules based on the country the
329         * user was in when the call was made or received.
330         * This value is not guaranteed to be present, and may not be current if the contact
331         * information associated with this number
332         * has changed.
333         * <P>Type: TEXT</P>
334         */
335        public static final String CACHED_FORMATTED_NUMBER = "formatted_number";
336
337        // Note: PHONE_ACCOUNT_* constant values are "subscription_*" due to a historic naming
338        // that was encoded into call log databases.
339
340        /**
341         * The component name of the account in string form.
342         * <P>Type: TEXT</P>
343         */
344        public static final String PHONE_ACCOUNT_COMPONENT_NAME = "subscription_component_name";
345
346        /**
347         * The identifier of a account that is unique to a specified component.
348         * <P>Type: TEXT</P>
349         */
350        public static final String PHONE_ACCOUNT_ID = "subscription_id";
351
352        /**
353         * If a successful call is made that is longer than this duration, update the phone number
354         * in the ContactsProvider with the normalized version of the number, based on the user's
355         * current country code.
356         */
357        private static final int MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS = 1000 * 10;
358
359        /**
360         * Adds a call to the call log.
361         *
362         * @param ci the CallerInfo object to get the target contact from.  Can be null
363         * if the contact is unknown.
364         * @param context the context used to get the ContentResolver
365         * @param number the phone number to be added to the calls db
366         * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
367         *        is set by the network and denotes the number presenting rules for
368         *        "allowed", "payphone", "restricted" or "unknown"
369         * @param callType enumerated values for "incoming", "outgoing", or "missed"
370         * @param features features of the call (e.g. Video).
371         * @param accountHandle The accountHandle object identifying the provider of the call
372         * @param start time stamp for the call in milliseconds
373         * @param duration call duration in seconds
374         * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
375         *                  the call.
376         * @result The URI of the call log entry belonging to the user that made or received this
377         *        call.
378         * {@hide}
379         */
380        public static Uri addCall(CallerInfo ci, Context context, String number,
381                int presentation, int callType, int features, PhoneAccountHandle accountHandle,
382                long start, int duration, Long dataUsage) {
383            return addCall(ci, context, number, presentation, callType, features, accountHandle,
384                    start, duration, dataUsage, false);
385        }
386
387        /**
388         * Adds a call to the call log.
389         *
390         * @param ci the CallerInfo object to get the target contact from.  Can be null
391         * if the contact is unknown.
392         * @param context the context used to get the ContentResolver
393         * @param number the phone number to be added to the calls db
394         * @param presentation enum value from PhoneConstants.PRESENTATION_xxx, which
395         *        is set by the network and denotes the number presenting rules for
396         *        "allowed", "payphone", "restricted" or "unknown"
397         * @param callType enumerated values for "incoming", "outgoing", or "missed"
398         * @param features features of the call (e.g. Video).
399         * @param accountHandle The accountHandle object identifying the provider of the call
400         * @param start time stamp for the call in milliseconds
401         * @param duration call duration in seconds
402         * @param dataUsage data usage for the call in bytes, null if data usage was not tracked for
403         *                  the call.
404         * @param addForAllUsers If true, the call is added to the call log of all currently
405         *        running users. The caller must have the MANAGE_USERS permission if this is true.
406         *
407         * @result The URI of the call log entry belonging to the user that made or received this
408         *        call.
409         * {@hide}
410         */
411        public static Uri addCall(CallerInfo ci, Context context, String number,
412                int presentation, int callType, int features, PhoneAccountHandle accountHandle,
413                long start, int duration, Long dataUsage, boolean addForAllUsers) {
414            final ContentResolver resolver = context.getContentResolver();
415            int numberPresentation = PRESENTATION_ALLOWED;
416
417            // Remap network specified number presentation types
418            // PhoneConstants.PRESENTATION_xxx to calllog number presentation types
419            // Calls.PRESENTATION_xxx, in order to insulate the persistent calllog
420            // from any future radio changes.
421            // If the number field is empty set the presentation type to Unknown.
422            if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
423                numberPresentation = PRESENTATION_RESTRICTED;
424            } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
425                numberPresentation = PRESENTATION_PAYPHONE;
426            } else if (TextUtils.isEmpty(number)
427                    || presentation == PhoneConstants.PRESENTATION_UNKNOWN) {
428                numberPresentation = PRESENTATION_UNKNOWN;
429            }
430            if (numberPresentation != PRESENTATION_ALLOWED) {
431                number = "";
432                if (ci != null) {
433                    ci.name = "";
434                }
435            }
436
437            // accountHandle information
438            String accountComponentString = null;
439            String accountId = null;
440            if (accountHandle != null) {
441                accountComponentString = accountHandle.getComponentName().flattenToString();
442                accountId = accountHandle.getId();
443            }
444
445            ContentValues values = new ContentValues(6);
446
447            values.put(NUMBER, number);
448            values.put(NUMBER_PRESENTATION, Integer.valueOf(numberPresentation));
449            values.put(TYPE, Integer.valueOf(callType));
450            values.put(FEATURES, features);
451            values.put(DATE, Long.valueOf(start));
452            values.put(DURATION, Long.valueOf(duration));
453            if (dataUsage != null) {
454                values.put(DATA_USAGE, dataUsage);
455            }
456            values.put(PHONE_ACCOUNT_COMPONENT_NAME, accountComponentString);
457            values.put(PHONE_ACCOUNT_ID, accountId);
458            values.put(NEW, Integer.valueOf(1));
459            if (callType == MISSED_TYPE) {
460                values.put(IS_READ, Integer.valueOf(0));
461            }
462            if (ci != null) {
463                values.put(CACHED_NAME, ci.name);
464                values.put(CACHED_NUMBER_TYPE, ci.numberType);
465                values.put(CACHED_NUMBER_LABEL, ci.numberLabel);
466            }
467
468            if ((ci != null) && (ci.contactIdOrZero > 0)) {
469                // Update usage information for the number associated with the contact ID.
470                // We need to use both the number and the ID for obtaining a data ID since other
471                // contacts may have the same number.
472
473                final Cursor cursor;
474
475                // We should prefer normalized one (probably coming from
476                // Phone.NORMALIZED_NUMBER column) first. If it isn't available try others.
477                if (ci.normalizedNumber != null) {
478                    final String normalizedPhoneNumber = ci.normalizedNumber;
479                    cursor = resolver.query(Phone.CONTENT_URI,
480                            new String[] { Phone._ID },
481                            Phone.CONTACT_ID + " =? AND " + Phone.NORMALIZED_NUMBER + " =?",
482                            new String[] { String.valueOf(ci.contactIdOrZero),
483                                    normalizedPhoneNumber},
484                            null);
485                } else {
486                    final String phoneNumber = ci.phoneNumber != null ? ci.phoneNumber : number;
487                    cursor = resolver.query(
488                            Uri.withAppendedPath(Callable.CONTENT_FILTER_URI,
489                                    Uri.encode(phoneNumber)),
490                            new String[] { Phone._ID },
491                            Phone.CONTACT_ID + " =?",
492                            new String[] { String.valueOf(ci.contactIdOrZero) },
493                            null);
494                }
495
496                if (cursor != null) {
497                    try {
498                        if (cursor.getCount() > 0 && cursor.moveToFirst()) {
499                            final String dataId = cursor.getString(0);
500                            updateDataUsageStatForData(resolver, dataId);
501                            if (duration >= MIN_DURATION_FOR_NORMALIZED_NUMBER_UPDATE_MS
502                                    && callType == Calls.OUTGOING_TYPE
503                                    && TextUtils.isEmpty(ci.normalizedNumber)) {
504                                updateNormalizedNumber(context, resolver, dataId, number);
505                            }
506                        }
507                    } finally {
508                        cursor.close();
509                    }
510                }
511            }
512
513            Uri result = null;
514
515            if (addForAllUsers) {
516                // Insert the entry for all currently running users, in order to trigger any
517                // ContentObservers currently set on the call log.
518                final UserManager userManager = (UserManager) context.getSystemService(
519                        Context.USER_SERVICE);
520                List<UserInfo> users = userManager.getUsers(true);
521                final int currentUserId = userManager.getUserHandle();
522                final int count = users.size();
523                for (int i = 0; i < count; i++) {
524                    final UserInfo user = users.get(i);
525                    final UserHandle userHandle = user.getUserHandle();
526                    if (userManager.isUserRunning(userHandle)
527                            && !userManager.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS,
528                                    userHandle)
529                            && !user.isManagedProfile()) {
530                        Uri uri = addEntryAndRemoveExpiredEntries(context,
531                                ContentProvider.maybeAddUserId(CONTENT_URI, user.id), values);
532                        if (user.id == currentUserId) {
533                            result = uri;
534                        }
535                    }
536                }
537            } else {
538                result = addEntryAndRemoveExpiredEntries(context, CONTENT_URI, values);
539            }
540
541            return result;
542        }
543
544        /**
545         * Query the call log database for the last dialed number.
546         * @param context Used to get the content resolver.
547         * @return The last phone number dialed (outgoing) or an empty
548         * string if none exist yet.
549         */
550        public static String getLastOutgoingCall(Context context) {
551            final ContentResolver resolver = context.getContentResolver();
552            Cursor c = null;
553            try {
554                c = resolver.query(
555                    CONTENT_URI,
556                    new String[] {NUMBER},
557                    TYPE + " = " + OUTGOING_TYPE,
558                    null,
559                    DEFAULT_SORT_ORDER + " LIMIT 1");
560                if (c == null || !c.moveToFirst()) {
561                    return "";
562                }
563                return c.getString(0);
564            } finally {
565                if (c != null) c.close();
566            }
567        }
568
569        private static Uri addEntryAndRemoveExpiredEntries(Context context, Uri uri,
570                ContentValues values) {
571            final ContentResolver resolver = context.getContentResolver();
572            Uri result = resolver.insert(uri, values);
573            resolver.delete(uri, "_id IN " +
574                    "(SELECT _id FROM calls ORDER BY " + DEFAULT_SORT_ORDER
575                    + " LIMIT -1 OFFSET 500)", null);
576            return result;
577        }
578
579        private static void updateDataUsageStatForData(ContentResolver resolver, String dataId) {
580            final Uri feedbackUri = DataUsageFeedback.FEEDBACK_URI.buildUpon()
581                    .appendPath(dataId)
582                    .appendQueryParameter(DataUsageFeedback.USAGE_TYPE,
583                                DataUsageFeedback.USAGE_TYPE_CALL)
584                    .build();
585            resolver.update(feedbackUri, new ContentValues(), null, null);
586        }
587
588        /**
589         * Update the normalized phone number for the given dataId in the ContactsProvider, based
590         * on the user's current country.
591         */
592        private static void updateNormalizedNumber(Context context, ContentResolver resolver,
593                String dataId, String number) {
594            if (TextUtils.isEmpty(number) || TextUtils.isEmpty(dataId)) {
595                return;
596            }
597
598            final String countryIso = getCurrentCountryIso(context);
599            if (TextUtils.isEmpty(countryIso)) {
600                return;
601            }
602
603            final String normalizedNumber = PhoneNumberUtils.formatNumberToE164(number,
604                    getCurrentCountryIso(context));
605            if (TextUtils.isEmpty(normalizedNumber)) {
606                return;
607            }
608
609            final ContentValues values = new ContentValues();
610            values.put(Phone.NORMALIZED_NUMBER, normalizedNumber);
611            resolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[] {dataId});
612        }
613
614        private static String getCurrentCountryIso(Context context) {
615            String countryIso = null;
616            final CountryDetector detector = (CountryDetector) context.getSystemService(
617                    Context.COUNTRY_DETECTOR);
618            if (detector != null) {
619                final Country country = detector.detectCountry();
620                if (country != null) {
621                    countryIso = country.getCountryIso();
622                }
623            }
624            return countryIso;
625        }
626    }
627}
628