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