PhoneUtils.java revision 7f63f08c5c88d604abba447032ed42f4f972f3ef
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.phone; 18 19import android.app.AlertDialog; 20import android.app.Dialog; 21import android.app.ProgressDialog; 22import android.content.ComponentName; 23import android.content.ContentResolver; 24import android.content.Context; 25import android.content.DialogInterface; 26import android.content.Intent; 27import android.content.ServiceConnection; 28import android.content.pm.ApplicationInfo; 29import android.content.pm.PackageManager; 30import android.graphics.drawable.Drawable; 31import android.media.AudioManager; 32import android.net.Uri; 33import android.os.AsyncResult; 34import android.os.Handler; 35import android.os.IBinder; 36import android.os.Message; 37import android.os.RemoteException; 38import android.os.SystemProperties; 39import android.telephony.PhoneNumberUtils; 40import android.text.TextUtils; 41import android.util.Log; 42import android.view.KeyEvent; 43import android.view.LayoutInflater; 44import android.view.View; 45import android.view.WindowManager; 46import android.widget.EditText; 47import android.widget.Toast; 48 49import com.android.internal.telephony.Call; 50import com.android.internal.telephony.CallStateException; 51import com.android.internal.telephony.CallerInfo; 52import com.android.internal.telephony.CallerInfoAsyncQuery; 53import com.android.internal.telephony.Connection; 54import com.android.internal.telephony.IExtendedNetworkService; 55import com.android.internal.telephony.MmiCode; 56import com.android.internal.telephony.Phone; 57import com.android.internal.telephony.TelephonyProperties; 58import com.android.internal.telephony.cdma.CdmaConnection; 59 60import java.util.Hashtable; 61import java.util.Iterator; 62import java.util.List; 63 64/** 65 * Misc utilities for the Phone app. 66 */ 67public class PhoneUtils { 68 private static final String LOG_TAG = "PhoneUtils"; 69 private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2); 70 71 /** Control stack trace for Audio Mode settings */ 72 private static final boolean DBG_SETAUDIOMODE_STACK = false; 73 74 /** Identifier for the "Add Call" intent extra. */ 75 static final String ADD_CALL_MODE_KEY = "add_call_mode"; 76 77 // Return codes from placeCall() 78 static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed 79 static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code 80 static final int CALL_STATUS_FAILED = 2; // The call failed 81 82 // State of the Phone's audio modes 83 // Each state can move to the other states, but within the state only certain 84 // transitions for AudioManager.setMode() are allowed. 85 static final int AUDIO_IDLE = 0; /** audio behaviour at phone idle */ 86 static final int AUDIO_RINGING = 1; /** audio behaviour while ringing */ 87 static final int AUDIO_OFFHOOK = 2; /** audio behaviour while in call. */ 88 private static int sAudioBehaviourState = AUDIO_IDLE; 89 90 /** Speaker state, persisting between wired headset connection events */ 91 private static boolean sIsSpeakerEnabled = false; 92 93 /** Hash table to store mute (Boolean) values based upon the connection.*/ 94 private static Hashtable<Connection, Boolean> sConnectionMuteTable = 95 new Hashtable<Connection, Boolean>(); 96 97 /** Static handler for the connection/mute tracking */ 98 private static ConnectionHandler mConnectionHandler; 99 100 /** Phone state changed event*/ 101 private static final int PHONE_STATE_CHANGED = -1; 102 103 /** Define for not a special CNAP string */ 104 private static final int CNAP_SPECIAL_CASE_NO = -1; 105 106 // Extended network service interface instance 107 private static IExtendedNetworkService mNwService = null; 108 // used to cancel MMI command after 15 seconds timeout for NWService requirement 109 private static Message mMmiTimeoutCbMsg = null; 110 111 /** Noise suppression status as selected by user */ 112 private static boolean sIsNoiseSuppressionEnabled = true; 113 114 /** 115 * Handler that tracks the connections and updates the value of the 116 * Mute settings for each connection as needed. 117 */ 118 private static class ConnectionHandler extends Handler { 119 @Override 120 public void handleMessage(Message msg) { 121 AsyncResult ar = (AsyncResult) msg.obj; 122 switch (msg.what) { 123 case PHONE_STATE_CHANGED: 124 if (DBG) log("ConnectionHandler: updating mute state for each connection"); 125 126 Phone phone = (Phone) ar.userObj; 127 128 // update the foreground connections, if there are new connections. 129 List<Connection> fgConnections = phone.getForegroundCall().getConnections(); 130 for (Connection cn : fgConnections) { 131 if (sConnectionMuteTable.get(cn) == null) { 132 sConnectionMuteTable.put(cn, Boolean.FALSE); 133 } 134 } 135 136 // update the background connections, if there are new connections. 137 List<Connection> bgConnections = phone.getBackgroundCall().getConnections(); 138 for (Connection cn : bgConnections) { 139 if (sConnectionMuteTable.get(cn) == null) { 140 sConnectionMuteTable.put(cn, Boolean.FALSE); 141 } 142 } 143 144 // Check to see if there are any lingering connections here 145 // (disconnected connections), use old-school iterators to avoid 146 // concurrent modification exceptions. 147 Connection cn; 148 for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator(); 149 cnlist.hasNext();) { 150 cn = cnlist.next(); 151 if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) { 152 if (DBG) log("connection: " + cn + "not accounted for, removing."); 153 cnlist.remove(); 154 } 155 } 156 157 // Restore the mute state of the foreground call if we're not IDLE, 158 // otherwise just clear the mute state. This is really saying that 159 // as long as there is one or more connections, we should update 160 // the mute state with the earliest connection on the foreground 161 // call, and that with no connections, we should be back to a 162 // non-mute state. 163 if (phone.getState() != Phone.State.IDLE) { 164 restoreMuteState(phone); 165 } else { 166 setMuteInternal(phone, false); 167 } 168 169 break; 170 } 171 } 172 } 173 174 175 private static ServiceConnection ExtendedNetworkServiceConnection = new ServiceConnection() { 176 public void onServiceConnected(ComponentName name, IBinder iBinder) { 177 if (DBG) log("Extended NW onServiceConnected"); 178 mNwService = IExtendedNetworkService.Stub.asInterface(iBinder); 179 } 180 181 public void onServiceDisconnected(ComponentName arg0) { 182 if (DBG) log("Extended NW onServiceDisconnected"); 183 mNwService = null; 184 } 185 }; 186 187 /** 188 * Register the ConnectionHandler with the phone, to receive connection events 189 */ 190 public static void initializeConnectionHandler(Phone phone) { 191 if (mConnectionHandler == null) { 192 mConnectionHandler = new ConnectionHandler(); 193 } 194 195 phone.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, phone); 196 // Extended NW service 197 Intent intent = new Intent("com.android.ussd.IExtendedNetworkService"); 198 phone.getContext().bindService(intent, 199 ExtendedNetworkServiceConnection, Context.BIND_AUTO_CREATE); 200 if (DBG) log("Extended NW bindService IExtendedNetworkService"); 201 202 } 203 204 /** This class is never instantiated. */ 205 private PhoneUtils() { 206 } 207 208 //static method to set the audio control state. 209 static void setAudioControlState(int newState) { 210 sAudioBehaviourState = newState; 211 } 212 213 /** 214 * Answer the currently-ringing call. 215 * 216 * @return true if we answered the call, or false if there wasn't 217 * actually a ringing incoming call, or some other error occurred. 218 * 219 * @see answerAndEndHolding() 220 * @see answerAndEndActive() 221 */ 222 static boolean answerCall(Phone phone) { 223 if (DBG) log("answerCall()..."); 224 225 // If the ringer is currently ringing and/or vibrating, stop it 226 // right now (before actually answering the call.) 227 PhoneApp.getInstance().getRinger().stopRing(); 228 229 PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK); 230 231 boolean answered = false; 232 Call call = phone.getRingingCall(); 233 PhoneApp app = PhoneApp.getInstance(); 234 boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA); 235 BluetoothHandsfree bthf = null; 236 237 if (phoneIsCdma) { 238 // Stop any signalInfo tone being played when a Call waiting gets answered 239 if (call.getState() == Call.State.WAITING) { 240 final CallNotifier notifier = app.notifier; 241 notifier.stopSignalInfoTone(); 242 } 243 } 244 245 if (call != null && call.isRinging()) { 246 if (DBG) log("answerCall: call state = " + call.getState()); 247 try { 248 if (phoneIsCdma) { 249 if (app.cdmaPhoneCallState.getCurrentCallState() 250 == CdmaPhoneCallState.PhoneCallState.IDLE) { 251 // This is the FIRST incoming call being answered. 252 // Set the Phone Call State to SINGLE_ACTIVE 253 app.cdmaPhoneCallState.setCurrentCallState( 254 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE); 255 } else { 256 // This is the CALL WAITING call being answered. 257 // Set the Phone Call State to CONF_CALL 258 app.cdmaPhoneCallState.setCurrentCallState( 259 CdmaPhoneCallState.PhoneCallState.CONF_CALL); 260 // Enable "Add Call" option after answering a Call Waiting as the user 261 // should be allowed to add another call in case one of the parties 262 // drops off 263 app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true); 264 265 // If a BluetoothHandsfree is valid we need to set the second call state 266 // so that the Bluetooth client can update the Call state correctly when 267 // a call waiting is answered from the Phone. 268 bthf = app.getBluetoothHandsfree(); 269 if (bthf != null) { 270 bthf.cdmaSetSecondCallState(true); 271 } 272 } 273 } 274 275 //if (DBG) log("sPhone.acceptCall"); 276 phone.acceptCall(); 277 answered = true; 278 if (phoneIsCdma) { 279 // automatically reset mute state to unmuted for CDMA 280 // TODO: Would GSM want this also? 281 setMute(phone, false); 282 } 283 setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL); 284 285 // Check is phone in any dock, and turn on speaker accordingly 286 activateSpeakerIfDocked(phone); 287 } catch (CallStateException ex) { 288 Log.w(LOG_TAG, "answerCall: caught " + ex, ex); 289 290 if (phoneIsCdma) { 291 // restore the cdmaPhoneCallState and bthf.cdmaSetSecondCallState: 292 app.cdmaPhoneCallState.setCurrentCallState( 293 app.cdmaPhoneCallState.getPreviousCallState()); 294 if (bthf != null) { 295 bthf.cdmaSetSecondCallState(false); 296 } 297 } 298 } 299 } 300 return answered; 301 } 302 303 /** 304 * Smart "hang up" helper method which hangs up exactly one connection, 305 * based on the current Phone state, as follows: 306 * <ul> 307 * <li>If there's a ringing call, hang that up. 308 * <li>Else if there's a foreground call, hang that up. 309 * <li>Else if there's a background call, hang that up. 310 * <li>Otherwise do nothing. 311 * </ul> 312 * @return true if we successfully hung up, or false 313 * if there were no active calls at all. 314 */ 315 static boolean hangup(Phone phone) { 316 boolean hungup = false; 317 Call ringing = phone.getRingingCall(); 318 Call fg = phone.getForegroundCall(); 319 Call bg = phone.getBackgroundCall(); 320 321 if (!ringing.isIdle()) { 322 if (DBG) log("HANGUP ringing call"); 323 hungup = hangupRingingCall(phone); 324 } else if (!fg.isIdle()) { 325 if (DBG) log("HANGUP foreground call"); 326 hungup = hangup(fg); 327 } else if (!bg.isIdle()) { 328 if (DBG) log("HANGUP background call"); 329 hungup = hangup(bg); 330 } 331 332 if (DBG) log("hungup=" + hungup); 333 334 return hungup; 335 } 336 337 static boolean hangupRingingCall(Phone phone) { 338 if (DBG) log("hangup ringing call"); 339 Call ringing = phone.getRingingCall(); 340 int phoneType = phone.getPhoneType(); 341 342 if (phoneType == Phone.PHONE_TYPE_CDMA) { 343 // CDMA: Ringing call and Call waiting hangup is handled differently. 344 // For Call waiting we DO NOT call the conventional hangup(call) function 345 // as in CDMA we just want to hungup the Call waiting connection. 346 Call.State state = ringing.getState(); 347 if (state == Call.State.INCOMING) { 348 if (DBG) log("hangup ringing call"); 349 return hangup(ringing); 350 } else if (state == Call.State.WAITING) { 351 if (DBG) log("hangup Call waiting call"); 352 final CallNotifier notifier = PhoneApp.getInstance().notifier; 353 notifier.sendCdmaCallWaitingReject(); 354 return true; 355 } else { 356 // This should never happen cause hangupRingingCall should always be called 357 // if the call.isRinging() returns TRUE, which basically means that the call 358 // should either be in INCOMING or WAITING state 359 if (DBG) log("No Ringing call to hangup"); 360 return false; 361 } 362 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 363 // GSM: Ringing Call and Call waiting, both are hungup by calling 364 // hangup(call) function. 365 if (DBG) log("hangup ringing call"); 366 return hangup(ringing); 367 } else { 368 throw new IllegalStateException("Unexpected phone type: " + phoneType); 369 } 370 } 371 372 static boolean hangupActiveCall(Phone phone) { 373 if (DBG) log("hangup active call"); 374 return hangup(phone.getForegroundCall()); 375 } 376 377 static boolean hangupHoldingCall(Phone phone) { 378 if (DBG) log("hangup holding call"); 379 return hangup(phone.getBackgroundCall()); 380 } 381 382 /** 383 * Used in CDMA phones to end the complete Call session 384 * @param phone the Phone object. 385 * @return true if *any* call was successfully hung up 386 */ 387 static boolean hangupRingingAndActive(Phone phone) { 388 boolean hungUpRingingCall = false; 389 boolean hungUpFgCall = false; 390 Call ringingCall = phone.getRingingCall(); 391 Call fgCall = phone.getForegroundCall(); 392 393 // Hang up any Ringing Call 394 if (!ringingCall.isIdle()) { 395 if (DBG) log("endCallInternal: Hang up Ringing Call"); 396 hungUpRingingCall = hangupRingingCall(phone); 397 } 398 399 // Hang up any Active Call 400 if (!fgCall.isIdle()) { 401 if (DBG) log("endCallInternal: Hang up Foreground Call"); 402 hungUpFgCall = hangupActiveCall(phone); 403 } 404 405 return hungUpRingingCall || hungUpFgCall; 406 } 407 408 /** 409 * Trivial wrapper around Call.hangup(), except that we return a 410 * boolean success code rather than throwing CallStateException on 411 * failure. 412 * 413 * @return true if the call was successfully hung up, or false 414 * if the call wasn't actually active. 415 */ 416 static boolean hangup(Call call) { 417 try { 418 call.hangup(); 419 return true; 420 } catch (CallStateException ex) { 421 Log.e(LOG_TAG, "Call hangup: caught " + ex, ex); 422 } 423 424 return false; 425 } 426 427 /** 428 * Trivial wrapper around Connection.hangup(), except that we silently 429 * do nothing (rather than throwing CallStateException) if the 430 * connection wasn't actually active. 431 */ 432 static void hangup(Connection c) { 433 try { 434 if (c != null) { 435 c.hangup(); 436 } 437 } catch (CallStateException ex) { 438 Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex); 439 } 440 } 441 442 static boolean answerAndEndHolding(Phone phone) { 443 if (DBG) log("end holding & answer waiting: 1"); 444 if (!hangupHoldingCall(phone)) { 445 Log.e(LOG_TAG, "end holding failed!"); 446 return false; 447 } 448 449 if (DBG) log("end holding & answer waiting: 2"); 450 return answerCall(phone); 451 452 } 453 454 static boolean answerAndEndActive(Phone phone) { 455 if (DBG) log("answerAndEndActive()..."); 456 457 // Unlike the answerCall() method, we *don't* need to stop the 458 // ringer or change audio modes here since the user is already 459 // in-call, which means that the audio mode is already set 460 // correctly, and that we wouldn't have started the ringer in the 461 // first place. 462 463 // hanging up the active call also accepts the waiting call 464 return hangupActiveCall(phone); 465 } 466 467 /** 468 * For a CDMA phone, advance the call state upon making a new 469 * outgoing call. 470 * 471 * <pre> 472 * IDLE -> SINGLE_ACTIVE 473 * or 474 * SINGLE_ACTIVE -> THRWAY_ACTIVE 475 * </pre> 476 * @param app The phone instance. 477 */ 478 private static void updateCdmaCallStateOnNewOutgoingCall(PhoneApp app) { 479 if (app.cdmaPhoneCallState.getCurrentCallState() == 480 CdmaPhoneCallState.PhoneCallState.IDLE) { 481 // This is the first outgoing call. Set the Phone Call State to ACTIVE 482 app.cdmaPhoneCallState.setCurrentCallState( 483 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE); 484 } else { 485 // This is the second outgoing call. Set the Phone Call State to 3WAY 486 app.cdmaPhoneCallState.setCurrentCallState( 487 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE); 488 } 489 } 490 491 /** 492 * Dial the number using the phone passed in. 493 * 494 * @param phone the Phone object. 495 * @param number to be dialed as requested by the user. 496 * @param contactRef that triggered the call. Either a 'tel:' or a 497 * 'content://contacts' uri depending on how the call was 498 * initiated (dialpad vs contact). 499 * @return either CALL_STATUS_DIALED, CALL_STATUS_DIALED_MMI, or CALL_STATUS_FAILED 500 */ 501 static int placeCall(Phone phone, String number, Uri contactRef) { 502 int status = CALL_STATUS_DIALED; 503 try { 504 if (DBG) log("placeCall: '" + number + "'..."); 505 506 Connection cn = phone.dial(number); 507 if (DBG) log("===> phone.dial() returned: " + cn); 508 509 int phoneType = phone.getPhoneType(); 510 511 // On GSM phones, null is returned for MMI codes 512 if (cn == null) { 513 if (phoneType == Phone.PHONE_TYPE_GSM) { 514 if (DBG) log("dialed MMI code: " + number); 515 status = CALL_STATUS_DIALED_MMI; 516 // Set dialed MMI command to service 517 if (mNwService != null) { 518 try { 519 mNwService.setMmiString(number); 520 if (DBG) log("Extended NW bindService setUssdString (" + number + ")"); 521 } catch (RemoteException e) { 522 mNwService = null; 523 } 524 } 525 } else { 526 status = PhoneUtils.CALL_STATUS_FAILED; 527 } 528 } else { 529 PhoneApp app = PhoneApp.getInstance(); 530 531 if (phoneType == Phone.PHONE_TYPE_CDMA) { 532 updateCdmaCallStateOnNewOutgoingCall(app); 533 } 534 535 PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK); 536 537 // phone.dial() succeeded: we're now in a normal phone call. 538 // attach the URI to the CallerInfo Object if it is there, 539 // otherwise just attach the Uri Reference. 540 // if the uri does not have a "content" scheme, then we treat 541 // it as if it does NOT have a unique reference. 542 String content = phone.getContext().getContentResolver().SCHEME_CONTENT; 543 if ((contactRef != null) && (contactRef.getScheme().equals(content))) { 544 Object userDataObject = cn.getUserData(); 545 if (userDataObject == null) { 546 cn.setUserData(contactRef); 547 } else { 548 // TODO: This branch is dead code, we have 549 // just created the connection 'cn' which has 550 // no user data (null) by default. 551 if (userDataObject instanceof CallerInfo) { 552 ((CallerInfo) userDataObject).contactRefUri = contactRef; 553 } else { 554 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri = 555 contactRef; 556 } 557 } 558 } 559 setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL); 560 561 // Check is phone in any dock, and turn on speaker accordingly 562 activateSpeakerIfDocked(phone); 563 } 564 } catch (CallStateException ex) { 565 Log.w(LOG_TAG, "Exception from phone.dial()", ex); 566 status = CALL_STATUS_FAILED; 567 } 568 569 return status; 570 } 571 572 /** 573 * Dial the number using a 3rd party provider gateway. Should 574 * *NOT* be called if the number is either: 575 * . An emergency one 576 * . A GSM MMI code 577 * . A CDMA feature code 578 * None of the above is checked in this method, it's the caller's 579 * responsability to make sure the number is 'valid'. 580 * 581 * If the connection is establised, this method issues a sync call 582 * that may block to query the caller info. 583 * TODO: Change the logic to use the async query. 584 * 585 * @param phone the Phone object. 586 * @param context To perform the CallerInfo query. 587 * @param number to be dialed as requested by the user. This is 588 * NOT the phone number to connect to. It is used only to build the 589 * call card and to update the call log. See above for restrictions. 590 * @param contactRef that triggered the call. Typically a 'tel:' 591 * uri but can also be a 'content://contacts' one. 592 * @param gatewayUri Is the address used to setup the connection. 593 * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED 594 */ 595 static int placeCallVia(Context context, Phone phone, 596 String number, Uri contactRef, Uri gatewayUri) { 597 if (DBG) log("placeCallVia: '" + number + "' GW:'" + gatewayUri + "'"); 598 599 // TODO: 'tel' should be a contant defined in framework base 600 // somewhere (it is in webkit.) 601 if (null == gatewayUri || !"tel".equals(gatewayUri.getScheme())) { 602 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri); 603 return CALL_STATUS_FAILED; 604 } 605 606 // We can use getSchemeSpecificPart because we don't allow # 607 // in the gateway numbers (treated a fragment delim.) However 608 // if we allow more complex gateway numbers sequence (with 609 // passwords or whatnot) that use #, this may break. 610 // TODO: Need to support MMI codes. 611 String gatewayNumber = gatewayUri.getSchemeSpecificPart(); 612 Connection connection; 613 try { 614 connection = phone.dial(gatewayNumber); 615 } catch (CallStateException ex) { 616 Log.e(LOG_TAG, "Exception dialing gateway", ex); 617 connection = null; 618 } 619 620 if (null == connection) { 621 Log.e(LOG_TAG, "Got null connection."); 622 return CALL_STATUS_FAILED; 623 } 624 625 PhoneApp app = PhoneApp.getInstance(); 626 boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA); 627 628 if (phoneIsCdma) { 629 updateCdmaCallStateOnNewOutgoingCall(app); 630 } 631 PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK); 632 633 // Clean up the number to be displayed. 634 if (phoneIsCdma) { 635 number = CdmaConnection.formatDialString(number); 636 } 637 number = PhoneNumberUtils.extractNetworkPortion(number); 638 number = PhoneNumberUtils.convertKeypadLettersToDigits(number); 639 number = PhoneNumberUtils.formatNumber(number); 640 641 // Get the caller info synchronously because we need the final 642 // CallerInfo object to update the dialed number with the one 643 // requested by the user (and not the provider's gateway number). 644 CallerInfo info = null; 645 646 if (ContentResolver.SCHEME_CONTENT.equals(contactRef.getScheme())) { 647 info = CallerInfo.getCallerInfo(context, contactRef); 648 } 649 650 // Fallback, lookup contact using the phone number if the 651 // contact's URI scheme was not content:// or if is was but 652 // the lookup failed. 653 if (null == info) { 654 info = CallerInfo.getCallerInfo(context, number); 655 } 656 info.phoneNumber = number; 657 connection.setUserData(info); 658 659 setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL); 660 return CALL_STATUS_DIALED; 661 } 662 663 /** 664 * Wrapper function to control when to send an empty Flash command to the network. 665 * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash 666 * to the network prior to placing a 3-way call for it to be successful. 667 */ 668 static void sendEmptyFlash(Phone phone) { 669 if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { 670 Call fgCall = phone.getForegroundCall(); 671 if (fgCall.getState() == Call.State.ACTIVE) { 672 // Send the empty flash 673 if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network"); 674 switchHoldingAndActive(phone); 675 } 676 } 677 } 678 679 static void switchHoldingAndActive(Phone phone) { 680 try { 681 if (DBG) log("switchHoldingAndActive"); 682 phone.switchHoldingAndActive(); 683 } catch (CallStateException ex) { 684 Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex); 685 } 686 } 687 688 /** 689 * Restore the mute setting from the earliest connection of the 690 * foreground call. 691 */ 692 static Boolean restoreMuteState(Phone phone) { 693 //get the earliest connection 694 Connection c = phone.getForegroundCall().getEarliestConnection(); 695 696 // only do this if connection is not null. 697 if (c != null) { 698 699 int phoneType = phone.getPhoneType(); 700 701 // retrieve the mute value. 702 Boolean shouldMute = null; 703 704 // In CDMA, mute is not maintained per Connection. Single mute apply for 705 // a call where call can have multiple connections such as 706 // Three way and Call Waiting. Therefore retrieving Mute state for 707 // latest connection can apply for all connection in that call 708 if (phoneType == Phone.PHONE_TYPE_CDMA) { 709 shouldMute = sConnectionMuteTable.get( 710 phone.getForegroundCall().getLatestConnection()); 711 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 712 shouldMute = sConnectionMuteTable.get( 713 phone.getForegroundCall().getEarliestConnection()); 714 } 715 if (shouldMute == null) { 716 if (DBG) log("problem retrieving mute value for this connection."); 717 shouldMute = Boolean.FALSE; 718 } 719 720 // set the mute value and return the result. 721 setMute (phone, shouldMute.booleanValue()); 722 return shouldMute; 723 } 724 return Boolean.valueOf(getMute (phone)); 725 } 726 727 static void mergeCalls(Phone phone) { 728 int phoneType = phone.getPhoneType(); 729 if (phoneType == Phone.PHONE_TYPE_GSM) { 730 try { 731 if (DBG) log("mergeCalls"); 732 phone.conference(); 733 } catch (CallStateException ex) { 734 Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex); 735 } 736 } else if (phoneType == Phone.PHONE_TYPE_CDMA) { 737 if (DBG) log("mergeCalls"); 738 PhoneApp app = PhoneApp.getInstance(); 739 if (app.cdmaPhoneCallState.getCurrentCallState() 740 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { 741 // Set the Phone Call State to conference 742 app.cdmaPhoneCallState.setCurrentCallState( 743 CdmaPhoneCallState.PhoneCallState.CONF_CALL); 744 745 // Send flash cmd 746 // TODO: Need to change the call from switchHoldingAndActive to 747 // something meaningful as we are not actually trying to swap calls but 748 // instead are merging two calls by sending a Flash command. 749 switchHoldingAndActive(phone); 750 } 751 } else { 752 throw new IllegalStateException("Unexpected phone type: " + phoneType); 753 } 754 } 755 756 static void separateCall(Connection c) { 757 try { 758 if (DBG) log("separateCall: " + c.getAddress()); 759 c.separate(); 760 } catch (CallStateException ex) { 761 Log.w(LOG_TAG, "separateCall: caught " + ex, ex); 762 } 763 } 764 765 /** 766 * Handle the MMIInitiate message and put up an alert that lets 767 * the user cancel the operation, if applicable. 768 * 769 * @param context context to get strings. 770 * @param mmiCode the MmiCode object being started. 771 * @param buttonCallbackMessage message to post when button is clicked. 772 * @param previousAlert a previous alert used in this activity. 773 * @return the dialog handle 774 */ 775 static Dialog displayMMIInitiate(Context context, 776 MmiCode mmiCode, 777 Message buttonCallbackMessage, 778 Dialog previousAlert) { 779 if (DBG) log("displayMMIInitiate: " + mmiCode); 780 if (previousAlert != null) { 781 previousAlert.dismiss(); 782 } 783 784 // The UI paradigm we are using now requests that all dialogs have 785 // user interaction, and that any other messages to the user should 786 // be by way of Toasts. 787 // 788 // In adhering to this request, all MMI initiating "OK" dialogs 789 // (non-cancelable MMIs) that end up being closed when the MMI 790 // completes (thereby showing a completion dialog) are being 791 // replaced with Toasts. 792 // 793 // As a side effect, moving to Toasts for the non-cancelable MMIs 794 // also means that buttonCallbackMessage (which was tied into "OK") 795 // is no longer invokable for these dialogs. This is not a problem 796 // since the only callback messages we supported were for cancelable 797 // MMIs anyway. 798 // 799 // A cancelable MMI is really just a USSD request. The term 800 // "cancelable" here means that we can cancel the request when the 801 // system prompts us for a response, NOT while the network is 802 // processing the MMI request. Any request to cancel a USSD while 803 // the network is NOT ready for a response may be ignored. 804 // 805 // With this in mind, we replace the cancelable alert dialog with 806 // a progress dialog, displayed until we receive a request from 807 // the the network. For more information, please see the comments 808 // in the displayMMIComplete() method below. 809 // 810 // Anything that is NOT a USSD request is a normal MMI request, 811 // which will bring up a toast (desribed above). 812 // Optional code for Extended USSD running prompt 813 if (mNwService != null) { 814 if (DBG) log("running USSD code, displaying indeterminate progress."); 815 // create the indeterminate progress dialog and display it. 816 ProgressDialog pd = new ProgressDialog(context); 817 CharSequence textmsg = ""; 818 try { 819 textmsg = mNwService.getMmiRunningText(); 820 821 } catch (RemoteException e) { 822 mNwService = null; 823 textmsg = context.getText(R.string.ussdRunning); 824 } 825 if (DBG) log("Extended NW displayMMIInitiate (" + textmsg+ ")"); 826 pd.setMessage(textmsg); 827 pd.setCancelable(false); 828 pd.setIndeterminate(true); 829 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); 830 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 831 pd.show(); 832 // trigger a 15 seconds timeout to clear this progress dialog 833 mMmiTimeoutCbMsg = buttonCallbackMessage; 834 try { 835 mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000); 836 } catch(NullPointerException e) { 837 mMmiTimeoutCbMsg = null; 838 } 839 return pd; 840 } 841 842 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable(); 843 844 if (!isCancelable) { 845 if (DBG) log("not a USSD code, displaying status toast."); 846 CharSequence text = context.getText(R.string.mmiStarted); 847 Toast.makeText(context, text, Toast.LENGTH_SHORT) 848 .show(); 849 return null; 850 } else { 851 if (DBG) log("running USSD code, displaying indeterminate progress."); 852 853 // create the indeterminate progress dialog and display it. 854 ProgressDialog pd = new ProgressDialog(context); 855 pd.setMessage(context.getText(R.string.ussdRunning)); 856 pd.setCancelable(false); 857 pd.setIndeterminate(true); 858 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); 859 860 pd.show(); 861 862 return pd; 863 } 864 865 } 866 867 /** 868 * Handle the MMIComplete message and fire off an intent to display 869 * the message. 870 * 871 * @param context context to get strings. 872 * @param mmiCode MMI result. 873 * @param previousAlert a previous alert used in this activity. 874 */ 875 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode, 876 Message dismissCallbackMessage, 877 AlertDialog previousAlert) { 878 CharSequence text; 879 int title = 0; // title for the progress dialog, if needed. 880 MmiCode.State state = mmiCode.getState(); 881 882 if (DBG) log("displayMMIComplete: state=" + state); 883 // Clear timeout trigger message 884 if(mMmiTimeoutCbMsg != null) { 885 try{ 886 mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what); 887 if (DBG) log("Extended NW displayMMIComplete removeMsg"); 888 } catch (NullPointerException e) { 889 } 890 mMmiTimeoutCbMsg = null; 891 } 892 893 894 switch (state) { 895 case PENDING: 896 // USSD code asking for feedback from user. 897 text = mmiCode.getMessage(); 898 if (DBG) log("- using text from PENDING MMI message: '" + text + "'"); 899 break; 900 case CANCELLED: 901 text = context.getText(R.string.mmiCancelled); 902 break; 903 case COMPLETE: 904 if (PhoneApp.getInstance().getPUKEntryActivity() != null) { 905 // if an attempt to unPUK the device was made, we specify 906 // the title and the message here. 907 title = com.android.internal.R.string.PinMmi; 908 text = context.getText(R.string.puk_unlocked); 909 break; 910 } 911 // All other conditions for the COMPLETE mmi state will cause 912 // the case to fall through to message logic in common with 913 // the FAILED case. 914 915 case FAILED: 916 text = mmiCode.getMessage(); 917 if (DBG) log("- using text from MMI message: '" + text + "'"); 918 break; 919 default: 920 throw new IllegalStateException("Unexpected MmiCode state: " + state); 921 } 922 923 if (previousAlert != null) { 924 previousAlert.dismiss(); 925 } 926 927 // Check to see if a UI exists for the PUK activation. If it does 928 // exist, then it indicates that we're trying to unblock the PUK. 929 PhoneApp app = PhoneApp.getInstance(); 930 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) { 931 if (DBG) log("displaying PUK unblocking progress dialog."); 932 933 // create the progress dialog, make sure the flags and type are 934 // set correctly. 935 ProgressDialog pd = new ProgressDialog(app); 936 pd.setTitle(title); 937 pd.setMessage(text); 938 pd.setCancelable(false); 939 pd.setIndeterminate(true); 940 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 941 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); 942 943 // display the dialog 944 pd.show(); 945 946 // indicate to the Phone app that the progress dialog has 947 // been assigned for the PUK unlock / SIM READY process. 948 app.setPukEntryProgressDialog(pd); 949 950 } else { 951 // In case of failure to unlock, we'll need to reset the 952 // PUK unlock activity, so that the user may try again. 953 if (app.getPUKEntryActivity() != null) { 954 app.setPukEntryActivity(null); 955 } 956 957 // A USSD in a pending state means that it is still 958 // interacting with the user. 959 if (state != MmiCode.State.PENDING) { 960 if (DBG) log("MMI code has finished running."); 961 962 // Replace response message with Extended Mmi wording 963 if (mNwService != null) { 964 try { 965 text = mNwService.getUserMessage(text); 966 } catch (RemoteException e) { 967 mNwService = null; 968 } 969 if (DBG) log("Extended NW displayMMIInitiate (" + text + ")"); 970 if (text == null || text.length() == 0) 971 return; 972 } 973 974 // displaying system alert dialog on the screen instead of 975 // using another activity to display the message. This 976 // places the message at the forefront of the UI. 977 AlertDialog newDialog = new AlertDialog.Builder(context) 978 .setMessage(text) 979 .setPositiveButton(R.string.ok, null) 980 .setCancelable(true) 981 .create(); 982 983 newDialog.getWindow().setType( 984 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 985 newDialog.getWindow().addFlags( 986 WindowManager.LayoutParams.FLAG_DIM_BEHIND); 987 988 newDialog.show(); 989 } else { 990 if (DBG) log("USSD code has requested user input. Constructing input dialog."); 991 992 // USSD MMI code that is interacting with the user. The 993 // basic set of steps is this: 994 // 1. User enters a USSD request 995 // 2. We recognize the request and displayMMIInitiate 996 // (above) creates a progress dialog. 997 // 3. Request returns and we get a PENDING or COMPLETE 998 // message. 999 // 4. These MMI messages are caught in the PhoneApp 1000 // (onMMIComplete) and the InCallScreen 1001 // (mHandler.handleMessage) which bring up this dialog 1002 // and closes the original progress dialog, 1003 // respectively. 1004 // 5. If the message is anything other than PENDING, 1005 // we are done, and the alert dialog (directly above) 1006 // displays the outcome. 1007 // 6. If the network is requesting more information from 1008 // the user, the MMI will be in a PENDING state, and 1009 // we display this dialog with the message. 1010 // 7. User input, or cancel requests result in a return 1011 // to step 1. Keep in mind that this is the only 1012 // time that a USSD should be canceled. 1013 1014 // inflate the layout with the scrolling text area for the dialog. 1015 LayoutInflater inflater = (LayoutInflater) context.getSystemService( 1016 Context.LAYOUT_INFLATER_SERVICE); 1017 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null); 1018 1019 // get the input field. 1020 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field); 1021 1022 // specify the dialog's click listener, with SEND and CANCEL logic. 1023 final DialogInterface.OnClickListener mUSSDDialogListener = 1024 new DialogInterface.OnClickListener() { 1025 public void onClick(DialogInterface dialog, int whichButton) { 1026 switch (whichButton) { 1027 case DialogInterface.BUTTON_POSITIVE: 1028 phone.sendUssdResponse(inputText.getText().toString()); 1029 break; 1030 case DialogInterface.BUTTON_NEGATIVE: 1031 if (mmiCode.isCancelable()) { 1032 mmiCode.cancel(); 1033 } 1034 break; 1035 } 1036 } 1037 }; 1038 1039 // build the dialog 1040 final AlertDialog newDialog = new AlertDialog.Builder(context) 1041 .setMessage(text) 1042 .setView(dialogView) 1043 .setPositiveButton(R.string.send_button, mUSSDDialogListener) 1044 .setNegativeButton(R.string.cancel, mUSSDDialogListener) 1045 .setCancelable(false) 1046 .create(); 1047 1048 // attach the key listener to the dialog's input field and make 1049 // sure focus is set. 1050 final View.OnKeyListener mUSSDDialogInputListener = 1051 new View.OnKeyListener() { 1052 public boolean onKey(View v, int keyCode, KeyEvent event) { 1053 switch (keyCode) { 1054 case KeyEvent.KEYCODE_CALL: 1055 case KeyEvent.KEYCODE_ENTER: 1056 phone.sendUssdResponse(inputText.getText().toString()); 1057 newDialog.dismiss(); 1058 return true; 1059 } 1060 return false; 1061 } 1062 }; 1063 inputText.setOnKeyListener(mUSSDDialogInputListener); 1064 inputText.requestFocus(); 1065 1066 // set the window properties of the dialog 1067 newDialog.getWindow().setType( 1068 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 1069 newDialog.getWindow().addFlags( 1070 WindowManager.LayoutParams.FLAG_DIM_BEHIND); 1071 1072 // now show the dialog! 1073 newDialog.show(); 1074 } 1075 } 1076 } 1077 1078 /** 1079 * Cancels the current pending MMI operation, if applicable. 1080 * @return true if we canceled an MMI operation, or false 1081 * if the current pending MMI wasn't cancelable 1082 * or if there was no current pending MMI at all. 1083 * 1084 * @see displayMMIInitiate 1085 */ 1086 static boolean cancelMmiCode(Phone phone) { 1087 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes(); 1088 int count = pendingMmis.size(); 1089 if (DBG) log("cancelMmiCode: num pending MMIs = " + count); 1090 1091 boolean canceled = false; 1092 if (count > 0) { 1093 // assume that we only have one pending MMI operation active at a time. 1094 // I don't think it's possible to enter multiple MMI codes concurrently 1095 // in the phone UI, because during the MMI operation, an Alert panel 1096 // is displayed, which prevents more MMI code from being entered. 1097 MmiCode mmiCode = pendingMmis.get(0); 1098 if (mmiCode.isCancelable()) { 1099 mmiCode.cancel(); 1100 canceled = true; 1101 } 1102 } 1103 1104 //clear timeout message and pre-set MMI command 1105 if (mNwService != null) { 1106 try { 1107 mNwService.clearMmiString(); 1108 } catch (RemoteException e) { 1109 mNwService = null; 1110 } 1111 } 1112 if (mMmiTimeoutCbMsg != null) { 1113 mMmiTimeoutCbMsg = null; 1114 } 1115 return canceled; 1116 } 1117 1118 public static class VoiceMailNumberMissingException extends Exception { 1119 VoiceMailNumberMissingException() { 1120 super(); 1121 } 1122 1123 VoiceMailNumberMissingException(String msg) { 1124 super(msg); 1125 } 1126 } 1127 1128 /** 1129 * Gets the phone number to be called from an intent. Requires a Context 1130 * to access the contacts database, and a Phone to access the voicemail 1131 * number. 1132 * 1133 * <p>If <code>phone</code> is <code>null</code>, the function will return 1134 * <code>null</code> for <code>voicemail:</code> URIs; 1135 * if <code>context</code> is <code>null</code>, the function will return 1136 * <code>null</code> for person/phone URIs.</p> 1137 * 1138 * @param context a context to use (or 1139 * @param phone the phone on which the number would be called 1140 * @param intent the intent 1141 * 1142 * @throws VoiceMailNumberMissingException if <code>intent</code> contains 1143 * a <code>voicemail:</code> URI, but <code>phone</code> does not 1144 * have a voicemail number set. 1145 * 1146 * @return the phone number that would be called by the intent, 1147 * or <code>null</code> if the number cannot be found. 1148 */ 1149 static String getNumberFromIntent(Context context, Phone phone, Intent intent) 1150 throws VoiceMailNumberMissingException { 1151 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context); 1152 1153 // Check for a voicemail-dailing request. If the voicemail number is 1154 // empty, throw a VoiceMailNumberMissingException. 1155 if (intent.getData().getScheme().equals("voicemail") && 1156 (number == null || TextUtils.isEmpty(number))) 1157 throw new VoiceMailNumberMissingException(); 1158 1159 return number; 1160 } 1161 1162 /** 1163 * Returns the caller-id info corresponding to the specified Connection. 1164 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we 1165 * extract a phone number from the specified Connection, and feed that 1166 * number into CallerInfo.getCallerInfo().) 1167 * 1168 * The returned CallerInfo may be null in certain error cases, like if the 1169 * specified Connection was null, or if we weren't able to get a valid 1170 * phone number from the Connection. 1171 * 1172 * Finally, if the getCallerInfo() call did succeed, we save the resulting 1173 * CallerInfo object in the "userData" field of the Connection. 1174 * 1175 * NOTE: This API should be avoided, with preference given to the 1176 * asynchronous startGetCallerInfo API. 1177 */ 1178 static CallerInfo getCallerInfo(Context context, Connection c) { 1179 CallerInfo info = null; 1180 1181 if (c != null) { 1182 //See if there is a URI attached. If there is, this means 1183 //that there is no CallerInfo queried yet, so we'll need to 1184 //replace the URI with a full CallerInfo object. 1185 Object userDataObject = c.getUserData(); 1186 if (userDataObject instanceof Uri) { 1187 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject); 1188 if (info != null) { 1189 c.setUserData(info); 1190 } 1191 } else { 1192 if (userDataObject instanceof CallerInfoToken) { 1193 //temporary result, while query is running 1194 info = ((CallerInfoToken) userDataObject).currentInfo; 1195 } else { 1196 //final query result 1197 info = (CallerInfo) userDataObject; 1198 } 1199 if (info == null) { 1200 // No URI, or Existing CallerInfo, so we'll have to make do with 1201 // querying a new CallerInfo using the connection's phone number. 1202 String number = c.getAddress(); 1203 1204 if (DBG) log("getCallerInfo: number = " + number); 1205 1206 if (!TextUtils.isEmpty(number)) { 1207 info = CallerInfo.getCallerInfo(context, number); 1208 if (info != null) { 1209 c.setUserData(info); 1210 } 1211 } 1212 } 1213 } 1214 } 1215 return info; 1216 } 1217 1218 /** 1219 * Class returned by the startGetCallerInfo call to package a temporary 1220 * CallerInfo Object, to be superceded by the CallerInfo Object passed 1221 * into the listener when the query with token mAsyncQueryToken is complete. 1222 */ 1223 public static class CallerInfoToken { 1224 /**indicates that there will no longer be updates to this request.*/ 1225 public boolean isFinal; 1226 1227 public CallerInfo currentInfo; 1228 public CallerInfoAsyncQuery asyncQuery; 1229 } 1230 1231 /** 1232 * Start a CallerInfo Query based on the earliest connection in the call. 1233 */ 1234 static CallerInfoToken startGetCallerInfo(Context context, Call call, 1235 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { 1236 PhoneApp app = PhoneApp.getInstance(); 1237 Connection conn = null; 1238 int phoneType = app.phone.getPhoneType(); 1239 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1240 conn = call.getLatestConnection(); 1241 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 1242 conn = call.getEarliestConnection(); 1243 } else { 1244 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1245 } 1246 1247 return startGetCallerInfo(context, conn, listener, cookie); 1248 } 1249 1250 /** 1251 * place a temporary callerinfo object in the hands of the caller and notify 1252 * caller when the actual query is done. 1253 */ 1254 static CallerInfoToken startGetCallerInfo(Context context, Connection c, 1255 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { 1256 CallerInfoToken cit; 1257 1258 if (c == null) { 1259 //TODO: perhaps throw an exception here. 1260 cit = new CallerInfoToken(); 1261 cit.asyncQuery = null; 1262 return cit; 1263 } 1264 1265 // There are now 3 states for the userdata. 1266 // 1. Uri - query has not been executed yet 1267 // 2. CallerInfoToken - query is executing, but has not completed. 1268 // 3. CallerInfo - query has executed. 1269 // In each case we have slightly different behaviour: 1270 // 1. If the query has not been executed yet (Uri or null), we start 1271 // query execution asynchronously, and note it by attaching a 1272 // CallerInfoToken as the userData. 1273 // 2. If the query is executing (CallerInfoToken), we've essentially 1274 // reached a state where we've received multiple requests for the 1275 // same callerInfo. That means that once the query is complete, 1276 // we'll need to execute the additional listener requested. 1277 // 3. If the query has already been executed (CallerInfo), we just 1278 // return the CallerInfo object as expected. 1279 // 4. Regarding isFinal - there are cases where the CallerInfo object 1280 // will not be attached, like when the number is empty (caller id 1281 // blocking). This flag is used to indicate that the 1282 // CallerInfoToken object is going to be permanent since no 1283 // query results will be returned. In the case where a query 1284 // has been completed, this flag is used to indicate to the caller 1285 // that the data will not be updated since it is valid. 1286 // 1287 // Note: For the case where a number is NOT retrievable, we leave 1288 // the CallerInfo as null in the CallerInfoToken. This is 1289 // something of a departure from the original code, since the old 1290 // code manufactured a CallerInfo object regardless of the query 1291 // outcome. From now on, we will append an empty CallerInfo 1292 // object, to mirror previous behaviour, and to avoid Null Pointer 1293 // Exceptions. 1294 Object userDataObject = c.getUserData(); 1295 if (userDataObject instanceof Uri) { 1296 //create a dummy callerinfo, populate with what we know from URI. 1297 cit = new CallerInfoToken(); 1298 cit.currentInfo = new CallerInfo(); 1299 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1300 (Uri) userDataObject, sCallerInfoQueryListener, c); 1301 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1302 cit.isFinal = false; 1303 1304 c.setUserData(cit); 1305 1306 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject); 1307 1308 } else if (userDataObject == null) { 1309 // No URI, or Existing CallerInfo, so we'll have to make do with 1310 // querying a new CallerInfo using the connection's phone number. 1311 String number = c.getAddress(); 1312 1313 cit = new CallerInfoToken(); 1314 cit.currentInfo = new CallerInfo(); 1315 1316 // Store CNAP information retrieved from the Connection (we want to do this 1317 // here regardless of whether the number is empty or not). 1318 cit.currentInfo.cnapName = c.getCnapName(); 1319 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten 1320 // by ContactInfo later 1321 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1322 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1323 1324 if (DBG) { 1325 log("startGetCallerInfo: number = " + number); 1326 log("startGetCallerInfo: CNAP Info from FW(1): name=" 1327 + cit.currentInfo.cnapName 1328 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1329 } 1330 1331 // handling case where number is null (caller id hidden) as well. 1332 if (!TextUtils.isEmpty(number)) { 1333 // Check for special CNAP cases and modify the CallerInfo accordingly 1334 // to be sure we keep the right information to display/log later 1335 number = modifyForSpecialCnapCases(context, cit.currentInfo, number, 1336 cit.currentInfo.numberPresentation); 1337 1338 cit.currentInfo.phoneNumber = number; 1339 // For scenarios where we may receive a valid number from the network but a 1340 // restricted/unavailable presentation, we do not want to perform a contact query 1341 // (see note on isFinal above). So we set isFinal to true here as well. 1342 if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { 1343 cit.isFinal = true; 1344 } else { 1345 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1346 number, sCallerInfoQueryListener, c); 1347 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1348 cit.isFinal = false; 1349 } 1350 } else { 1351 // This is the case where we are querying on a number that 1352 // is null or empty, like a caller whose caller id is 1353 // blocked or empty (CLIR). The previous behaviour was to 1354 // throw a null CallerInfo object back to the user, but 1355 // this departure is somewhat cleaner. 1356 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply."); 1357 cit.isFinal = true; // please see note on isFinal, above. 1358 } 1359 1360 c.setUserData(cit); 1361 1362 if (DBG) log("startGetCallerInfo: query based on number: " + number); 1363 1364 } else if (userDataObject instanceof CallerInfoToken) { 1365 // query is running, just tack on this listener to the queue. 1366 cit = (CallerInfoToken) userDataObject; 1367 1368 // handling case where number is null (caller id hidden) as well. 1369 if (cit.asyncQuery != null) { 1370 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1371 1372 if (DBG) log("startGetCallerInfo: query already running, adding listener: " + 1373 listener.getClass().toString()); 1374 } else { 1375 // handling case where number/name gets updated later on by the network 1376 String updatedNumber = c.getAddress(); 1377 if (DBG) log("startGetCallerInfo: updatedNumber initially = " + updatedNumber); 1378 if (!TextUtils.isEmpty(updatedNumber)) { 1379 // Store CNAP information retrieved from the Connection 1380 cit.currentInfo.cnapName = c.getCnapName(); 1381 // This can still get overwritten by ContactInfo 1382 cit.currentInfo.name = cit.currentInfo.cnapName; 1383 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1384 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1385 1386 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo, 1387 updatedNumber, cit.currentInfo.numberPresentation); 1388 1389 cit.currentInfo.phoneNumber = updatedNumber; 1390 if (DBG) log("startGetCallerInfo: updatedNumber=" + updatedNumber); 1391 if (DBG) log("startGetCallerInfo: CNAP Info from FW(2): name=" 1392 + cit.currentInfo.cnapName 1393 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1394 // For scenarios where we may receive a valid number from the network but a 1395 // restricted/unavailable presentation, we do not want to perform a contact query 1396 // (see note on isFinal above). So we set isFinal to true here as well. 1397 if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { 1398 cit.isFinal = true; 1399 } else { 1400 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1401 updatedNumber, sCallerInfoQueryListener, c); 1402 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1403 cit.isFinal = false; 1404 } 1405 } else { 1406 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply."); 1407 if (cit.currentInfo == null) { 1408 cit.currentInfo = new CallerInfo(); 1409 } 1410 // Store CNAP information retrieved from the Connection 1411 cit.currentInfo.cnapName = c.getCnapName(); // This can still get 1412 // overwritten by ContactInfo 1413 cit.currentInfo.name = cit.currentInfo.cnapName; 1414 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1415 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1416 1417 if (DBG) log("startGetCallerInfo: CNAP Info from FW(3): name=" 1418 + cit.currentInfo.cnapName 1419 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1420 cit.isFinal = true; // please see note on isFinal, above. 1421 } 1422 } 1423 } else { 1424 cit = new CallerInfoToken(); 1425 cit.currentInfo = (CallerInfo) userDataObject; 1426 cit.asyncQuery = null; 1427 cit.isFinal = true; 1428 // since the query is already done, call the listener. 1429 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo"); 1430 } 1431 return cit; 1432 } 1433 1434 /** 1435 * Implemented for CallerInfo.OnCallerInfoQueryCompleteListener interface. 1436 * Updates the connection's userData when called. 1437 */ 1438 private static final int QUERY_TOKEN = -1; 1439 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener = 1440 new CallerInfoAsyncQuery.OnQueryCompleteListener () { 1441 public void onQueryComplete(int token, Object cookie, CallerInfo ci) { 1442 if (DBG) log("query complete, updating connection.userdata"); 1443 Connection conn = (Connection) cookie; 1444 1445 // Added a check if CallerInfo is coming from ContactInfo or from Connection. 1446 // If no ContactInfo, then we want to use CNAP information coming from network 1447 if (DBG) log("- onQueryComplete: CallerInfo:" + ci); 1448 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) { 1449 // If the number presentation has not been set by 1450 // the ContactInfo, use the one from the 1451 // connection. 1452 1453 // TODO: Need a new util method to merge the info 1454 // from the Connection in a CallerInfo object. 1455 // Here 'ci' is a new CallerInfo instance read 1456 // from the DB. It has lost all the connection 1457 // info preset before the query (see PhoneUtils 1458 // line 1334). We should have a method to merge 1459 // back into this new instance the info from the 1460 // connection object not set by the DB. If the 1461 // Connection already has a CallerInfo instance in 1462 // userData, then we could use this instance to 1463 // fill 'ci' in. The same routine could be used in 1464 // PhoneUtils. 1465 if (0 == ci.numberPresentation) { 1466 ci.numberPresentation = conn.getNumberPresentation(); 1467 } 1468 } else { 1469 CallerInfo newCi = getCallerInfo(null, conn); 1470 if (newCi != null) { 1471 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number 1472 ci = newCi; 1473 } 1474 } 1475 conn.setUserData(ci); 1476 } 1477 }; 1478 1479 1480 /** 1481 * Returns a single "name" for the specified given a CallerInfo object. 1482 * If the name is null, return defaultString as the default value, usually 1483 * context.getString(R.string.unknown). 1484 */ 1485 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) { 1486 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci); 1487 1488 String compactName = null; 1489 if (ci != null) { 1490 if (TextUtils.isEmpty(ci.name)) { 1491 // Perform any modifications for special CNAP cases to 1492 // the phone number being displayed, if applicable. 1493 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber, 1494 ci.numberPresentation); 1495 } else { 1496 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795. 1497 compactName = ci.name; 1498 } 1499 } 1500 1501 if ((compactName == null) || (TextUtils.isEmpty(compactName))) { 1502 // If we're still null/empty here, then check if we have a presentation 1503 // string that takes precedence that we could return, otherwise display 1504 // "unknown" string. 1505 if (ci != null && ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) { 1506 compactName = context.getString(R.string.private_num); 1507 } else if (ci != null && ci.numberPresentation == Connection.PRESENTATION_PAYPHONE) { 1508 compactName = context.getString(R.string.payphone); 1509 } else { 1510 compactName = context.getString(R.string.unknown); 1511 } 1512 } 1513 if (DBG) log("getCompactNameFromCallerInfo: compactName=" + compactName); 1514 return compactName; 1515 } 1516 1517 /** 1518 * Returns true if the specified Call is a "conference call", meaning 1519 * that it owns more than one Connection object. This information is 1520 * used to trigger certain UI changes that appear when a conference 1521 * call is active (like displaying the label "Conference call", and 1522 * enabling the "Manage conference" UI.) 1523 * 1524 * Watch out: This method simply checks the number of Connections, 1525 * *not* their states. So if a Call has (for example) one ACTIVE 1526 * connection and one DISCONNECTED connection, this method will return 1527 * true (which is unintuitive, since the Call isn't *really* a 1528 * conference call any more.) 1529 * 1530 * @return true if the specified call has more than one connection (in any state.) 1531 */ 1532 static boolean isConferenceCall(Call call) { 1533 // CDMA phones don't have the same concept of "conference call" as 1534 // GSM phones do; there's no special "conference call" state of 1535 // the UI or a "manage conference" function. (Instead, when 1536 // you're in a 3-way call, all we can do is display the "generic" 1537 // state of the UI.) So as far as the in-call UI is concerned, 1538 // Conference corresponds to generic display. 1539 PhoneApp app = PhoneApp.getInstance(); 1540 int phoneType = app.phone.getPhoneType(); 1541 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1542 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState(); 1543 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL) 1544 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) 1545 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) { 1546 return true; 1547 } 1548 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 1549 List<Connection> connections = call.getConnections(); 1550 if (connections != null && connections.size() > 1) { 1551 return true; 1552 } 1553 } else { 1554 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1555 } 1556 return false; 1557 1558 // TODO: We may still want to change the semantics of this method 1559 // to say that a given call is only really a conference call if 1560 // the number of ACTIVE connections, not the total number of 1561 // connections, is greater than one. (See warning comment in the 1562 // javadoc above.) 1563 // Here's an implementation of that: 1564 // if (connections == null) { 1565 // return false; 1566 // } 1567 // int numActiveConnections = 0; 1568 // for (Connection conn : connections) { 1569 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState()); 1570 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++; 1571 // if (numActiveConnections > 1) { 1572 // return true; 1573 // } 1574 // } 1575 // return false; 1576 } 1577 1578 /** 1579 * Launch the Dialer to start a new call. 1580 * This is just a wrapper around the ACTION_DIAL intent. 1581 */ 1582 static void startNewCall(final Phone phone) { 1583 // Sanity-check that this is OK given the current state of the phone. 1584 if (!okToAddCall(phone)) { 1585 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state"); 1586 dumpCallState(phone); 1587 return; 1588 } 1589 1590 // if applicable, mute the call while we're showing the add call UI. 1591 if (!phone.getForegroundCall().isIdle()) { 1592 setMuteInternal(phone, true); 1593 // Inform the phone app that this mute state was NOT done 1594 // voluntarily by the User. 1595 PhoneApp.getInstance().setRestoreMuteOnInCallResume(true); 1596 } 1597 1598 Intent intent = new Intent(Intent.ACTION_DIAL); 1599 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1600 1601 // when we request the dialer come up, we also want to inform 1602 // it that we're going through the "add call" option from the 1603 // InCallScreen / PhoneUtils. 1604 intent.putExtra(ADD_CALL_MODE_KEY, true); 1605 1606 PhoneApp.getInstance().startActivity(intent); 1607 } 1608 1609 static void turnOnSpeaker(Context context, boolean flag, boolean store) { 1610 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")..."); 1611 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1612 1613 audioManager.setSpeakerphoneOn(flag); 1614 // record the speaker-enable value 1615 if (store) { 1616 sIsSpeakerEnabled = flag; 1617 } 1618 if (flag) { 1619 NotificationMgr.getDefault().notifySpeakerphone(); 1620 } else { 1621 NotificationMgr.getDefault().cancelSpeakerphone(); 1622 } 1623 1624 // We also need to make a fresh call to PhoneApp.updateWakeState() 1625 // any time the speaker state changes, since the screen timeout is 1626 // sometimes different depending on whether or not the speaker is 1627 // in use. 1628 PhoneApp app = PhoneApp.getInstance(); 1629 app.updateWakeState(); 1630 1631 // Update the Proximity sensor based on speaker state 1632 app.updateProximitySensorMode(app.phone.getState()); 1633 } 1634 1635 /** 1636 * Restore the speaker mode, called after a wired headset disconnect 1637 * event. 1638 */ 1639 static void restoreSpeakerMode(Context context) { 1640 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled); 1641 1642 // change the mode if needed. 1643 if (isSpeakerOn(context) != sIsSpeakerEnabled) { 1644 turnOnSpeaker(context, sIsSpeakerEnabled, false); 1645 } 1646 } 1647 1648 static boolean isSpeakerOn(Context context) { 1649 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1650 return audioManager.isSpeakerphoneOn(); 1651 } 1652 1653 1654 static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) { 1655 if (DBG) log("turnOnNoiseSuppression: " + flag); 1656 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1657 1658 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1659 return; 1660 } 1661 1662 if (flag) { 1663 audioManager.setParameters("noise_suppression=auto"); 1664 } else { 1665 audioManager.setParameters("noise_suppression=off"); 1666 } 1667 1668 // record the speaker-enable value 1669 if (store) { 1670 sIsNoiseSuppressionEnabled = flag; 1671 } 1672 1673 // TODO: implement and manage ICON 1674 1675 } 1676 1677 static void restoreNoiseSuppression(Context context) { 1678 if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled); 1679 1680 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1681 return; 1682 } 1683 1684 // change the mode if needed. 1685 if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) { 1686 turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false); 1687 } 1688 } 1689 1690 static boolean isNoiseSuppressionOn(Context context) { 1691 1692 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1693 return false; 1694 } 1695 1696 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1697 String noiseSuppression = audioManager.getParameters("noise_suppression"); 1698 if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression); 1699 if (noiseSuppression.contains("off")) { 1700 return false; 1701 } else { 1702 return true; 1703 } 1704 } 1705 1706 /** 1707 * Wrapper around Phone.setMute() that also updates the mute icon in 1708 * the status bar. 1709 * 1710 * All muting / unmuting from the in-call UI should go through this 1711 * wrapper. 1712 */ 1713 static void setMute(Phone phone, boolean muted) { 1714 // make the call to mute the audio 1715 setMuteInternal(phone, muted); 1716 1717 // update the foreground connections to match. This includes 1718 // all the connections on conference calls. 1719 for (Connection cn : phone.getForegroundCall().getConnections()) { 1720 if (sConnectionMuteTable.get(cn) == null) { 1721 if (DBG) log("problem retrieving mute value for this connection."); 1722 } 1723 sConnectionMuteTable.put(cn, Boolean.valueOf(muted)); 1724 } 1725 } 1726 1727 /** 1728 * Internally used muting function. All UI calls should use {@link setMute} 1729 */ 1730 static void setMuteInternal(Phone phone, boolean muted) { 1731 if (DBG) log("setMute: " + muted); 1732 Context context = phone.getContext(); 1733 boolean routeToAudioManager = 1734 context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); 1735 if (routeToAudioManager) { 1736 AudioManager audioManager = 1737 (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE); 1738 if (DBG) log(" setMicrophoneMute: " + muted); 1739 audioManager.setMicrophoneMute(muted); 1740 } else { 1741 phone.setMute(muted); 1742 } 1743 if (muted) { 1744 NotificationMgr.getDefault().notifyMute(); 1745 } else { 1746 NotificationMgr.getDefault().cancelMute(); 1747 } 1748 } 1749 1750 static boolean getMute(Phone phone) { 1751 Context context = phone.getContext(); 1752 boolean routeToAudioManager = 1753 context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); 1754 if (routeToAudioManager) { 1755 AudioManager audioManager = 1756 (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE); 1757 return audioManager.isMicrophoneMute(); 1758 } else { 1759 return phone.getMute(); 1760 } 1761 } 1762 1763 /** 1764 * A really simple wrapper around AudioManager.setMode(), 1765 * with a bit of extra logging to help debug the exact 1766 * timing (and call stacks) for all our setMode() calls. 1767 * 1768 * Also, add additional state monitoring to determine 1769 * whether or not certain calls to change the audio mode 1770 * are ignored. 1771 */ 1772 /* package */ static void setAudioMode(Context context, int mode) { 1773 if (DBG) Log.d(LOG_TAG, "setAudioMode(" + audioModeToString(mode) + ")..."); 1774 1775 //decide whether or not to ignore the audio setting 1776 boolean ignore = false; 1777 1778 switch (sAudioBehaviourState) { 1779 case AUDIO_RINGING: 1780 ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_IN_CALL)); 1781 break; 1782 case AUDIO_OFFHOOK: 1783 ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_RINGTONE)); 1784 break; 1785 case AUDIO_IDLE: 1786 default: 1787 ignore = (mode == AudioManager.MODE_IN_CALL); 1788 break; 1789 } 1790 1791 if (!ignore) { 1792 AudioManager audioManager = 1793 (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1794 // Enable stack dump only when actively debugging ("new Throwable()" is expensive!) 1795 if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump")); 1796 audioManager.setMode(mode); 1797 } else { 1798 if (DBG) Log.d(LOG_TAG, "setAudioMode(), state is " + sAudioBehaviourState + 1799 " ignoring " + audioModeToString(mode) + " request"); 1800 } 1801 } 1802 private static String audioModeToString(int mode) { 1803 switch (mode) { 1804 case AudioManager.MODE_INVALID: return "MODE_INVALID"; 1805 case AudioManager.MODE_CURRENT: return "MODE_CURRENT"; 1806 case AudioManager.MODE_NORMAL: return "MODE_NORMAL"; 1807 case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE"; 1808 case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL"; 1809 default: return String.valueOf(mode); 1810 } 1811 } 1812 1813 /** 1814 * Handles the wired headset button while in-call. 1815 * 1816 * This is called from the PhoneApp, not from the InCallScreen, 1817 * since the HEADSETHOOK button means "mute or unmute the current 1818 * call" *any* time a call is active, even if the user isn't actually 1819 * on the in-call screen. 1820 * 1821 * @return true if we consumed the event. 1822 */ 1823 /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) { 1824 if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount()); 1825 1826 // If the phone is totally idle, we ignore HEADSETHOOK events 1827 // (and instead let them fall through to the media player.) 1828 if (phone.getState() == Phone.State.IDLE) { 1829 return false; 1830 } 1831 1832 // Ok, the phone is in use. 1833 // The headset button button means "Answer" if an incoming call is 1834 // ringing. If not, it toggles the mute / unmute state. 1835 // 1836 // And in any case we *always* consume this event; this means 1837 // that the usual mediaplayer-related behavior of the headset 1838 // button will NEVER happen while the user is on a call. 1839 1840 final boolean hasRingingCall = !phone.getRingingCall().isIdle(); 1841 final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); 1842 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); 1843 1844 if (hasRingingCall && 1845 event.getRepeatCount() == 0 && 1846 event.getAction() == KeyEvent.ACTION_UP) { 1847 // If an incoming call is ringing, answer it (just like with the 1848 // CALL button): 1849 int phoneType = phone.getPhoneType(); 1850 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1851 answerCall(phone); 1852 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 1853 if (hasActiveCall && hasHoldingCall) { 1854 if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!"); 1855 answerAndEndActive(phone); 1856 } else { 1857 if (DBG) log("handleHeadsetHook: ringing ==> answer!"); 1858 answerCall(phone); // Automatically holds the current active call, 1859 // if there is one 1860 } 1861 } else { 1862 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1863 } 1864 } else { 1865 // No incoming ringing call. 1866 if (event.isLongPress()) { 1867 if (DBG) log("handleHeadsetHook: longpress -> hangup"); 1868 hangup(phone); 1869 } 1870 else if (event.getAction() == KeyEvent.ACTION_UP && 1871 event.getRepeatCount() == 0) { 1872 Connection c = phone.getForegroundCall().getLatestConnection(); 1873 // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook. 1874 if (c != null && !PhoneNumberUtils.isEmergencyNumber(c.getAddress())) { 1875 if (getMute(phone)) { 1876 if (DBG) log("handleHeadsetHook: UNmuting..."); 1877 setMute(phone, false); 1878 } else { 1879 if (DBG) log("handleHeadsetHook: muting..."); 1880 setMute(phone, true); 1881 } 1882 } 1883 } 1884 } 1885 1886 // Even if the InCallScreen is the current activity, there's no 1887 // need to force it to update, because (1) if we answered a 1888 // ringing call, the InCallScreen will imminently get a phone 1889 // state change event (causing an update), and (2) if we muted or 1890 // unmuted, the setMute() call automagically updates the status 1891 // bar, and there's no "mute" indication in the InCallScreen 1892 // itself (other than the menu item, which only ever stays 1893 // onscreen for a second anyway.) 1894 // TODO: (2) isn't entirely true anymore. Once we return our result 1895 // to the PhoneApp, we ask InCallScreen to update its control widgets 1896 // in case we changed mute or speaker state and phones with touch- 1897 // screen [toggle] buttons need to update themselves. 1898 1899 return true; 1900 } 1901 1902 /** 1903 * Look for ANY connections on the phone that qualify as being 1904 * disconnected. 1905 * 1906 * @return true if we find a connection that is disconnected over 1907 * all the phone's call objects. 1908 */ 1909 /* package */ static boolean hasDisconnectedConnections(Phone phone) { 1910 return hasDisconnectedConnections(phone.getForegroundCall()) || 1911 hasDisconnectedConnections(phone.getBackgroundCall()) || 1912 hasDisconnectedConnections(phone.getRingingCall()); 1913 } 1914 1915 /** 1916 * Iterate over all connections in a call to see if there are any 1917 * that are not alive (disconnected or idle). 1918 * 1919 * @return true if we find a connection that is disconnected, and 1920 * pending removal via 1921 * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}. 1922 */ 1923 private static final boolean hasDisconnectedConnections(Call call) { 1924 // look through all connections for non-active ones. 1925 for (Connection c : call.getConnections()) { 1926 if (!c.isAlive()) { 1927 return true; 1928 } 1929 } 1930 return false; 1931 } 1932 1933 // 1934 // Misc UI policy helper functions 1935 // 1936 1937 /** 1938 * @return true if we're allowed to swap calls, given the current 1939 * state of the Phone. 1940 */ 1941 /* package */ static boolean okToSwapCalls(Phone phone) { 1942 int phoneType = phone.getPhoneType(); 1943 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1944 // CDMA: "Swap" is enabled only when the phone reaches a *generic*. 1945 // state by either accepting a Call Waiting or by merging two calls 1946 PhoneApp app = PhoneApp.getInstance(); 1947 return (app.cdmaPhoneCallState.getCurrentCallState() 1948 == CdmaPhoneCallState.PhoneCallState.CONF_CALL); 1949 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 1950 // GSM: "Swap" is available if both lines are in use and there's no 1951 // incoming call. (Actually we need to verify that the active 1952 // call really is in the ACTIVE state and the holding call really 1953 // is in the HOLDING state, since you *can't* actually swap calls 1954 // when the foreground call is DIALING or ALERTING.) 1955 return phone.getRingingCall().isIdle() 1956 && (phone.getForegroundCall().getState() == Call.State.ACTIVE) 1957 && (phone.getBackgroundCall().getState() == Call.State.HOLDING); 1958 } else { 1959 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1960 } 1961 } 1962 1963 /** 1964 * @return true if we're allowed to merge calls, given the current 1965 * state of the Phone. 1966 */ 1967 /* package */ static boolean okToMergeCalls(Phone phone) { 1968 int phoneType = phone.getPhoneType(); 1969 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1970 // CDMA: "Merge" is enabled only when the user is in a 3Way call. 1971 PhoneApp app = PhoneApp.getInstance(); 1972 return ((app.cdmaPhoneCallState.getCurrentCallState() 1973 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) 1974 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); 1975 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 1976 // GSM: "Merge" is available if both lines are in use and there's no 1977 // incoming call, *and* the current conference isn't already 1978 // "full". 1979 return phone.getRingingCall().isIdle() && phone.canConference(); 1980 } else { 1981 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1982 } 1983 } 1984 1985 /** 1986 * @return true if the UI should let you add a new call, given the current 1987 * state of the Phone. 1988 */ 1989 /* package */ static boolean okToAddCall(Phone phone) { 1990 int phoneType = phone.getPhoneType(); 1991 final Call.State fgCallState = phone.getForegroundCall().getState(); 1992 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1993 // CDMA: "Add call" menu item is only enabled when the call is in 1994 // - ForegroundCall is in ACTIVE state 1995 // - After 30 seconds of user Ignoring/Missing a Call Waiting call. 1996 PhoneApp app = PhoneApp.getInstance(); 1997 return ((fgCallState == Call.State.ACTIVE) 1998 && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting())); 1999 } else if (phoneType == Phone.PHONE_TYPE_GSM) { 2000 // GSM: "Add call" is available only if ALL of the following are true: 2001 // - There's no incoming ringing call 2002 // - There's < 2 lines in use 2003 // - The foreground call is ACTIVE or IDLE or DISCONNECTED. 2004 // (We mainly need to make sure it *isn't* DIALING or ALERTING.) 2005 final boolean hasRingingCall = !phone.getRingingCall().isIdle(); 2006 final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); 2007 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); 2008 final boolean allLinesTaken = hasActiveCall && hasHoldingCall; 2009 2010 return !hasRingingCall 2011 && !allLinesTaken 2012 && ((fgCallState == Call.State.ACTIVE) 2013 || (fgCallState == Call.State.IDLE) 2014 || (fgCallState == Call.State.DISCONNECTED)); 2015 } else { 2016 throw new IllegalStateException("Unexpected phone type: " + phoneType); 2017 } 2018 } 2019 2020 /** 2021 * Based on the input CNAP number string, 2022 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings. 2023 * Otherwise, return CNAP_SPECIAL_CASE_NO. 2024 */ 2025 private static int checkCnapSpecialCases(String n) { 2026 if (n.equals("PRIVATE") || 2027 n.equals("P") || 2028 n.equals("RES")) { 2029 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n); 2030 return Connection.PRESENTATION_RESTRICTED; 2031 } else if (n.equals("UNAVAILABLE") || 2032 n.equals("UNKNOWN") || 2033 n.equals("UNA") || 2034 n.equals("U")) { 2035 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n); 2036 return Connection.PRESENTATION_UNKNOWN; 2037 } else { 2038 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n); 2039 return CNAP_SPECIAL_CASE_NO; 2040 } 2041 } 2042 2043 /** 2044 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers 2045 * from the network to indicate different number presentations, convert them to 2046 * expected number and presentation values within the CallerInfo object. 2047 * @param number number we use to verify if we are in a corner case 2048 * @param presentation presentation value used to verify if we are in a corner case 2049 * @return the new String that should be used for the phone number 2050 */ 2051 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci, 2052 String number, int presentation) { 2053 // Obviously we return number if ci == null, but still return number if 2054 // number == null, because in these cases the correct string will still be 2055 // displayed/logged after this function returns based on the presentation value. 2056 if (ci == null || number == null) return number; 2057 2058 if (DBG) log("modifyForSpecialCnapCases: initially, number=" + number 2059 + ", presentation=" + presentation + " ci " + ci); 2060 2061 // "ABSENT NUMBER" is a possible value we could get from the network as the 2062 // phone number, so if this happens, change it to "Unknown" in the CallerInfo 2063 // and fix the presentation to be the same. 2064 if (number.equals(context.getString(R.string.absent_num)) 2065 && presentation == Connection.PRESENTATION_ALLOWED) { 2066 number = context.getString(R.string.unknown); 2067 ci.numberPresentation = Connection.PRESENTATION_UNKNOWN; 2068 } 2069 2070 // Check for other special "corner cases" for CNAP and fix them similarly. Corner 2071 // cases only apply if we received an allowed presentation from the network, so check 2072 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't 2073 // match the presentation passed in for verification (meaning we changed it previously 2074 // because it's a corner case and we're being called from a different entry point). 2075 if (ci.numberPresentation == Connection.PRESENTATION_ALLOWED 2076 || (ci.numberPresentation != presentation 2077 && presentation == Connection.PRESENTATION_ALLOWED)) { 2078 int cnapSpecialCase = checkCnapSpecialCases(number); 2079 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) { 2080 // For all special strings, change number & numberPresentation. 2081 if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) { 2082 number = context.getString(R.string.private_num); 2083 } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) { 2084 number = context.getString(R.string.unknown); 2085 } 2086 if (DBG) log("SpecialCnap: number=" + number 2087 + "; presentation now=" + cnapSpecialCase); 2088 ci.numberPresentation = cnapSpecialCase; 2089 } 2090 } 2091 if (DBG) log("modifyForSpecialCnapCases: returning number string=" + number); 2092 return number; 2093 } 2094 2095 // 2096 // Support for 3rd party phone service providers. 2097 // 2098 2099 /** 2100 * Check if all the provider's info is present in the intent. 2101 * @param intent Expected to have the provider's extra. 2102 * @return true if the intent has all the extras to build the 2103 * in-call screen's provider info overlay. 2104 */ 2105 /* package */ static boolean hasPhoneProviderExtras(Intent intent) { 2106 if (null == intent) { 2107 return false; 2108 } 2109 final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2110 final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); 2111 2112 return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri); 2113 } 2114 2115 /** 2116 * Copy all the expected extras set when a 3rd party provider is 2117 * used from the source intent to the destination one. Checks all 2118 * the required extras are present, if any is missing, none will 2119 * be copied. 2120 * @param src Intent which may contain the provider's extras. 2121 * @param dst Intent where a copy of the extras will be added if applicable. 2122 */ 2123 /* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) { 2124 if (!hasPhoneProviderExtras(src)) { 2125 Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing."); 2126 return; 2127 } 2128 2129 dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE, 2130 src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE)); 2131 dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI, 2132 src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI)); 2133 } 2134 2135 /** 2136 * Get the provider's label from the intent. 2137 * @param context to lookup the provider's package name. 2138 * @param intent with an extra set to the provider's package name. 2139 * @return The provider's application label. null if an error 2140 * occurred during the lookup of the package name or the label. 2141 */ 2142 /* package */ static CharSequence getProviderLabel(Context context, Intent intent) { 2143 String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2144 PackageManager pm = context.getPackageManager(); 2145 2146 try { 2147 ApplicationInfo info = pm.getApplicationInfo(packageName, 0); 2148 2149 return pm.getApplicationLabel(info); 2150 } catch (PackageManager.NameNotFoundException e) { 2151 return null; 2152 } 2153 } 2154 2155 /** 2156 * Get the provider's icon. 2157 * @param context to lookup the provider's icon. 2158 * @param intent with an extra set to the provider's package name. 2159 * @return The provider's application icon. null if an error occured during the icon lookup. 2160 */ 2161 /* package */ static Drawable getProviderIcon(Context context, Intent intent) { 2162 String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2163 PackageManager pm = context.getPackageManager(); 2164 2165 try { 2166 return pm.getApplicationIcon(packageName); 2167 } catch (PackageManager.NameNotFoundException e) { 2168 return null; 2169 } 2170 } 2171 2172 /** 2173 * Return the gateway uri from the intent. 2174 * @param intent With the gateway uri extra. 2175 * @return The gateway URI or null if not found. 2176 */ 2177 /* package */ static Uri getProviderGatewayUri(Intent intent) { 2178 String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); 2179 return TextUtils.isEmpty(uri) ? null : Uri.parse(uri); 2180 } 2181 2182 /** 2183 * Return a formatted version of the uri's scheme specific 2184 * part. E.g for 'tel:12345678', return '1-234-5678'. 2185 * @param uri A 'tel:' URI with the gateway phone number. 2186 * @return the provider's address (from the gateway uri) formatted 2187 * for user display. null if uri was null or its scheme was not 'tel:'. 2188 */ 2189 /* package */ static String formatProviderUri(Uri uri) { 2190 if (null != uri) { 2191 if ("tel".equals(uri.getScheme())) { 2192 return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart()); 2193 } else { 2194 return uri.toString(); 2195 } 2196 } 2197 return null; 2198 } 2199 2200 /** 2201 * Check if a phone number can be route through a 3rd party 2202 * gateway. The number must be a global phone number in numerical 2203 * form (1-800-666-SEXY won't work). 2204 * 2205 * MMI codes and the like cannot be used as a dial number for the 2206 * gateway either. 2207 * 2208 * @param number To be dialed via a 3rd party gateway. 2209 * @return true If the number can be routed through the 3rd party network. 2210 */ 2211 /* package */ static boolean isRoutableViaGateway(String number) { 2212 if (TextUtils.isEmpty(number)) { 2213 return false; 2214 } 2215 number = PhoneNumberUtils.stripSeparators(number); 2216 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) { 2217 return false; 2218 } 2219 number = PhoneNumberUtils.extractNetworkPortion(number); 2220 return PhoneNumberUtils.isGlobalPhoneNumber(number); 2221 } 2222 2223 /** 2224 * This function is called when phone answers or places a call. 2225 * Check if the phone is in a car dock or desk dock. 2226 * If yes, turn on the speaker, when no wired or BT headsets are connected. 2227 * Otherwise do nothing. 2228 */ 2229 private static void activateSpeakerIfDocked(Phone phone) { 2230 if (DBG) log("activateSpeakerIfDocked()..."); 2231 2232 if (PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_DESK || 2233 PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_CAR) { 2234 if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker."); 2235 PhoneApp app = PhoneApp.getInstance(); 2236 BluetoothHandsfree bthf = app.getBluetoothHandsfree(); 2237 2238 if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) { 2239 turnOnSpeaker(phone.getContext(), true, true); 2240 } 2241 } 2242 } 2243 2244 2245 /** 2246 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not. 2247 * (For non-CDMA phones, this will always return false. 2248 * For CDMA Phones, return true iff PROPERTY_INECM_MODE == "true".) 2249 */ 2250 /* package */ static boolean isPhoneInEcm(Phone phone) { 2251 boolean phoneInEcm = false; 2252 if ((phone != null) && (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA)) { 2253 String ecmMode = 2254 SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE); 2255 if (ecmMode != null) { 2256 phoneInEcm = ecmMode.equals("true"); 2257 } 2258 } 2259 return phoneInEcm; 2260 } 2261 2262 2263 // 2264 // General phone and call state debugging/testing code 2265 // 2266 2267 /* package */ static void dumpCallState(Phone phone) { 2268 PhoneApp app = PhoneApp.getInstance(); 2269 Log.d(LOG_TAG, "dumpCallState():"); 2270 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName() 2271 + ", state = " + phone.getState()); 2272 2273 StringBuilder b = new StringBuilder(128); 2274 2275 Call call = phone.getForegroundCall(); 2276 b.setLength(0); 2277 b.append(" - FG call: ").append(call.getState()); 2278 b.append(" isAlive ").append(call.getState().isAlive()); 2279 b.append(" isRinging ").append(call.getState().isRinging()); 2280 b.append(" isDialing ").append(call.getState().isDialing()); 2281 b.append(" isIdle ").append(call.isIdle()); 2282 b.append(" hasConnections ").append(call.hasConnections()); 2283 Log.d(LOG_TAG, b.toString()); 2284 2285 call = phone.getBackgroundCall(); 2286 b.setLength(0); 2287 b.append(" - BG call: ").append(call.getState()); 2288 b.append(" isAlive ").append(call.getState().isAlive()); 2289 b.append(" isRinging ").append(call.getState().isRinging()); 2290 b.append(" isDialing ").append(call.getState().isDialing()); 2291 b.append(" isIdle ").append(call.isIdle()); 2292 b.append(" hasConnections ").append(call.hasConnections()); 2293 Log.d(LOG_TAG, b.toString()); 2294 2295 call = phone.getRingingCall(); 2296 b.setLength(0); 2297 b.append(" - RINGING call: ").append(call.getState()); 2298 b.append(" isAlive ").append(call.getState().isAlive()); 2299 b.append(" isRinging ").append(call.getState().isRinging()); 2300 b.append(" isDialing ").append(call.getState().isDialing()); 2301 b.append(" isIdle ").append(call.isIdle()); 2302 b.append(" hasConnections ").append(call.hasConnections()); 2303 Log.d(LOG_TAG, b.toString()); 2304 2305 2306 final boolean hasRingingCall = !phone.getRingingCall().isIdle(); 2307 final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); 2308 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); 2309 final boolean allLinesTaken = hasActiveCall && hasHoldingCall; 2310 b.setLength(0); 2311 b.append(" - hasRingingCall ").append(hasRingingCall); 2312 b.append(" hasActiveCall ").append(hasActiveCall); 2313 b.append(" hasHoldingCall ").append(hasHoldingCall); 2314 b.append(" allLinesTaken ").append(allLinesTaken); 2315 Log.d(LOG_TAG, b.toString()); 2316 2317 // On CDMA phones, dump out the CdmaPhoneCallState too: 2318 if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { 2319 if (app.cdmaPhoneCallState != null) { 2320 Log.d(LOG_TAG, " - CDMA call state: " 2321 + app.cdmaPhoneCallState.getCurrentCallState()); 2322 } else { 2323 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!"); 2324 } 2325 } 2326 2327 // Watch out: the isRinging() call below does NOT tell us anything 2328 // about the state of the telephony layer; it merely tells us whether 2329 // the Ringer manager is currently playing the ringtone. 2330 boolean ringing = app.getRinger().isRinging(); 2331 Log.d(LOG_TAG, " - Ringer state: " + ringing); 2332 } 2333 2334 private static void log(String msg) { 2335 Log.d(LOG_TAG, msg); 2336 } 2337} 2338