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