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