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