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