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