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