CallerInfoAsyncQuery.java revision fb40dd4d00bd3361b2535bc866e6c21eadc52558
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 17package com.android.internal.telephony; 18 19import android.content.AsyncQueryHandler; 20import android.content.Context; 21import android.database.Cursor; 22import android.database.SQLException; 23import android.net.Uri; 24import android.os.Handler; 25import android.os.Looper; 26import android.os.Message; 27import android.os.SystemProperties; 28import android.provider.ContactsContract.CommonDataKinds.SipAddress; 29import android.provider.ContactsContract.Data; 30import android.provider.ContactsContract.PhoneLookup; 31import android.telephony.PhoneNumberUtils; 32import android.text.TextUtils; 33import android.telephony.Rlog; 34import android.telephony.SubscriptionManager; 35import android.telephony.TelephonyManager; 36 37/** 38 * Helper class to make it easier to run asynchronous caller-id lookup queries. 39 * @see CallerInfo 40 * 41 * {@hide} 42 */ 43public class CallerInfoAsyncQuery { 44 private static final boolean DBG = false; 45 private static final String LOG_TAG = "CallerInfoAsyncQuery"; 46 47 private static final int EVENT_NEW_QUERY = 1; 48 private static final int EVENT_ADD_LISTENER = 2; 49 private static final int EVENT_END_OF_QUEUE = 3; 50 private static final int EVENT_EMERGENCY_NUMBER = 4; 51 private static final int EVENT_VOICEMAIL_NUMBER = 5; 52 53 private CallerInfoAsyncQueryHandler mHandler; 54 55 // If the CallerInfo query finds no contacts, should we use the 56 // PhoneNumberOfflineGeocoder to look up a "geo description"? 57 // (TODO: This could become a flag in config.xml if it ever needs to be 58 // configured on a per-product basis.) 59 private static final boolean ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION = true; 60 61 /** 62 * Interface for a CallerInfoAsyncQueryHandler result return. 63 */ 64 public interface OnQueryCompleteListener { 65 /** 66 * Called when the query is complete. 67 */ 68 public void onQueryComplete(int token, Object cookie, CallerInfo ci); 69 } 70 71 72 /** 73 * Wrap the cookie from the WorkerArgs with additional information needed by our 74 * classes. 75 */ 76 private static final class CookieWrapper { 77 public OnQueryCompleteListener listener; 78 public Object cookie; 79 public int event; 80 public String number; 81 82 public long subId; 83 } 84 85 86 /** 87 * Simple exception used to communicate problems with the query pool. 88 */ 89 public static class QueryPoolException extends SQLException { 90 public QueryPoolException(String error) { 91 super(error); 92 } 93 } 94 95 /** 96 * Our own implementation of the AsyncQueryHandler. 97 */ 98 private class CallerInfoAsyncQueryHandler extends AsyncQueryHandler { 99 100 /** 101 * The information relevant to each CallerInfo query. Each query may have multiple 102 * listeners, so each AsyncCursorInfo is associated with 2 or more CookieWrapper 103 * objects in the queue (one with a new query event, and one with a end event, with 104 * 0 or more additional listeners in between). 105 */ 106 private Context mQueryContext; 107 private Uri mQueryUri; 108 private CallerInfo mCallerInfo; 109 110 /** 111 * Our own query worker thread. 112 * 113 * This thread handles the messages enqueued in the looper. The normal sequence 114 * of events is that a new query shows up in the looper queue, followed by 0 or 115 * more add listener requests, and then an end request. Of course, these requests 116 * can be interlaced with requests from other tokens, but is irrelevant to this 117 * handler since the handler has no state. 118 * 119 * Note that we depend on the queue to keep things in order; in other words, the 120 * looper queue must be FIFO with respect to input from the synchronous startQuery 121 * calls and output to this handleMessage call. 122 * 123 * This use of the queue is required because CallerInfo objects may be accessed 124 * multiple times before the query is complete. All accesses (listeners) must be 125 * queued up and informed in order when the query is complete. 126 */ 127 protected class CallerInfoWorkerHandler extends WorkerHandler { 128 public CallerInfoWorkerHandler(Looper looper) { 129 super(looper); 130 } 131 132 @Override 133 public void handleMessage(Message msg) { 134 WorkerArgs args = (WorkerArgs) msg.obj; 135 CookieWrapper cw = (CookieWrapper) args.cookie; 136 137 if (cw == null) { 138 // Normally, this should never be the case for calls originating 139 // from within this code. 140 // However, if there is any code that this Handler calls (such as in 141 // super.handleMessage) that DOES place unexpected messages on the 142 // queue, then we need pass these messages on. 143 if (DBG) Rlog.d(LOG_TAG, "Unexpected command (CookieWrapper is null): " + msg.what + 144 " ignored by CallerInfoWorkerHandler, passing onto parent."); 145 146 super.handleMessage(msg); 147 } else { 148 149 if (DBG) Rlog.d(LOG_TAG, "Processing event: " + cw.event + " token (arg1): " + msg.arg1 + 150 " command: " + msg.what + " query URI: " + sanitizeUriToString(args.uri)); 151 152 switch (cw.event) { 153 case EVENT_NEW_QUERY: 154 //start the sql command. 155 super.handleMessage(msg); 156 break; 157 158 // shortcuts to avoid query for recognized numbers. 159 case EVENT_EMERGENCY_NUMBER: 160 case EVENT_VOICEMAIL_NUMBER: 161 162 case EVENT_ADD_LISTENER: 163 case EVENT_END_OF_QUEUE: 164 // query was already completed, so just send the reply. 165 // passing the original token value back to the caller 166 // on top of the event values in arg1. 167 Message reply = args.handler.obtainMessage(msg.what); 168 reply.obj = args; 169 reply.arg1 = msg.arg1; 170 171 reply.sendToTarget(); 172 173 break; 174 default: 175 } 176 } 177 } 178 } 179 180 181 /** 182 * Asynchronous query handler class for the contact / callerinfo object. 183 */ 184 private CallerInfoAsyncQueryHandler(Context context) { 185 super(context.getContentResolver()); 186 } 187 188 @Override 189 protected Handler createHandler(Looper looper) { 190 return new CallerInfoWorkerHandler(looper); 191 } 192 193 /** 194 * Overrides onQueryComplete from AsyncQueryHandler. 195 * 196 * This method takes into account the state of this class; we construct the CallerInfo 197 * object only once for each set of listeners. When the query thread has done its work 198 * and calls this method, we inform the remaining listeners in the queue, until we're 199 * out of listeners. Once we get the message indicating that we should expect no new 200 * listeners for this CallerInfo object, we release the AsyncCursorInfo back into the 201 * pool. 202 */ 203 @Override 204 protected void onQueryComplete(int token, Object cookie, Cursor cursor) { 205 if (DBG) Rlog.d(LOG_TAG, "##### onQueryComplete() ##### query complete for token: " + token); 206 207 //get the cookie and notify the listener. 208 CookieWrapper cw = (CookieWrapper) cookie; 209 if (cw == null) { 210 // Normally, this should never be the case for calls originating 211 // from within this code. 212 // However, if there is any code that calls this method, we should 213 // check the parameters to make sure they're viable. 214 if (DBG) Rlog.d(LOG_TAG, "Cookie is null, ignoring onQueryComplete() request."); 215 if (cursor != null) { 216 cursor.close(); 217 } 218 return; 219 } 220 221 if (cw.event == EVENT_END_OF_QUEUE) { 222 release(); 223 if (cursor != null) { 224 cursor.close(); 225 } 226 return; 227 } 228 229 // check the token and if needed, create the callerinfo object. 230 if (mCallerInfo == null) { 231 if ((mQueryContext == null) || (mQueryUri == null)) { 232 throw new QueryPoolException 233 ("Bad context or query uri, or CallerInfoAsyncQuery already released."); 234 } 235 236 // adjust the callerInfo data as needed, and only if it was set from the 237 // initial query request. 238 // Change the callerInfo number ONLY if it is an emergency number or the 239 // voicemail number, and adjust other data (including photoResource) 240 // accordingly. 241 if (cw.event == EVENT_EMERGENCY_NUMBER) { 242 // Note we're setting the phone number here (refer to javadoc 243 // comments at the top of CallerInfo class). 244 mCallerInfo = new CallerInfo().markAsEmergency(mQueryContext); 245 } else if (cw.event == EVENT_VOICEMAIL_NUMBER) { 246 mCallerInfo = new CallerInfo().markAsVoiceMail(cw.subId); 247 } else { 248 mCallerInfo = CallerInfo.getCallerInfo(mQueryContext, mQueryUri, cursor); 249 if (DBG) Rlog.d(LOG_TAG, "==> Got mCallerInfo: " + mCallerInfo); 250 251 CallerInfo newCallerInfo = CallerInfo.doSecondaryLookupIfNecessary( 252 mQueryContext, cw.number, mCallerInfo); 253 if (newCallerInfo != mCallerInfo) { 254 mCallerInfo = newCallerInfo; 255 if (DBG) Rlog.d(LOG_TAG, "#####async contact look up with numeric username" 256 + mCallerInfo); 257 } 258 259 // Final step: look up the geocoded description. 260 if (ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION) { 261 // Note we do this only if we *don't* have a valid name (i.e. if 262 // no contacts matched the phone number of the incoming call), 263 // since that's the only case where the incoming-call UI cares 264 // about this field. 265 // 266 // (TODO: But if we ever want the UI to show the geoDescription 267 // even when we *do* match a contact, we'll need to either call 268 // updateGeoDescription() unconditionally here, or possibly add a 269 // new parameter to CallerInfoAsyncQuery.startQuery() to force 270 // the geoDescription field to be populated.) 271 272 if (TextUtils.isEmpty(mCallerInfo.name)) { 273 // Actually when no contacts match the incoming phone number, 274 // the CallerInfo object is totally blank here (i.e. no name 275 // *or* phoneNumber). So we need to pass in cw.number as 276 // a fallback number. 277 mCallerInfo.updateGeoDescription(mQueryContext, cw.number); 278 } 279 } 280 281 // Use the number entered by the user for display. 282 if (!TextUtils.isEmpty(cw.number)) { 283 mCallerInfo.phoneNumber = PhoneNumberUtils.formatNumber(cw.number, 284 mCallerInfo.normalizedNumber, 285 CallerInfo.getCurrentCountryIso(mQueryContext)); 286 } 287 } 288 289 if (DBG) Rlog.d(LOG_TAG, "constructing CallerInfo object for token: " + token); 290 291 //notify that we can clean up the queue after this. 292 CookieWrapper endMarker = new CookieWrapper(); 293 endMarker.event = EVENT_END_OF_QUEUE; 294 startQuery(token, endMarker, null, null, null, null, null); 295 } 296 297 //notify the listener that the query is complete. 298 if (cw.listener != null) { 299 if (DBG) Rlog.d(LOG_TAG, "notifying listener: " + cw.listener.getClass().toString() + 300 " for token: " + token + mCallerInfo); 301 cw.listener.onQueryComplete(token, cw.cookie, mCallerInfo); 302 } 303 304 if (cursor != null) { 305 cursor.close(); 306 } 307 } 308 } 309 310 /** 311 * Private constructor for factory methods. 312 */ 313 private CallerInfoAsyncQuery() { 314 } 315 316 317 /** 318 * Factory method to start query with a Uri query spec 319 */ 320 public static CallerInfoAsyncQuery startQuery(int token, Context context, Uri contactRef, 321 OnQueryCompleteListener listener, Object cookie) { 322 323 CallerInfoAsyncQuery c = new CallerInfoAsyncQuery(); 324 c.allocate(context, contactRef); 325 326 if (DBG) Rlog.d(LOG_TAG, "starting query for URI: " + contactRef + " handler: " + c.toString()); 327 328 //create cookieWrapper, start query 329 CookieWrapper cw = new CookieWrapper(); 330 cw.listener = listener; 331 cw.cookie = cookie; 332 cw.event = EVENT_NEW_QUERY; 333 334 c.mHandler.startQuery(token, cw, contactRef, null, null, null, null); 335 336 return c; 337 } 338 339 /** 340 * Factory method to start the query based on a number. 341 * 342 * Note: if the number contains an "@" character we treat it 343 * as a SIP address, and look it up directly in the Data table 344 * rather than using the PhoneLookup table. 345 * TODO: But eventually we should expose two separate methods, one for 346 * numbers and one for SIP addresses, and then have 347 * PhoneUtils.startGetCallerInfo() decide which one to call based on 348 * the phone type of the incoming connection. 349 */ 350 public static CallerInfoAsyncQuery startQuery(int token, Context context, String number, 351 OnQueryCompleteListener listener, Object cookie) { 352 353 long subId = SubscriptionManager.getDefaultSubId(); 354 return startQuery(token, context, number, listener, cookie, subId); 355 } 356 357 /** 358 * Factory method to start the query based on a number with specific subscription. 359 * 360 * Note: if the number contains an "@" character we treat it 361 * as a SIP address, and look it up directly in the Data table 362 * rather than using the PhoneLookup table. 363 * TODO: But eventually we should expose two separate methods, one for 364 * numbers and one for SIP addresses, and then have 365 * PhoneUtils.startGetCallerInfo() decide which one to call based on 366 * the phone type of the incoming connection. 367 */ 368 public static CallerInfoAsyncQuery startQuery(int token, Context context, String number, 369 OnQueryCompleteListener listener, Object cookie, long subId) { 370 371 if (DBG) { 372 Rlog.d(LOG_TAG, "##### CallerInfoAsyncQuery startQuery()... #####"); 373 Rlog.d(LOG_TAG, "- number: " + /*number*/ "xxxxxxx"); 374 Rlog.d(LOG_TAG, "- cookie: " + cookie); 375 } 376 377 // Construct the URI object and query params, and start the query. 378 379 Uri contactRef; 380 String selection; 381 String[] selectionArgs; 382 383 if (PhoneNumberUtils.isUriNumber(number)) { 384 // "number" is really a SIP address. 385 if (DBG) Rlog.d(LOG_TAG, " - Treating number as a SIP address: " + /*number*/ "xxxxxxx"); 386 387 // We look up SIP addresses directly in the Data table: 388 contactRef = Data.CONTENT_URI; 389 390 // Note Data.DATA1 and SipAddress.SIP_ADDRESS are equivalent. 391 // 392 // Also note we use "upper(data1)" in the WHERE clause, and 393 // uppercase the incoming SIP address, in order to do a 394 // case-insensitive match. 395 // 396 // TODO: need to confirm that the use of upper() doesn't 397 // prevent us from using the index! (Linear scan of the whole 398 // contacts DB can be very slow.) 399 // 400 // TODO: May also need to normalize by adding "sip:" as a 401 // prefix, if we start storing SIP addresses that way in the 402 // database. 403 404 selection = "upper(" + Data.DATA1 + ")=?" 405 + " AND " 406 + Data.MIMETYPE + "='" + SipAddress.CONTENT_ITEM_TYPE + "'"; 407 selectionArgs = new String[] { number.toUpperCase() }; 408 409 } else { 410 // "number" is a regular phone number. Use the PhoneLookup table: 411 contactRef = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); 412 selection = null; 413 selectionArgs = null; 414 } 415 416 if (DBG) { 417 Rlog.d(LOG_TAG, "==> contactRef: " + sanitizeUriToString(contactRef)); 418 Rlog.d(LOG_TAG, "==> selection: " + selection); 419 if (selectionArgs != null) { 420 for (int i = 0; i < selectionArgs.length; i++) { 421 Rlog.d(LOG_TAG, "==> selectionArgs[" + i + "]: " + selectionArgs[i]); 422 } 423 } 424 } 425 426 CallerInfoAsyncQuery c = new CallerInfoAsyncQuery(); 427 c.allocate(context, contactRef); 428 429 //create cookieWrapper, start query 430 CookieWrapper cw = new CookieWrapper(); 431 cw.listener = listener; 432 cw.cookie = cookie; 433 cw.number = number; 434 cw.subId = subId; 435 436 // check to see if these are recognized numbers, and use shortcuts if we can. 437 if (PhoneNumberUtils.isLocalEmergencyNumber(context, number)) { 438 cw.event = EVENT_EMERGENCY_NUMBER; 439 } else if (PhoneNumberUtils.isVoiceMailNumber(subId, number)) { 440 cw.event = EVENT_VOICEMAIL_NUMBER; 441 } else { 442 cw.event = EVENT_NEW_QUERY; 443 } 444 445 c.mHandler.startQuery(token, 446 cw, // cookie 447 contactRef, // uri 448 null, // projection 449 selection, // selection 450 selectionArgs, // selectionArgs 451 null); // orderBy 452 return c; 453 } 454 455 /** 456 * Method to add listeners to a currently running query 457 */ 458 public void addQueryListener(int token, OnQueryCompleteListener listener, Object cookie) { 459 460 if (DBG) Rlog.d(LOG_TAG, "adding listener to query: " + sanitizeUriToString(mHandler.mQueryUri) + 461 " handler: " + mHandler.toString()); 462 463 //create cookieWrapper, add query request to end of queue. 464 CookieWrapper cw = new CookieWrapper(); 465 cw.listener = listener; 466 cw.cookie = cookie; 467 cw.event = EVENT_ADD_LISTENER; 468 469 mHandler.startQuery(token, cw, null, null, null, null, null); 470 } 471 472 /** 473 * Method to create a new CallerInfoAsyncQueryHandler object, ensuring correct 474 * state of context and uri. 475 */ 476 private void allocate(Context context, Uri contactRef) { 477 if ((context == null) || (contactRef == null)){ 478 throw new QueryPoolException("Bad context or query uri."); 479 } 480 mHandler = new CallerInfoAsyncQueryHandler(context); 481 mHandler.mQueryContext = context; 482 mHandler.mQueryUri = contactRef; 483 } 484 485 /** 486 * Releases the relevant data. 487 */ 488 private void release() { 489 mHandler.mQueryContext = null; 490 mHandler.mQueryUri = null; 491 mHandler.mCallerInfo = null; 492 mHandler = null; 493 } 494 495 private static String sanitizeUriToString(Uri uri) { 496 if (uri != null) { 497 String uriString = uri.toString(); 498 int indexOfLastSlash = uriString.lastIndexOf('/'); 499 if (indexOfLastSlash > 0) { 500 return uriString.substring(0, indexOfLastSlash) + "/xxxxxxx"; 501 } else { 502 return uriString; 503 } 504 } else { 505 return ""; 506 } 507 } 508} 509