blob: 0ac252acfe16586d41f5954f0a3b3aa2994e85cf [file] [log] [blame]
Eric Erfanianccca3152017-02-22 16:32:36 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.incallui;
18
19import android.Manifest;
20import android.annotation.TargetApi;
21import android.content.AsyncQueryHandler;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.database.Cursor;
25import android.database.SQLException;
26import android.net.Uri;
Eric Erfanianccca3152017-02-22 16:32:36 -080027import android.os.Build.VERSION_CODES;
28import android.os.Handler;
29import android.os.Looper;
30import android.os.Message;
wangqi9982f0d2017-10-11 17:46:07 -070031import android.os.Trace;
Eric Erfanianccca3152017-02-22 16:32:36 -080032import android.provider.ContactsContract;
33import android.provider.ContactsContract.Directory;
34import android.support.annotation.MainThread;
35import android.support.annotation.RequiresPermission;
36import android.support.annotation.WorkerThread;
Eric Erfanianccca3152017-02-22 16:32:36 -080037import android.text.TextUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080038import com.android.dialer.phonenumbercache.CachedNumberLookupService;
39import com.android.dialer.phonenumbercache.CachedNumberLookupService.CachedContactInfo;
40import com.android.dialer.phonenumbercache.ContactInfoHelper;
41import com.android.dialer.phonenumbercache.PhoneNumberCache;
linyuha8d677f2018-03-07 17:16:08 -080042import com.android.dialer.phonenumberutil.PhoneNumberHelper;
wangqie37d60c2017-09-27 10:13:49 -070043import com.android.dialer.strictmode.StrictModeUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080044import java.io.IOException;
45import java.io.InputStream;
46import java.util.ArrayList;
47import java.util.Arrays;
48
49/**
50 * Helper class to make it easier to run asynchronous caller-id lookup queries.
51 *
52 * @see CallerInfo
53 */
calderwoodra57fdc2b2018-03-22 01:06:19 -070054@TargetApi(VERSION_CODES.N)
Eric Erfanianccca3152017-02-22 16:32:36 -080055public class CallerInfoAsyncQuery {
56
57 /** Interface for a CallerInfoAsyncQueryHandler result return. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -070058 interface OnQueryCompleteListener {
Eric Erfanianccca3152017-02-22 16:32:36 -080059
60 /** Called when the query is complete. */
61 @MainThread
62 void onQueryComplete(int token, Object cookie, CallerInfo ci);
63
64 /** Called when data is loaded. Must be called in worker thread. */
65 @WorkerThread
66 void onDataLoaded(int token, Object cookie, CallerInfo ci);
67 }
68
69 private static final boolean DBG = false;
70 private static final String LOG_TAG = "CallerInfoAsyncQuery";
71
72 private static final int EVENT_NEW_QUERY = 1;
73 private static final int EVENT_ADD_LISTENER = 2;
74 private static final int EVENT_EMERGENCY_NUMBER = 3;
75 private static final int EVENT_VOICEMAIL_NUMBER = 4;
76 // If the CallerInfo query finds no contacts, should we use the
77 // PhoneNumberOfflineGeocoder to look up a "geo description"?
78 // (TODO: This could become a flag in config.xml if it ever needs to be
79 // configured on a per-product basis.)
80 private static final boolean ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION = true;
81 /* Directory lookup related code - START */
82 private static final String[] DIRECTORY_PROJECTION = new String[] {Directory._ID};
83
84 /** Private constructor for factory methods. */
85 private CallerInfoAsyncQuery() {}
86
87 @RequiresPermission(Manifest.permission.READ_CONTACTS)
Eric Erfaniand5e47f62017-03-15 14:41:07 -070088 static void startQuery(
Eric Erfanianccca3152017-02-22 16:32:36 -080089 final int token,
90 final Context context,
91 final CallerInfo info,
92 final OnQueryCompleteListener listener,
93 final Object cookie) {
94 Log.d(LOG_TAG, "##### CallerInfoAsyncQuery startContactProviderQuery()... #####");
95 Log.d(LOG_TAG, "- number: " + info.phoneNumber);
96 Log.d(LOG_TAG, "- cookie: " + cookie);
97
98 OnQueryCompleteListener contactsProviderQueryCompleteListener =
99 new OnQueryCompleteListener() {
100 @Override
101 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700102 Log.d(LOG_TAG, "contactsProviderQueryCompleteListener onQueryComplete");
Eric Erfanianccca3152017-02-22 16:32:36 -0800103 // If there are no other directory queries, make sure that the listener is
Eric Erfanian938468d2017-10-24 14:05:52 -0700104 // notified of this result. see a bug
Eric Erfanianccca3152017-02-22 16:32:36 -0800105 if ((ci != null && ci.contactExists)
106 || !startOtherDirectoriesQuery(token, context, info, listener, cookie)) {
107 if (listener != null && ci != null) {
108 listener.onQueryComplete(token, cookie, ci);
109 }
110 }
111 }
112
113 @Override
114 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700115 Log.d(LOG_TAG, "contactsProviderQueryCompleteListener onDataLoaded");
Eric Erfanianccca3152017-02-22 16:32:36 -0800116 listener.onDataLoaded(token, cookie, ci);
117 }
118 };
119 startDefaultDirectoryQuery(token, context, info, contactsProviderQueryCompleteListener, cookie);
120 }
121
122 // Private methods
123 private static void startDefaultDirectoryQuery(
124 int token,
125 Context context,
126 CallerInfo info,
127 OnQueryCompleteListener listener,
128 Object cookie) {
129 // Construct the URI object and query params, and start the query.
130 Uri uri = ContactInfoHelper.getContactInfoLookupUri(info.phoneNumber);
131 startQueryInternal(token, context, info, listener, cookie, uri);
132 }
133
134 /**
135 * Factory method to start the query based on a CallerInfo object.
136 *
137 * <p>Note: if the number contains an "@" character we treat it as a SIP address, and look it up
138 * directly in the Data table rather than using the PhoneLookup table. TODO: But eventually we
139 * should expose two separate methods, one for numbers and one for SIP addresses, and then have
140 * PhoneUtils.startGetCallerInfo() decide which one to call based on the phone type of the
141 * incoming connection.
142 */
143 private static void startQueryInternal(
144 int token,
145 Context context,
146 CallerInfo info,
147 OnQueryCompleteListener listener,
148 Object cookie,
149 Uri contactRef) {
150 if (DBG) {
151 Log.d(LOG_TAG, "==> contactRef: " + sanitizeUriToString(contactRef));
152 }
153
154 if ((context == null) || (contactRef == null)) {
155 throw new QueryPoolException("Bad context or query uri.");
156 }
157 CallerInfoAsyncQueryHandler handler = new CallerInfoAsyncQueryHandler(context, contactRef);
158
159 //create cookieWrapper, start query
160 CookieWrapper cw = new CookieWrapper();
161 cw.listener = listener;
162 cw.cookie = cookie;
163 cw.number = info.phoneNumber;
wangqi1420a222017-09-21 09:37:40 -0700164 cw.countryIso = info.countryIso;
Eric Erfanianccca3152017-02-22 16:32:36 -0800165
166 // check to see if these are recognized numbers, and use shortcuts if we can.
linyuha8d677f2018-03-07 17:16:08 -0800167 if (PhoneNumberHelper.isLocalEmergencyNumber(context, info.phoneNumber)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800168 cw.event = EVENT_EMERGENCY_NUMBER;
169 } else if (info.isVoiceMailNumber()) {
170 cw.event = EVENT_VOICEMAIL_NUMBER;
171 } else {
172 cw.event = EVENT_NEW_QUERY;
173 }
174
linyuh437ae952018-03-26 12:46:18 -0700175 String[] proejection = CallerInfo.getDefaultPhoneLookupProjection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800176 handler.startQuery(
177 token,
178 cw, // cookie
179 contactRef, // uri
180 proejection, // projection
181 null, // selection
182 null, // selectionArgs
183 null); // orderBy
184 }
185
186 // Return value indicates if listener was notified.
187 private static boolean startOtherDirectoriesQuery(
188 int token,
189 Context context,
190 CallerInfo info,
191 OnQueryCompleteListener listener,
192 Object cookie) {
wangqi9982f0d2017-10-11 17:46:07 -0700193 Trace.beginSection("CallerInfoAsyncQuery.startOtherDirectoriesQuery");
wangqie37d60c2017-09-27 10:13:49 -0700194 long[] directoryIds = StrictModeUtils.bypass(() -> getDirectoryIds(context));
Eric Erfanianccca3152017-02-22 16:32:36 -0800195 int size = directoryIds.length;
196 if (size == 0) {
wangqi9982f0d2017-10-11 17:46:07 -0700197 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800198 return false;
199 }
200
201 DirectoryQueryCompleteListenerFactory listenerFactory =
202 new DirectoryQueryCompleteListenerFactory(context, size, listener);
203
204 // The current implementation of multiple async query runs in single handler thread
205 // in AsyncQueryHandler.
206 // intermediateListener.onQueryComplete is also called from the same caller thread.
Eric Erfanian938468d2017-10-24 14:05:52 -0700207 // TODO(a bug): use thread pool instead of single thread.
Eric Erfanianccca3152017-02-22 16:32:36 -0800208 for (int i = 0; i < size; i++) {
209 long directoryId = directoryIds[i];
210 Uri uri = ContactInfoHelper.getContactInfoLookupUri(info.phoneNumber, directoryId);
211 if (DBG) {
212 Log.d(LOG_TAG, "directoryId: " + directoryId + " uri: " + uri);
213 }
214 OnQueryCompleteListener intermediateListener = listenerFactory.newListener(directoryId);
215 startQueryInternal(token, context, info, intermediateListener, cookie, uri);
216 }
wangqi9982f0d2017-10-11 17:46:07 -0700217 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800218 return true;
219 }
220
221 private static long[] getDirectoryIds(Context context) {
222 ArrayList<Long> results = new ArrayList<>();
223
linyuh437ae952018-03-26 12:46:18 -0700224 Uri uri = Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "directories_enterprise");
Eric Erfanianccca3152017-02-22 16:32:36 -0800225
226 ContentResolver cr = context.getContentResolver();
227 Cursor cursor = cr.query(uri, DIRECTORY_PROJECTION, null, null, null);
228 addDirectoryIdsFromCursor(cursor, results);
229
230 long[] result = new long[results.size()];
231 for (int i = 0; i < results.size(); i++) {
232 result[i] = results.get(i);
233 }
234 return result;
235 }
236
237 private static void addDirectoryIdsFromCursor(Cursor cursor, ArrayList<Long> results) {
238 if (cursor != null) {
239 int idIndex = cursor.getColumnIndex(Directory._ID);
240 while (cursor.moveToNext()) {
241 long id = cursor.getLong(idIndex);
linyuh437ae952018-03-26 12:46:18 -0700242 if (Directory.isRemoteDirectoryId(id)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800243 results.add(id);
244 }
245 }
246 cursor.close();
247 }
248 }
249
250 private static String sanitizeUriToString(Uri uri) {
251 if (uri != null) {
252 String uriString = uri.toString();
253 int indexOfLastSlash = uriString.lastIndexOf('/');
254 if (indexOfLastSlash > 0) {
255 return uriString.substring(0, indexOfLastSlash) + "/xxxxxxx";
256 } else {
257 return uriString;
258 }
259 } else {
260 return "";
261 }
262 }
263
264 /** Wrap the cookie from the WorkerArgs with additional information needed by our classes. */
265 private static final class CookieWrapper {
266
267 public OnQueryCompleteListener listener;
268 public Object cookie;
269 public int event;
270 public String number;
wangqi1420a222017-09-21 09:37:40 -0700271 public String countryIso;
Eric Erfanianccca3152017-02-22 16:32:36 -0800272 }
273 /* Directory lookup related code - END */
274
275 /** Simple exception used to communicate problems with the query pool. */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700276 private static class QueryPoolException extends SQLException {
Eric Erfanianccca3152017-02-22 16:32:36 -0800277
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700278 QueryPoolException(String error) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800279 super(error);
280 }
281 }
282
283 private static final class DirectoryQueryCompleteListenerFactory {
284
linyuh183cb712017-12-27 17:02:37 -0800285 private final OnQueryCompleteListener listener;
286 private final Context context;
Eric Erfanianccca3152017-02-22 16:32:36 -0800287 // Make sure listener to be called once and only once
linyuh183cb712017-12-27 17:02:37 -0800288 private int count;
289 private boolean isListenerCalled;
Eric Erfanianccca3152017-02-22 16:32:36 -0800290
291 DirectoryQueryCompleteListenerFactory(
292 Context context, int size, OnQueryCompleteListener listener) {
linyuh183cb712017-12-27 17:02:37 -0800293 count = size;
294 this.listener = listener;
295 isListenerCalled = false;
296 this.context = context;
Eric Erfanianccca3152017-02-22 16:32:36 -0800297 }
298
299 private void onDirectoryQueryComplete(
300 int token, Object cookie, CallerInfo ci, long directoryId) {
301 boolean shouldCallListener = false;
302 synchronized (this) {
linyuh183cb712017-12-27 17:02:37 -0800303 count = count - 1;
304 if (!isListenerCalled && (ci.contactExists || count == 0)) {
305 isListenerCalled = true;
Eric Erfanianccca3152017-02-22 16:32:36 -0800306 shouldCallListener = true;
307 }
308 }
309
310 // Don't call callback in synchronized block because mListener.onQueryComplete may
311 // take long time to complete
linyuh183cb712017-12-27 17:02:37 -0800312 if (shouldCallListener && listener != null) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800313 addCallerInfoIntoCache(ci, directoryId);
linyuh183cb712017-12-27 17:02:37 -0800314 listener.onQueryComplete(token, cookie, ci);
Eric Erfanianccca3152017-02-22 16:32:36 -0800315 }
316 }
317
318 private void addCallerInfoIntoCache(CallerInfo ci, long directoryId) {
319 CachedNumberLookupService cachedNumberLookupService =
linyuh183cb712017-12-27 17:02:37 -0800320 PhoneNumberCache.get(context).getCachedNumberLookupService();
Eric Erfanianccca3152017-02-22 16:32:36 -0800321 if (ci.contactExists && cachedNumberLookupService != null) {
322 // 1. Cache caller info
323 CachedContactInfo cachedContactInfo =
324 CallerInfoUtils.buildCachedContactInfo(cachedNumberLookupService, ci);
linyuh183cb712017-12-27 17:02:37 -0800325 String directoryLabel = context.getString(R.string.directory_search_label);
Eric Erfanianccca3152017-02-22 16:32:36 -0800326 cachedContactInfo.setDirectorySource(directoryLabel, directoryId);
linyuh183cb712017-12-27 17:02:37 -0800327 cachedNumberLookupService.addContact(context, cachedContactInfo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800328
329 // 2. Cache photo
330 if (ci.contactDisplayPhotoUri != null && ci.normalizedNumber != null) {
331 try (InputStream in =
linyuh183cb712017-12-27 17:02:37 -0800332 context.getContentResolver().openInputStream(ci.contactDisplayPhotoUri)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800333 if (in != null) {
linyuh183cb712017-12-27 17:02:37 -0800334 cachedNumberLookupService.addPhoto(context, ci.normalizedNumber, in);
Eric Erfanianccca3152017-02-22 16:32:36 -0800335 }
336 } catch (IOException e) {
337 Log.e(LOG_TAG, "failed to fetch directory contact photo", e);
338 }
339 }
340 }
341 }
342
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700343 OnQueryCompleteListener newListener(long directoryId) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800344 return new DirectoryQueryCompleteListener(directoryId);
345 }
346
347 private class DirectoryQueryCompleteListener implements OnQueryCompleteListener {
348
linyuh183cb712017-12-27 17:02:37 -0800349 private final long directoryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800350
351 DirectoryQueryCompleteListener(long directoryId) {
linyuh183cb712017-12-27 17:02:37 -0800352 this.directoryId = directoryId;
Eric Erfanianccca3152017-02-22 16:32:36 -0800353 }
354
355 @Override
356 public void onDataLoaded(int token, Object cookie, CallerInfo ci) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700357 Log.d(LOG_TAG, "DirectoryQueryCompleteListener.onDataLoaded");
linyuh183cb712017-12-27 17:02:37 -0800358 listener.onDataLoaded(token, cookie, ci);
Eric Erfanianccca3152017-02-22 16:32:36 -0800359 }
360
361 @Override
362 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700363 Log.d(LOG_TAG, "DirectoryQueryCompleteListener.onQueryComplete");
linyuh183cb712017-12-27 17:02:37 -0800364 onDirectoryQueryComplete(token, cookie, ci, directoryId);
Eric Erfanianccca3152017-02-22 16:32:36 -0800365 }
366 }
367 }
368
369 /** Our own implementation of the AsyncQueryHandler. */
370 private static class CallerInfoAsyncQueryHandler extends AsyncQueryHandler {
371
372 /**
373 * The information relevant to each CallerInfo query. Each query may have multiple listeners, so
374 * each AsyncCursorInfo is associated with 2 or more CookieWrapper objects in the queue (one
375 * with a new query event, and one with a end event, with 0 or more additional listeners in
376 * between).
377 */
linyuh183cb712017-12-27 17:02:37 -0800378 private Context queryContext;
Eric Erfanianccca3152017-02-22 16:32:36 -0800379
linyuh183cb712017-12-27 17:02:37 -0800380 private Uri queryUri;
381 private CallerInfo callerInfo;
Eric Erfanianccca3152017-02-22 16:32:36 -0800382
383 /** Asynchronous query handler class for the contact / callerinfo object. */
384 private CallerInfoAsyncQueryHandler(Context context, Uri contactRef) {
385 super(context.getContentResolver());
linyuh183cb712017-12-27 17:02:37 -0800386 this.queryContext = context;
387 this.queryUri = contactRef;
Eric Erfanianccca3152017-02-22 16:32:36 -0800388 }
389
390 @Override
391 public void startQuery(
392 int token,
393 Object cookie,
394 Uri uri,
395 String[] projection,
396 String selection,
397 String[] selectionArgs,
398 String orderBy) {
399 if (DBG) {
400 // Show stack trace with the arguments.
401 Log.d(
402 LOG_TAG,
403 "InCall: startQuery: url="
404 + uri
405 + " projection=["
406 + Arrays.toString(projection)
407 + "]"
408 + " selection="
409 + selection
410 + " "
411 + " args=["
412 + Arrays.toString(selectionArgs)
413 + "]",
414 new RuntimeException("STACKTRACE"));
415 }
416 super.startQuery(token, cookie, uri, projection, selection, selectionArgs, orderBy);
417 }
418
419 @Override
420 protected Handler createHandler(Looper looper) {
421 return new CallerInfoWorkerHandler(looper);
422 }
423
424 /**
425 * Overrides onQueryComplete from AsyncQueryHandler.
426 *
427 * <p>This method takes into account the state of this class; we construct the CallerInfo object
428 * only once for each set of listeners. When the query thread has done its work and calls this
429 * method, we inform the remaining listeners in the queue, until we're out of listeners. Once we
430 * get the message indicating that we should expect no new listeners for this CallerInfo object,
431 * we release the AsyncCursorInfo back into the pool.
432 */
433 @Override
434 protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
435 Log.d(this, "##### onQueryComplete() ##### query complete for token: " + token);
436
437 CookieWrapper cw = (CookieWrapper) cookie;
438
439 if (cw.listener != null) {
440 Log.d(
441 this,
442 "notifying listener: "
443 + cw.listener.getClass().toString()
444 + " for token: "
445 + token
linyuh183cb712017-12-27 17:02:37 -0800446 + callerInfo);
447 cw.listener.onQueryComplete(token, cw.cookie, callerInfo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800448 }
linyuh183cb712017-12-27 17:02:37 -0800449 queryContext = null;
450 queryUri = null;
451 callerInfo = null;
Eric Erfanianccca3152017-02-22 16:32:36 -0800452 }
453
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700454 void updateData(int token, Object cookie, Cursor cursor) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800455 try {
456 Log.d(this, "##### updateData() ##### for token: " + token);
457
458 //get the cookie and notify the listener.
459 CookieWrapper cw = (CookieWrapper) cookie;
460 if (cw == null) {
461 // Normally, this should never be the case for calls originating
462 // from within this code.
463 // However, if there is any code that calls this method, we should
464 // check the parameters to make sure they're viable.
465 Log.d(this, "Cookie is null, ignoring onQueryComplete() request.");
466 return;
467 }
468
469 // check the token and if needed, create the callerinfo object.
linyuh183cb712017-12-27 17:02:37 -0800470 if (callerInfo == null) {
471 if ((queryContext == null) || (queryUri == null)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800472 throw new QueryPoolException(
473 "Bad context or query uri, or CallerInfoAsyncQuery already released.");
474 }
475
476 // adjust the callerInfo data as needed, and only if it was set from the
477 // initial query request.
478 // Change the callerInfo number ONLY if it is an emergency number or the
479 // voicemail number, and adjust other data (including photoResource)
480 // accordingly.
481 if (cw.event == EVENT_EMERGENCY_NUMBER) {
482 // Note we're setting the phone number here (refer to javadoc
483 // comments at the top of CallerInfo class).
linyuh183cb712017-12-27 17:02:37 -0800484 callerInfo = new CallerInfo().markAsEmergency(queryContext);
Eric Erfanianccca3152017-02-22 16:32:36 -0800485 } else if (cw.event == EVENT_VOICEMAIL_NUMBER) {
linyuh183cb712017-12-27 17:02:37 -0800486 callerInfo = new CallerInfo().markAsVoiceMail(queryContext);
Eric Erfanianccca3152017-02-22 16:32:36 -0800487 } else {
linyuh183cb712017-12-27 17:02:37 -0800488 callerInfo = CallerInfo.getCallerInfo(queryContext, queryUri, cursor);
489 Log.d(this, "==> Got mCallerInfo: " + callerInfo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800490
491 CallerInfo newCallerInfo =
linyuh183cb712017-12-27 17:02:37 -0800492 CallerInfo.doSecondaryLookupIfNecessary(queryContext, cw.number, callerInfo);
493 if (newCallerInfo != callerInfo) {
494 callerInfo = newCallerInfo;
495 Log.d(this, "#####async contact look up with numeric username" + callerInfo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800496 }
linyuh183cb712017-12-27 17:02:37 -0800497 callerInfo.countryIso = cw.countryIso;
Eric Erfanianccca3152017-02-22 16:32:36 -0800498
499 // Final step: look up the geocoded description.
500 if (ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION) {
501 // Note we do this only if we *don't* have a valid name (i.e. if
502 // no contacts matched the phone number of the incoming call),
503 // since that's the only case where the incoming-call UI cares
504 // about this field.
505 //
506 // (TODO: But if we ever want the UI to show the geoDescription
507 // even when we *do* match a contact, we'll need to either call
508 // updateGeoDescription() unconditionally here, or possibly add a
509 // new parameter to CallerInfoAsyncQuery.startQuery() to force
510 // the geoDescription field to be populated.)
511
linyuh183cb712017-12-27 17:02:37 -0800512 if (TextUtils.isEmpty(callerInfo.name)) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800513 // Actually when no contacts match the incoming phone number,
514 // the CallerInfo object is totally blank here (i.e. no name
515 // *or* phoneNumber). So we need to pass in cw.number as
516 // a fallback number.
linyuh183cb712017-12-27 17:02:37 -0800517 callerInfo.updateGeoDescription(queryContext, cw.number);
Eric Erfanianccca3152017-02-22 16:32:36 -0800518 }
519 }
520
521 // Use the number entered by the user for display.
522 if (!TextUtils.isEmpty(cw.number)) {
linyuh183cb712017-12-27 17:02:37 -0800523 callerInfo.phoneNumber = cw.number;
Eric Erfanianccca3152017-02-22 16:32:36 -0800524 }
525 }
526
527 Log.d(this, "constructing CallerInfo object for token: " + token);
528
529 if (cw.listener != null) {
linyuh183cb712017-12-27 17:02:37 -0800530 cw.listener.onDataLoaded(token, cw.cookie, callerInfo);
Eric Erfanianccca3152017-02-22 16:32:36 -0800531 }
532 }
533
534 } finally {
535 // The cursor may have been closed in CallerInfo.getCallerInfo()
536 if (cursor != null && !cursor.isClosed()) {
537 cursor.close();
538 }
539 }
540 }
541
542 /**
543 * Our own query worker thread.
544 *
545 * <p>This thread handles the messages enqueued in the looper. The normal sequence of events is
546 * that a new query shows up in the looper queue, followed by 0 or more add listener requests,
547 * and then an end request. Of course, these requests can be interlaced with requests from other
548 * tokens, but is irrelevant to this handler since the handler has no state.
549 *
550 * <p>Note that we depend on the queue to keep things in order; in other words, the looper queue
551 * must be FIFO with respect to input from the synchronous startQuery calls and output to this
552 * handleMessage call.
553 *
554 * <p>This use of the queue is required because CallerInfo objects may be accessed multiple
555 * times before the query is complete. All accesses (listeners) must be queued up and informed
556 * in order when the query is complete.
557 */
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700558 class CallerInfoWorkerHandler extends WorkerHandler {
Eric Erfanianccca3152017-02-22 16:32:36 -0800559
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700560 CallerInfoWorkerHandler(Looper looper) {
Eric Erfanianccca3152017-02-22 16:32:36 -0800561 super(looper);
562 }
563
564 @Override
565 public void handleMessage(Message msg) {
566 WorkerArgs args = (WorkerArgs) msg.obj;
567 CookieWrapper cw = (CookieWrapper) args.cookie;
568
569 if (cw == null) {
570 // Normally, this should never be the case for calls originating
571 // from within this code.
572 // However, if there is any code that this Handler calls (such as in
573 // super.handleMessage) that DOES place unexpected messages on the
574 // queue, then we need pass these messages on.
575 Log.d(
576 this,
577 "Unexpected command (CookieWrapper is null): "
578 + msg.what
579 + " ignored by CallerInfoWorkerHandler, passing onto parent.");
580
581 super.handleMessage(msg);
582 } else {
583 Log.d(
584 this,
585 "Processing event: "
586 + cw.event
587 + " token (arg1): "
588 + msg.arg1
589 + " command: "
590 + msg.what
591 + " query URI: "
592 + sanitizeUriToString(args.uri));
593
594 switch (cw.event) {
595 case EVENT_NEW_QUERY:
linyuh183cb712017-12-27 17:02:37 -0800596 final ContentResolver resolver = queryContext.getContentResolver();
Eric Erfanianccca3152017-02-22 16:32:36 -0800597
598 // This should never happen.
599 if (resolver == null) {
600 Log.e(this, "Content Resolver is null!");
601 return;
602 }
linyuh183cb712017-12-27 17:02:37 -0800603 // start the sql command.
Eric Erfanianccca3152017-02-22 16:32:36 -0800604 Cursor cursor;
605 try {
606 cursor =
607 resolver.query(
608 args.uri,
609 args.projection,
610 args.selection,
611 args.selectionArgs,
612 args.orderBy);
613 // Calling getCount() causes the cursor window to be filled,
614 // which will make the first access on the main thread a lot faster.
615 if (cursor != null) {
616 cursor.getCount();
617 }
618 } catch (Exception e) {
619 Log.e(this, "Exception thrown during handling EVENT_ARG_QUERY", e);
620 cursor = null;
621 }
622
623 args.result = cursor;
624 updateData(msg.arg1, cw, cursor);
625 break;
626
627 // shortcuts to avoid query for recognized numbers.
628 case EVENT_EMERGENCY_NUMBER:
629 case EVENT_VOICEMAIL_NUMBER:
630 case EVENT_ADD_LISTENER:
631 updateData(msg.arg1, cw, (Cursor) args.result);
632 break;
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700633 default: // fall out
Eric Erfanianccca3152017-02-22 16:32:36 -0800634 }
635 Message reply = args.handler.obtainMessage(msg.what);
636 reply.obj = args;
637 reply.arg1 = msg.arg1;
638
639 reply.sendToTarget();
640 }
641 }
642 }
643 }
644}