PhoneUtils.java revision 84e032e3b5cc9c9702a305103c9591e8c79f1a1a
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.phone; 18 19import android.app.AlertDialog; 20import android.app.Dialog; 21import android.app.ProgressDialog; 22import android.content.ActivityNotFoundException; 23import android.content.ComponentName; 24import android.content.Context; 25import android.content.DialogInterface; 26import android.content.Intent; 27import android.content.ServiceConnection; 28import android.content.pm.ApplicationInfo; 29import android.content.pm.PackageManager; 30import android.graphics.drawable.Drawable; 31import android.media.AudioManager; 32import android.net.Uri; 33import android.net.sip.SipManager; 34import android.os.AsyncResult; 35import android.os.AsyncTask; 36import android.os.Handler; 37import android.os.IBinder; 38import android.os.Message; 39import android.os.RemoteException; 40import android.os.SystemProperties; 41import android.provider.ContactsContract; 42import android.provider.Settings; 43import android.telephony.PhoneNumberUtils; 44import android.text.TextUtils; 45import android.util.Log; 46import android.view.KeyEvent; 47import android.view.LayoutInflater; 48import android.view.View; 49import android.view.WindowManager; 50import android.widget.EditText; 51import android.widget.Toast; 52 53import com.android.internal.telephony.Call; 54import com.android.internal.telephony.CallManager; 55import com.android.internal.telephony.CallStateException; 56import com.android.internal.telephony.CallerInfo; 57import com.android.internal.telephony.CallerInfoAsyncQuery; 58import com.android.internal.telephony.Connection; 59import com.android.internal.telephony.IExtendedNetworkService; 60import com.android.internal.telephony.MmiCode; 61import com.android.internal.telephony.Phone; 62import com.android.internal.telephony.TelephonyCapabilities; 63import com.android.internal.telephony.TelephonyProperties; 64import com.android.internal.telephony.cdma.CdmaConnection; 65import com.android.internal.telephony.sip.SipPhone; 66 67import java.util.ArrayList; 68import java.util.Hashtable; 69import java.util.Iterator; 70import java.util.List; 71 72/** 73 * Misc utilities for the Phone app. 74 */ 75public 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 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 */ 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. */ 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 */ 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 */ 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 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 420 static boolean hangupActiveCall(Call foreground) { 421 if (DBG) log("hangup active call"); 422 return hangup(foreground); 423 } 424 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 */ 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 */ 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 */ 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 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 */ 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 */ 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 */ 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 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 */ 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 */ 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 */ 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 847 static void mergeCalls() { 848 mergeCalls(PhoneApp.getInstance().mCM); 849 } 850 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 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 */ 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 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 954 pd.show(); 955 // trigger a 15 seconds timeout to clear this progress dialog 956 mMmiTimeoutCbMsg = buttonCallbackMessage; 957 try { 958 mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000); 959 } catch(NullPointerException e) { 960 mMmiTimeoutCbMsg = null; 961 } 962 return pd; 963 } 964 965 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable(); 966 967 if (!isCancelable) { 968 if (DBG) log("not a USSD code, displaying status toast."); 969 CharSequence text = context.getText(R.string.mmiStarted); 970 Toast.makeText(context, text, Toast.LENGTH_SHORT) 971 .show(); 972 return null; 973 } else { 974 if (DBG) log("running USSD code, displaying indeterminate progress."); 975 976 // create the indeterminate progress dialog and display it. 977 ProgressDialog pd = new ProgressDialog(context); 978 pd.setMessage(context.getText(R.string.ussdRunning)); 979 pd.setCancelable(false); 980 pd.setIndeterminate(true); 981 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); 982 983 pd.show(); 984 985 return pd; 986 } 987 988 } 989 990 /** 991 * Handle the MMIComplete message and fire off an intent to display 992 * the message. 993 * 994 * @param context context to get strings. 995 * @param mmiCode MMI result. 996 * @param previousAlert a previous alert used in this activity. 997 */ 998 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode, 999 Message dismissCallbackMessage, 1000 AlertDialog previousAlert) { 1001 final PhoneApp app = PhoneApp.getInstance(); 1002 CharSequence text; 1003 int title = 0; // title for the progress dialog, if needed. 1004 MmiCode.State state = mmiCode.getState(); 1005 1006 if (DBG) log("displayMMIComplete: state=" + state); 1007 // Clear timeout trigger message 1008 if(mMmiTimeoutCbMsg != null) { 1009 try{ 1010 mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what); 1011 if (DBG) log("Extended NW displayMMIComplete removeMsg"); 1012 } catch (NullPointerException e) { 1013 } 1014 mMmiTimeoutCbMsg = null; 1015 } 1016 1017 1018 switch (state) { 1019 case PENDING: 1020 // USSD code asking for feedback from user. 1021 text = mmiCode.getMessage(); 1022 if (DBG) log("- using text from PENDING MMI message: '" + text + "'"); 1023 break; 1024 case CANCELLED: 1025 text = context.getText(R.string.mmiCancelled); 1026 break; 1027 case COMPLETE: 1028 if (app.getPUKEntryActivity() != null) { 1029 // if an attempt to unPUK the device was made, we specify 1030 // the title and the message here. 1031 title = com.android.internal.R.string.PinMmi; 1032 text = context.getText(R.string.puk_unlocked); 1033 break; 1034 } 1035 // All other conditions for the COMPLETE mmi state will cause 1036 // the case to fall through to message logic in common with 1037 // the FAILED case. 1038 1039 case FAILED: 1040 text = mmiCode.getMessage(); 1041 if (DBG) log("- using text from MMI message: '" + text + "'"); 1042 break; 1043 default: 1044 throw new IllegalStateException("Unexpected MmiCode state: " + state); 1045 } 1046 1047 if (previousAlert != null) { 1048 previousAlert.dismiss(); 1049 } 1050 1051 // Check to see if a UI exists for the PUK activation. If it does 1052 // exist, then it indicates that we're trying to unblock the PUK. 1053 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) { 1054 if (DBG) log("displaying PUK unblocking progress dialog."); 1055 1056 // create the progress dialog, make sure the flags and type are 1057 // set correctly. 1058 ProgressDialog pd = new ProgressDialog(app); 1059 pd.setTitle(title); 1060 pd.setMessage(text); 1061 pd.setCancelable(false); 1062 pd.setIndeterminate(true); 1063 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 1064 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); 1065 1066 // display the dialog 1067 pd.show(); 1068 1069 // indicate to the Phone app that the progress dialog has 1070 // been assigned for the PUK unlock / SIM READY process. 1071 app.setPukEntryProgressDialog(pd); 1072 1073 } else { 1074 // In case of failure to unlock, we'll need to reset the 1075 // PUK unlock activity, so that the user may try again. 1076 if (app.getPUKEntryActivity() != null) { 1077 app.setPukEntryActivity(null); 1078 } 1079 1080 // A USSD in a pending state means that it is still 1081 // interacting with the user. 1082 if (state != MmiCode.State.PENDING) { 1083 if (DBG) log("MMI code has finished running."); 1084 1085 // Replace response message with Extended Mmi wording 1086 if (mNwService != null) { 1087 try { 1088 text = mNwService.getUserMessage(text); 1089 } catch (RemoteException e) { 1090 mNwService = null; 1091 } 1092 if (DBG) log("Extended NW displayMMIInitiate (" + text + ")"); 1093 if (text == null || text.length() == 0) 1094 return; 1095 } 1096 1097 // displaying system alert dialog on the screen instead of 1098 // using another activity to display the message. This 1099 // places the message at the forefront of the UI. 1100 AlertDialog newDialog = new AlertDialog.Builder(context) 1101 .setMessage(text) 1102 .setPositiveButton(R.string.ok, null) 1103 .setCancelable(true) 1104 .create(); 1105 1106 newDialog.getWindow().setType( 1107 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 1108 newDialog.getWindow().addFlags( 1109 WindowManager.LayoutParams.FLAG_DIM_BEHIND); 1110 1111 newDialog.show(); 1112 } else { 1113 if (DBG) log("USSD code has requested user input. Constructing input dialog."); 1114 1115 // USSD MMI code that is interacting with the user. The 1116 // basic set of steps is this: 1117 // 1. User enters a USSD request 1118 // 2. We recognize the request and displayMMIInitiate 1119 // (above) creates a progress dialog. 1120 // 3. Request returns and we get a PENDING or COMPLETE 1121 // message. 1122 // 4. These MMI messages are caught in the PhoneApp 1123 // (onMMIComplete) and the InCallScreen 1124 // (mHandler.handleMessage) which bring up this dialog 1125 // and closes the original progress dialog, 1126 // respectively. 1127 // 5. If the message is anything other than PENDING, 1128 // we are done, and the alert dialog (directly above) 1129 // displays the outcome. 1130 // 6. If the network is requesting more information from 1131 // the user, the MMI will be in a PENDING state, and 1132 // we display this dialog with the message. 1133 // 7. User input, or cancel requests result in a return 1134 // to step 1. Keep in mind that this is the only 1135 // time that a USSD should be canceled. 1136 1137 // inflate the layout with the scrolling text area for the dialog. 1138 LayoutInflater inflater = (LayoutInflater) context.getSystemService( 1139 Context.LAYOUT_INFLATER_SERVICE); 1140 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null); 1141 1142 // get the input field. 1143 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field); 1144 1145 // specify the dialog's click listener, with SEND and CANCEL logic. 1146 final DialogInterface.OnClickListener mUSSDDialogListener = 1147 new DialogInterface.OnClickListener() { 1148 public void onClick(DialogInterface dialog, int whichButton) { 1149 switch (whichButton) { 1150 case DialogInterface.BUTTON_POSITIVE: 1151 phone.sendUssdResponse(inputText.getText().toString()); 1152 break; 1153 case DialogInterface.BUTTON_NEGATIVE: 1154 if (mmiCode.isCancelable()) { 1155 mmiCode.cancel(); 1156 } 1157 break; 1158 } 1159 } 1160 }; 1161 1162 // build the dialog 1163 final AlertDialog newDialog = new AlertDialog.Builder(context) 1164 .setMessage(text) 1165 .setView(dialogView) 1166 .setPositiveButton(R.string.send_button, mUSSDDialogListener) 1167 .setNegativeButton(R.string.cancel, mUSSDDialogListener) 1168 .setCancelable(false) 1169 .create(); 1170 1171 // attach the key listener to the dialog's input field and make 1172 // sure focus is set. 1173 final View.OnKeyListener mUSSDDialogInputListener = 1174 new View.OnKeyListener() { 1175 public boolean onKey(View v, int keyCode, KeyEvent event) { 1176 switch (keyCode) { 1177 case KeyEvent.KEYCODE_CALL: 1178 case KeyEvent.KEYCODE_ENTER: 1179 if(event.getAction() == KeyEvent.ACTION_DOWN) { 1180 phone.sendUssdResponse(inputText.getText().toString()); 1181 newDialog.dismiss(); 1182 } 1183 return true; 1184 } 1185 return false; 1186 } 1187 }; 1188 inputText.setOnKeyListener(mUSSDDialogInputListener); 1189 inputText.requestFocus(); 1190 1191 // set the window properties of the dialog 1192 newDialog.getWindow().setType( 1193 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 1194 newDialog.getWindow().addFlags( 1195 WindowManager.LayoutParams.FLAG_DIM_BEHIND); 1196 1197 // now show the dialog! 1198 newDialog.show(); 1199 } 1200 } 1201 } 1202 1203 /** 1204 * Cancels the current pending MMI operation, if applicable. 1205 * @return true if we canceled an MMI operation, or false 1206 * if the current pending MMI wasn't cancelable 1207 * or if there was no current pending MMI at all. 1208 * 1209 * @see displayMMIInitiate 1210 */ 1211 static boolean cancelMmiCode(Phone phone) { 1212 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes(); 1213 int count = pendingMmis.size(); 1214 if (DBG) log("cancelMmiCode: num pending MMIs = " + count); 1215 1216 boolean canceled = false; 1217 if (count > 0) { 1218 // assume that we only have one pending MMI operation active at a time. 1219 // I don't think it's possible to enter multiple MMI codes concurrently 1220 // in the phone UI, because during the MMI operation, an Alert panel 1221 // is displayed, which prevents more MMI code from being entered. 1222 MmiCode mmiCode = pendingMmis.get(0); 1223 if (mmiCode.isCancelable()) { 1224 mmiCode.cancel(); 1225 canceled = true; 1226 } 1227 } 1228 1229 //clear timeout message and pre-set MMI command 1230 if (mNwService != null) { 1231 try { 1232 mNwService.clearMmiString(); 1233 } catch (RemoteException e) { 1234 mNwService = null; 1235 } 1236 } 1237 if (mMmiTimeoutCbMsg != null) { 1238 mMmiTimeoutCbMsg = null; 1239 } 1240 return canceled; 1241 } 1242 1243 public static class VoiceMailNumberMissingException extends Exception { 1244 VoiceMailNumberMissingException() { 1245 super(); 1246 } 1247 1248 VoiceMailNumberMissingException(String msg) { 1249 super(msg); 1250 } 1251 } 1252 1253 /** 1254 * Given an Intent (which is presumably the ACTION_CALL intent that 1255 * initiated this outgoing call), figure out the actual phone number we 1256 * should dial. 1257 * 1258 * Note that the returned "number" may actually be a SIP address, 1259 * if the specified intent contains a sip: URI. 1260 * 1261 * This method is basically a wrapper around PhoneUtils.getNumberFromIntent(), 1262 * except it's also aware of the EXTRA_ACTUAL_NUMBER_TO_DIAL extra. 1263 * (That extra, if present, tells us the exact string to pass down to the 1264 * telephony layer. It's guaranteed to be safe to dial: it's either a PSTN 1265 * phone number with separators and keypad letters stripped out, or a raw 1266 * unencoded SIP address.) 1267 * 1268 * @return the phone number corresponding to the specified Intent, or null 1269 * if the Intent has no action or if the intent's data is malformed or 1270 * missing. 1271 * 1272 * @throws VoiceMailNumberMissingException if the intent 1273 * contains a "voicemail" URI, but there's no voicemail 1274 * number configured on the device. 1275 */ 1276 public static String getInitialNumber(Intent intent) 1277 throws PhoneUtils.VoiceMailNumberMissingException { 1278 if (DBG) log("getInitialNumber(): " + intent); 1279 1280 String action = intent.getAction(); 1281 if (TextUtils.isEmpty(action)) { 1282 return null; 1283 } 1284 1285 // If the EXTRA_ACTUAL_NUMBER_TO_DIAL extra is present, get the phone 1286 // number from there. (That extra takes precedence over the actual data 1287 // included in the intent.) 1288 if (intent.hasExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL)) { 1289 String actualNumberToDial = 1290 intent.getStringExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL); 1291 if (DBG) { 1292 log("==> got EXTRA_ACTUAL_NUMBER_TO_DIAL; returning '" 1293 + toLogSafePhoneNumber(actualNumberToDial) + "'"); 1294 } 1295 return actualNumberToDial; 1296 } 1297 1298 return getNumberFromIntent(PhoneApp.getInstance(), intent); 1299 } 1300 1301 /** 1302 * Gets the phone number to be called from an intent. Requires a Context 1303 * to access the contacts database, and a Phone to access the voicemail 1304 * number. 1305 * 1306 * <p>If <code>phone</code> is <code>null</code>, the function will return 1307 * <code>null</code> for <code>voicemail:</code> URIs; 1308 * if <code>context</code> is <code>null</code>, the function will return 1309 * <code>null</code> for person/phone URIs.</p> 1310 * 1311 * <p>If the intent contains a <code>sip:</code> URI, the returned 1312 * "number" is actually the SIP address. 1313 * 1314 * @param context a context to use (or 1315 * @param intent the intent 1316 * 1317 * @throws VoiceMailNumberMissingException if <code>intent</code> contains 1318 * a <code>voicemail:</code> URI, but <code>phone</code> does not 1319 * have a voicemail number set. 1320 * 1321 * @return the phone number (or SIP address) that would be called by the intent, 1322 * or <code>null</code> if the number cannot be found. 1323 */ 1324 private static String getNumberFromIntent(Context context, Intent intent) 1325 throws VoiceMailNumberMissingException { 1326 Uri uri = intent.getData(); 1327 String scheme = uri.getScheme(); 1328 1329 // The sip: scheme is simple: just treat the rest of the URI as a 1330 // SIP address. 1331 if (Constants.SCHEME_SIP.equals(scheme)) { 1332 return uri.getSchemeSpecificPart(); 1333 } 1334 1335 // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle 1336 // the other cases (i.e. tel: and voicemail: and contact: URIs.) 1337 1338 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context); 1339 1340 // Check for a voicemail-dialing request. If the voicemail number is 1341 // empty, throw a VoiceMailNumberMissingException. 1342 if (Constants.SCHEME_VOICEMAIL.equals(scheme) && 1343 (number == null || TextUtils.isEmpty(number))) 1344 throw new VoiceMailNumberMissingException(); 1345 1346 return number; 1347 } 1348 1349 /** 1350 * Returns the caller-id info corresponding to the specified Connection. 1351 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we 1352 * extract a phone number from the specified Connection, and feed that 1353 * number into CallerInfo.getCallerInfo().) 1354 * 1355 * The returned CallerInfo may be null in certain error cases, like if the 1356 * specified Connection was null, or if we weren't able to get a valid 1357 * phone number from the Connection. 1358 * 1359 * Finally, if the getCallerInfo() call did succeed, we save the resulting 1360 * CallerInfo object in the "userData" field of the Connection. 1361 * 1362 * NOTE: This API should be avoided, with preference given to the 1363 * asynchronous startGetCallerInfo API. 1364 */ 1365 static CallerInfo getCallerInfo(Context context, Connection c) { 1366 CallerInfo info = null; 1367 1368 if (c != null) { 1369 //See if there is a URI attached. If there is, this means 1370 //that there is no CallerInfo queried yet, so we'll need to 1371 //replace the URI with a full CallerInfo object. 1372 Object userDataObject = c.getUserData(); 1373 if (userDataObject instanceof Uri) { 1374 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject); 1375 if (info != null) { 1376 c.setUserData(info); 1377 } 1378 } else { 1379 if (userDataObject instanceof CallerInfoToken) { 1380 //temporary result, while query is running 1381 info = ((CallerInfoToken) userDataObject).currentInfo; 1382 } else { 1383 //final query result 1384 info = (CallerInfo) userDataObject; 1385 } 1386 if (info == null) { 1387 // No URI, or Existing CallerInfo, so we'll have to make do with 1388 // querying a new CallerInfo using the connection's phone number. 1389 String number = c.getAddress(); 1390 1391 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number)); 1392 1393 if (!TextUtils.isEmpty(number)) { 1394 info = CallerInfo.getCallerInfo(context, number); 1395 if (info != null) { 1396 c.setUserData(info); 1397 } 1398 } 1399 } 1400 } 1401 } 1402 return info; 1403 } 1404 1405 /** 1406 * Class returned by the startGetCallerInfo call to package a temporary 1407 * CallerInfo Object, to be superceded by the CallerInfo Object passed 1408 * into the listener when the query with token mAsyncQueryToken is complete. 1409 */ 1410 public static class CallerInfoToken { 1411 /**indicates that there will no longer be updates to this request.*/ 1412 public boolean isFinal; 1413 1414 public CallerInfo currentInfo; 1415 public CallerInfoAsyncQuery asyncQuery; 1416 } 1417 1418 /** 1419 * Start a CallerInfo Query based on the earliest connection in the call. 1420 */ 1421 static CallerInfoToken startGetCallerInfo(Context context, Call call, 1422 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { 1423 Connection conn = null; 1424 int phoneType = call.getPhone().getPhoneType(); 1425 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1426 conn = call.getLatestConnection(); 1427 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 1428 || (phoneType == Phone.PHONE_TYPE_SIP)) { 1429 conn = call.getEarliestConnection(); 1430 } else { 1431 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1432 } 1433 1434 return startGetCallerInfo(context, conn, listener, cookie); 1435 } 1436 1437 /** 1438 * place a temporary callerinfo object in the hands of the caller and notify 1439 * caller when the actual query is done. 1440 */ 1441 static CallerInfoToken startGetCallerInfo(Context context, Connection c, 1442 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { 1443 CallerInfoToken cit; 1444 1445 if (c == null) { 1446 //TODO: perhaps throw an exception here. 1447 cit = new CallerInfoToken(); 1448 cit.asyncQuery = null; 1449 return cit; 1450 } 1451 1452 Object userDataObject = c.getUserData(); 1453 1454 // There are now 3 states for the Connection's userData object: 1455 // 1456 // (1) Uri - query has not been executed yet 1457 // 1458 // (2) CallerInfoToken - query is executing, but has not completed. 1459 // 1460 // (3) CallerInfo - query has executed. 1461 // 1462 // In each case we have slightly different behaviour: 1463 // 1. If the query has not been executed yet (Uri or null), we start 1464 // query execution asynchronously, and note it by attaching a 1465 // CallerInfoToken as the userData. 1466 // 2. If the query is executing (CallerInfoToken), we've essentially 1467 // reached a state where we've received multiple requests for the 1468 // same callerInfo. That means that once the query is complete, 1469 // we'll need to execute the additional listener requested. 1470 // 3. If the query has already been executed (CallerInfo), we just 1471 // return the CallerInfo object as expected. 1472 // 4. Regarding isFinal - there are cases where the CallerInfo object 1473 // will not be attached, like when the number is empty (caller id 1474 // blocking). This flag is used to indicate that the 1475 // CallerInfoToken object is going to be permanent since no 1476 // query results will be returned. In the case where a query 1477 // has been completed, this flag is used to indicate to the caller 1478 // that the data will not be updated since it is valid. 1479 // 1480 // Note: For the case where a number is NOT retrievable, we leave 1481 // the CallerInfo as null in the CallerInfoToken. This is 1482 // something of a departure from the original code, since the old 1483 // code manufactured a CallerInfo object regardless of the query 1484 // outcome. From now on, we will append an empty CallerInfo 1485 // object, to mirror previous behaviour, and to avoid Null Pointer 1486 // Exceptions. 1487 1488 if (userDataObject instanceof Uri) { 1489 // State (1): query has not been executed yet 1490 1491 //create a dummy callerinfo, populate with what we know from URI. 1492 cit = new CallerInfoToken(); 1493 cit.currentInfo = new CallerInfo(); 1494 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1495 (Uri) userDataObject, sCallerInfoQueryListener, c); 1496 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1497 cit.isFinal = false; 1498 1499 c.setUserData(cit); 1500 1501 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject); 1502 1503 } else if (userDataObject == null) { 1504 // No URI, or Existing CallerInfo, so we'll have to make do with 1505 // querying a new CallerInfo using the connection's phone number. 1506 String number = c.getAddress(); 1507 1508 if (DBG) { 1509 log("PhoneUtils.startGetCallerInfo: new query for phone number..."); 1510 log("- number (address): " + toLogSafePhoneNumber(number)); 1511 log("- c: " + c); 1512 log("- phone: " + c.getCall().getPhone()); 1513 int phoneType = c.getCall().getPhone().getPhoneType(); 1514 log("- phoneType: " + phoneType); 1515 switch (phoneType) { 1516 case Phone.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break; 1517 case Phone.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break; 1518 case Phone.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break; 1519 case Phone.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break; 1520 default: log(" ==> Unknown phone type"); break; 1521 } 1522 } 1523 1524 cit = new CallerInfoToken(); 1525 cit.currentInfo = new CallerInfo(); 1526 1527 // Store CNAP information retrieved from the Connection (we want to do this 1528 // here regardless of whether the number is empty or not). 1529 cit.currentInfo.cnapName = c.getCnapName(); 1530 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten 1531 // by ContactInfo later 1532 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1533 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1534 1535 if (VDBG) { 1536 log("startGetCallerInfo: number = " + number); 1537 log("startGetCallerInfo: CNAP Info from FW(1): name=" 1538 + cit.currentInfo.cnapName 1539 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1540 } 1541 1542 // handling case where number is null (caller id hidden) as well. 1543 if (!TextUtils.isEmpty(number)) { 1544 // Check for special CNAP cases and modify the CallerInfo accordingly 1545 // to be sure we keep the right information to display/log later 1546 number = modifyForSpecialCnapCases(context, cit.currentInfo, number, 1547 cit.currentInfo.numberPresentation); 1548 1549 cit.currentInfo.phoneNumber = number; 1550 // For scenarios where we may receive a valid number from the network but a 1551 // restricted/unavailable presentation, we do not want to perform a contact query 1552 // (see note on isFinal above). So we set isFinal to true here as well. 1553 if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { 1554 cit.isFinal = true; 1555 } else { 1556 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()..."); 1557 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1558 number, sCallerInfoQueryListener, c); 1559 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1560 cit.isFinal = false; 1561 } 1562 } else { 1563 // This is the case where we are querying on a number that 1564 // is null or empty, like a caller whose caller id is 1565 // blocked or empty (CLIR). The previous behaviour was to 1566 // throw a null CallerInfo object back to the user, but 1567 // this departure is somewhat cleaner. 1568 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply."); 1569 cit.isFinal = true; // please see note on isFinal, above. 1570 } 1571 1572 c.setUserData(cit); 1573 1574 if (DBG) { 1575 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number)); 1576 } 1577 1578 } else if (userDataObject instanceof CallerInfoToken) { 1579 // State (2): query is executing, but has not completed. 1580 1581 // just tack on this listener to the queue. 1582 cit = (CallerInfoToken) userDataObject; 1583 1584 // handling case where number is null (caller id hidden) as well. 1585 if (cit.asyncQuery != null) { 1586 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1587 1588 if (DBG) log("startGetCallerInfo: query already running, adding listener: " + 1589 listener.getClass().toString()); 1590 } else { 1591 // handling case where number/name gets updated later on by the network 1592 String updatedNumber = c.getAddress(); 1593 if (DBG) { 1594 log("startGetCallerInfo: updatedNumber initially = " 1595 + toLogSafePhoneNumber(updatedNumber)); 1596 } 1597 if (!TextUtils.isEmpty(updatedNumber)) { 1598 // Store CNAP information retrieved from the Connection 1599 cit.currentInfo.cnapName = c.getCnapName(); 1600 // This can still get overwritten by ContactInfo 1601 cit.currentInfo.name = cit.currentInfo.cnapName; 1602 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1603 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1604 1605 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo, 1606 updatedNumber, cit.currentInfo.numberPresentation); 1607 1608 cit.currentInfo.phoneNumber = updatedNumber; 1609 if (DBG) { 1610 log("startGetCallerInfo: updatedNumber=" 1611 + toLogSafePhoneNumber(updatedNumber)); 1612 } 1613 if (VDBG) { 1614 log("startGetCallerInfo: CNAP Info from FW(2): name=" 1615 + cit.currentInfo.cnapName 1616 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1617 } else if (DBG) { 1618 log("startGetCallerInfo: CNAP Info from FW(2)"); 1619 } 1620 // For scenarios where we may receive a valid number from the network but a 1621 // restricted/unavailable presentation, we do not want to perform a contact query 1622 // (see note on isFinal above). So we set isFinal to true here as well. 1623 if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { 1624 cit.isFinal = true; 1625 } else { 1626 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1627 updatedNumber, sCallerInfoQueryListener, c); 1628 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1629 cit.isFinal = false; 1630 } 1631 } else { 1632 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply."); 1633 if (cit.currentInfo == null) { 1634 cit.currentInfo = new CallerInfo(); 1635 } 1636 // Store CNAP information retrieved from the Connection 1637 cit.currentInfo.cnapName = c.getCnapName(); // This can still get 1638 // overwritten by ContactInfo 1639 cit.currentInfo.name = cit.currentInfo.cnapName; 1640 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1641 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1642 1643 if (VDBG) { 1644 log("startGetCallerInfo: CNAP Info from FW(3): name=" 1645 + cit.currentInfo.cnapName 1646 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1647 } else if (DBG) { 1648 log("startGetCallerInfo: CNAP Info from FW(3)"); 1649 } 1650 cit.isFinal = true; // please see note on isFinal, above. 1651 } 1652 } 1653 } else { 1654 // State (3): query is complete. 1655 1656 // The connection's userDataObject is a full-fledged 1657 // CallerInfo instance. Wrap it in a CallerInfoToken and 1658 // return it to the user. 1659 1660 cit = new CallerInfoToken(); 1661 cit.currentInfo = (CallerInfo) userDataObject; 1662 cit.asyncQuery = null; 1663 cit.isFinal = true; 1664 // since the query is already done, call the listener. 1665 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo"); 1666 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo); 1667 } 1668 return cit; 1669 } 1670 1671 /** 1672 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that 1673 * we use with all our CallerInfoAsyncQuery.startQuery() requests. 1674 */ 1675 private static final int QUERY_TOKEN = -1; 1676 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener = 1677 new CallerInfoAsyncQuery.OnQueryCompleteListener () { 1678 /** 1679 * When the query completes, we stash the resulting CallerInfo 1680 * object away in the Connection's "userData" (where it will 1681 * later be retrieved by the in-call UI.) 1682 */ 1683 public void onQueryComplete(int token, Object cookie, CallerInfo ci) { 1684 if (DBG) log("query complete, updating connection.userdata"); 1685 Connection conn = (Connection) cookie; 1686 1687 // Added a check if CallerInfo is coming from ContactInfo or from Connection. 1688 // If no ContactInfo, then we want to use CNAP information coming from network 1689 if (DBG) log("- onQueryComplete: CallerInfo:" + ci); 1690 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) { 1691 // If the number presentation has not been set by 1692 // the ContactInfo, use the one from the 1693 // connection. 1694 1695 // TODO: Need a new util method to merge the info 1696 // from the Connection in a CallerInfo object. 1697 // Here 'ci' is a new CallerInfo instance read 1698 // from the DB. It has lost all the connection 1699 // info preset before the query (see PhoneUtils 1700 // line 1334). We should have a method to merge 1701 // back into this new instance the info from the 1702 // connection object not set by the DB. If the 1703 // Connection already has a CallerInfo instance in 1704 // userData, then we could use this instance to 1705 // fill 'ci' in. The same routine could be used in 1706 // PhoneUtils. 1707 if (0 == ci.numberPresentation) { 1708 ci.numberPresentation = conn.getNumberPresentation(); 1709 } 1710 } else { 1711 // No matching contact was found for this number. 1712 // Return a new CallerInfo based solely on the CNAP 1713 // information from the network. 1714 1715 CallerInfo newCi = getCallerInfo(null, conn); 1716 1717 // ...but copy over the (few) things we care about 1718 // from the original CallerInfo object: 1719 if (newCi != null) { 1720 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number 1721 newCi.geoDescription = ci.geoDescription; // To get geo description string 1722 ci = newCi; 1723 } 1724 } 1725 1726 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection..."); 1727 conn.setUserData(ci); 1728 } 1729 }; 1730 1731 1732 /** 1733 * Returns a single "name" for the specified given a CallerInfo object. 1734 * If the name is null, return defaultString as the default value, usually 1735 * context.getString(R.string.unknown). 1736 */ 1737 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) { 1738 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci); 1739 1740 String compactName = null; 1741 if (ci != null) { 1742 if (TextUtils.isEmpty(ci.name)) { 1743 // Perform any modifications for special CNAP cases to 1744 // the phone number being displayed, if applicable. 1745 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber, 1746 ci.numberPresentation); 1747 } else { 1748 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795. 1749 compactName = ci.name; 1750 } 1751 } 1752 1753 if ((compactName == null) || (TextUtils.isEmpty(compactName))) { 1754 // If we're still null/empty here, then check if we have a presentation 1755 // string that takes precedence that we could return, otherwise display 1756 // "unknown" string. 1757 if (ci != null && ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) { 1758 compactName = context.getString(R.string.private_num); 1759 } else if (ci != null && ci.numberPresentation == Connection.PRESENTATION_PAYPHONE) { 1760 compactName = context.getString(R.string.payphone); 1761 } else { 1762 compactName = context.getString(R.string.unknown); 1763 } 1764 } 1765 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName); 1766 return compactName; 1767 } 1768 1769 /** 1770 * Returns true if the specified Call is a "conference call", meaning 1771 * that it owns more than one Connection object. This information is 1772 * used to trigger certain UI changes that appear when a conference 1773 * call is active (like displaying the label "Conference call", and 1774 * enabling the "Manage conference" UI.) 1775 * 1776 * Watch out: This method simply checks the number of Connections, 1777 * *not* their states. So if a Call has (for example) one ACTIVE 1778 * connection and one DISCONNECTED connection, this method will return 1779 * true (which is unintuitive, since the Call isn't *really* a 1780 * conference call any more.) 1781 * 1782 * @return true if the specified call has more than one connection (in any state.) 1783 */ 1784 static boolean isConferenceCall(Call call) { 1785 // CDMA phones don't have the same concept of "conference call" as 1786 // GSM phones do; there's no special "conference call" state of 1787 // the UI or a "manage conference" function. (Instead, when 1788 // you're in a 3-way call, all we can do is display the "generic" 1789 // state of the UI.) So as far as the in-call UI is concerned, 1790 // Conference corresponds to generic display. 1791 final PhoneApp app = PhoneApp.getInstance(); 1792 int phoneType = call.getPhone().getPhoneType(); 1793 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1794 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState(); 1795 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL) 1796 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) 1797 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) { 1798 return true; 1799 } 1800 } else { 1801 List<Connection> connections = call.getConnections(); 1802 if (connections != null && connections.size() > 1) { 1803 return true; 1804 } 1805 } 1806 return false; 1807 1808 // TODO: We may still want to change the semantics of this method 1809 // to say that a given call is only really a conference call if 1810 // the number of ACTIVE connections, not the total number of 1811 // connections, is greater than one. (See warning comment in the 1812 // javadoc above.) 1813 // Here's an implementation of that: 1814 // if (connections == null) { 1815 // return false; 1816 // } 1817 // int numActiveConnections = 0; 1818 // for (Connection conn : connections) { 1819 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState()); 1820 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++; 1821 // if (numActiveConnections > 1) { 1822 // return true; 1823 // } 1824 // } 1825 // return false; 1826 } 1827 1828 /** 1829 * Launch the Dialer to start a new call. 1830 * This is just a wrapper around the ACTION_DIAL intent. 1831 */ 1832 /* package */ static boolean startNewCall(final CallManager cm) { 1833 final PhoneApp app = PhoneApp.getInstance(); 1834 1835 // Sanity-check that this is OK given the current state of the phone. 1836 if (!okToAddCall(cm)) { 1837 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state"); 1838 dumpCallManager(); 1839 return false; 1840 } 1841 1842 // if applicable, mute the call while we're showing the add call UI. 1843 if (cm.hasActiveFgCall()) { 1844 setMuteInternal(cm.getActiveFgCall().getPhone(), true); 1845 // Inform the phone app that this mute state was NOT done 1846 // voluntarily by the User. 1847 app.setRestoreMuteOnInCallResume(true); 1848 } 1849 1850 Intent intent = new Intent(Intent.ACTION_DIAL); 1851 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1852 1853 // when we request the dialer come up, we also want to inform 1854 // it that we're going through the "add call" option from the 1855 // InCallScreen / PhoneUtils. 1856 intent.putExtra(ADD_CALL_MODE_KEY, true); 1857 try { 1858 app.startActivity(intent); 1859 } catch (ActivityNotFoundException e) { 1860 // This is rather rare but possible. 1861 // Note: this method is used even when the phone is encrypted. At that moment 1862 // the system may not find any Activity which can accept this Intent. 1863 Log.e(LOG_TAG, "Activity for adding calls isn't found."); 1864 return false; 1865 } 1866 1867 return true; 1868 } 1869 1870 /** 1871 * Turns on/off speaker. 1872 * 1873 * @param context Context 1874 * @param flag True when speaker should be on. False otherwise. 1875 * @param store True when the settings should be stored in the device. 1876 */ 1877 /* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) { 1878 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")..."); 1879 final PhoneApp app = PhoneApp.getInstance(); 1880 1881 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1882 audioManager.setSpeakerphoneOn(flag); 1883 1884 // record the speaker-enable value 1885 if (store) { 1886 sIsSpeakerEnabled = flag; 1887 } 1888 1889 // Update the status bar icon 1890 app.notificationMgr.updateSpeakerNotification(flag); 1891 1892 // We also need to make a fresh call to PhoneApp.updateWakeState() 1893 // any time the speaker state changes, since the screen timeout is 1894 // sometimes different depending on whether or not the speaker is 1895 // in use. 1896 app.updateWakeState(); 1897 1898 // Update the Proximity sensor based on speaker state 1899 app.updateProximitySensorMode(app.mCM.getState()); 1900 1901 app.mCM.setEchoSuppressionEnabled(flag); 1902 } 1903 1904 /** 1905 * Restore the speaker mode, called after a wired headset disconnect 1906 * event. 1907 */ 1908 static void restoreSpeakerMode(Context context) { 1909 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled); 1910 1911 // change the mode if needed. 1912 if (isSpeakerOn(context) != sIsSpeakerEnabled) { 1913 turnOnSpeaker(context, sIsSpeakerEnabled, false); 1914 } 1915 } 1916 1917 static boolean isSpeakerOn(Context context) { 1918 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1919 return audioManager.isSpeakerphoneOn(); 1920 } 1921 1922 1923 static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) { 1924 if (DBG) log("turnOnNoiseSuppression: " + flag); 1925 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1926 1927 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1928 return; 1929 } 1930 1931 if (flag) { 1932 audioManager.setParameters("noise_suppression=auto"); 1933 } else { 1934 audioManager.setParameters("noise_suppression=off"); 1935 } 1936 1937 // record the speaker-enable value 1938 if (store) { 1939 sIsNoiseSuppressionEnabled = flag; 1940 } 1941 1942 // TODO: implement and manage ICON 1943 1944 } 1945 1946 static void restoreNoiseSuppression(Context context) { 1947 if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled); 1948 1949 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1950 return; 1951 } 1952 1953 // change the mode if needed. 1954 if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) { 1955 turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false); 1956 } 1957 } 1958 1959 static boolean isNoiseSuppressionOn(Context context) { 1960 1961 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1962 return false; 1963 } 1964 1965 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1966 String noiseSuppression = audioManager.getParameters("noise_suppression"); 1967 if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression); 1968 if (noiseSuppression.contains("off")) { 1969 return false; 1970 } else { 1971 return true; 1972 } 1973 } 1974 1975 /** 1976 * 1977 * Mute / umute the foreground phone, which has the current foreground call 1978 * 1979 * All muting / unmuting from the in-call UI should go through this 1980 * wrapper. 1981 * 1982 * Wrapper around Phone.setMute() and setMicrophoneMute(). 1983 * It also updates the connectionMuteTable and mute icon in the status bar. 1984 * 1985 */ 1986 static void setMute(boolean muted) { 1987 CallManager cm = PhoneApp.getInstance().mCM; 1988 1989 // make the call to mute the audio 1990 setMuteInternal(cm.getFgPhone(), muted); 1991 1992 // update the foreground connections to match. This includes 1993 // all the connections on conference calls. 1994 for (Connection cn : cm.getActiveFgCall().getConnections()) { 1995 if (sConnectionMuteTable.get(cn) == null) { 1996 if (DBG) log("problem retrieving mute value for this connection."); 1997 } 1998 sConnectionMuteTable.put(cn, Boolean.valueOf(muted)); 1999 } 2000 } 2001 2002 /** 2003 * Internally used muting function. 2004 */ 2005 private static void setMuteInternal(Phone phone, boolean muted) { 2006 final PhoneApp app = PhoneApp.getInstance(); 2007 Context context = phone.getContext(); 2008 boolean routeToAudioManager = 2009 context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); 2010 if (routeToAudioManager) { 2011 AudioManager audioManager = 2012 (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE); 2013 if (DBG) log("setMuteInternal: using setMicrophoneMute(" + muted + ")..."); 2014 audioManager.setMicrophoneMute(muted); 2015 } else { 2016 if (DBG) log("setMuteInternal: using phone.setMute(" + muted + ")..."); 2017 phone.setMute(muted); 2018 } 2019 app.notificationMgr.updateMuteNotification(); 2020 } 2021 2022 /** 2023 * Get the mute state of foreground phone, which has the current 2024 * foreground call 2025 */ 2026 static boolean getMute() { 2027 final PhoneApp app = PhoneApp.getInstance(); 2028 2029 boolean routeToAudioManager = 2030 app.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); 2031 if (routeToAudioManager) { 2032 AudioManager audioManager = 2033 (AudioManager) app.getSystemService(Context.AUDIO_SERVICE); 2034 return audioManager.isMicrophoneMute(); 2035 } else { 2036 return app.mCM.getMute(); 2037 } 2038 } 2039 2040 /* package */ static void setAudioMode() { 2041 setAudioMode(PhoneApp.getInstance().mCM); 2042 } 2043 2044 /** 2045 * Sets the audio mode per current phone state. 2046 */ 2047 /* package */ static void setAudioMode(CallManager cm) { 2048 if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState()); 2049 2050 Context context = PhoneApp.getInstance(); 2051 AudioManager audioManager = (AudioManager) 2052 context.getSystemService(Context.AUDIO_SERVICE); 2053 int modeBefore = audioManager.getMode(); 2054 cm.setAudioMode(); 2055 int modeAfter = audioManager.getMode(); 2056 2057 if (modeBefore != modeAfter) { 2058 // Enable stack dump only when actively debugging ("new Throwable()" is expensive!) 2059 if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump")); 2060 } else { 2061 if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: " 2062 + audioModeToString(modeBefore)); 2063 } 2064 } 2065 private static String audioModeToString(int mode) { 2066 switch (mode) { 2067 case AudioManager.MODE_INVALID: return "MODE_INVALID"; 2068 case AudioManager.MODE_CURRENT: return "MODE_CURRENT"; 2069 case AudioManager.MODE_NORMAL: return "MODE_NORMAL"; 2070 case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE"; 2071 case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL"; 2072 default: return String.valueOf(mode); 2073 } 2074 } 2075 2076 /** 2077 * Handles the wired headset button while in-call. 2078 * 2079 * This is called from the PhoneApp, not from the InCallScreen, 2080 * since the HEADSETHOOK button means "mute or unmute the current 2081 * call" *any* time a call is active, even if the user isn't actually 2082 * on the in-call screen. 2083 * 2084 * @return true if we consumed the event. 2085 */ 2086 /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) { 2087 if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount()); 2088 final PhoneApp app = PhoneApp.getInstance(); 2089 2090 // If the phone is totally idle, we ignore HEADSETHOOK events 2091 // (and instead let them fall through to the media player.) 2092 if (phone.getState() == Phone.State.IDLE) { 2093 return false; 2094 } 2095 2096 // Ok, the phone is in use. 2097 // The headset button button means "Answer" if an incoming call is 2098 // ringing. If not, it toggles the mute / unmute state. 2099 // 2100 // And in any case we *always* consume this event; this means 2101 // that the usual mediaplayer-related behavior of the headset 2102 // button will NEVER happen while the user is on a call. 2103 2104 final boolean hasRingingCall = !phone.getRingingCall().isIdle(); 2105 final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); 2106 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); 2107 2108 if (hasRingingCall && 2109 event.getRepeatCount() == 0 && 2110 event.getAction() == KeyEvent.ACTION_UP) { 2111 // If an incoming call is ringing, answer it (just like with the 2112 // CALL button): 2113 int phoneType = phone.getPhoneType(); 2114 if (phoneType == Phone.PHONE_TYPE_CDMA) { 2115 answerCall(phone.getRingingCall()); 2116 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 2117 || (phoneType == Phone.PHONE_TYPE_SIP)) { 2118 if (hasActiveCall && hasHoldingCall) { 2119 if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!"); 2120 answerAndEndActive(app.mCM, phone.getRingingCall()); 2121 } else { 2122 if (DBG) log("handleHeadsetHook: ringing ==> answer!"); 2123 // answerCall() will automatically hold the current 2124 // active call, if there is one. 2125 answerCall(phone.getRingingCall()); 2126 } 2127 } else { 2128 throw new IllegalStateException("Unexpected phone type: " + phoneType); 2129 } 2130 } else { 2131 // No incoming ringing call. 2132 if (event.isLongPress()) { 2133 if (DBG) log("handleHeadsetHook: longpress -> hangup"); 2134 hangup(app.mCM); 2135 } 2136 else if (event.getAction() == KeyEvent.ACTION_UP && 2137 event.getRepeatCount() == 0) { 2138 Connection c = phone.getForegroundCall().getLatestConnection(); 2139 // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook. 2140 if (c != null && !PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(), 2141 PhoneApp.getInstance())) { 2142 if (getMute()) { 2143 if (DBG) log("handleHeadsetHook: UNmuting..."); 2144 setMute(false); 2145 } else { 2146 if (DBG) log("handleHeadsetHook: muting..."); 2147 setMute(true); 2148 } 2149 } 2150 } 2151 } 2152 2153 // Even if the InCallScreen is the current activity, there's no 2154 // need to force it to update, because (1) if we answered a 2155 // ringing call, the InCallScreen will imminently get a phone 2156 // state change event (causing an update), and (2) if we muted or 2157 // unmuted, the setMute() call automagically updates the status 2158 // bar, and there's no "mute" indication in the InCallScreen 2159 // itself (other than the menu item, which only ever stays 2160 // onscreen for a second anyway.) 2161 // TODO: (2) isn't entirely true anymore. Once we return our result 2162 // to the PhoneApp, we ask InCallScreen to update its control widgets 2163 // in case we changed mute or speaker state and phones with touch- 2164 // screen [toggle] buttons need to update themselves. 2165 2166 return true; 2167 } 2168 2169 /** 2170 * Look for ANY connections on the phone that qualify as being 2171 * disconnected. 2172 * 2173 * @return true if we find a connection that is disconnected over 2174 * all the phone's call objects. 2175 */ 2176 /* package */ static boolean hasDisconnectedConnections(Phone phone) { 2177 return hasDisconnectedConnections(phone.getForegroundCall()) || 2178 hasDisconnectedConnections(phone.getBackgroundCall()) || 2179 hasDisconnectedConnections(phone.getRingingCall()); 2180 } 2181 2182 /** 2183 * Iterate over all connections in a call to see if there are any 2184 * that are not alive (disconnected or idle). 2185 * 2186 * @return true if we find a connection that is disconnected, and 2187 * pending removal via 2188 * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}. 2189 */ 2190 private static final boolean hasDisconnectedConnections(Call call) { 2191 // look through all connections for non-active ones. 2192 for (Connection c : call.getConnections()) { 2193 if (!c.isAlive()) { 2194 return true; 2195 } 2196 } 2197 return false; 2198 } 2199 2200 // 2201 // Misc UI policy helper functions 2202 // 2203 2204 /** 2205 * @return true if we're allowed to swap calls, given the current 2206 * state of the Phone. 2207 */ 2208 /* package */ static boolean okToSwapCalls(CallManager cm) { 2209 int phoneType = cm.getDefaultPhone().getPhoneType(); 2210 if (phoneType == Phone.PHONE_TYPE_CDMA) { 2211 // CDMA: "Swap" is enabled only when the phone reaches a *generic*. 2212 // state by either accepting a Call Waiting or by merging two calls 2213 PhoneApp app = PhoneApp.getInstance(); 2214 return (app.cdmaPhoneCallState.getCurrentCallState() 2215 == CdmaPhoneCallState.PhoneCallState.CONF_CALL); 2216 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 2217 || (phoneType == Phone.PHONE_TYPE_SIP)) { 2218 // GSM: "Swap" is available if both lines are in use and there's no 2219 // incoming call. (Actually we need to verify that the active 2220 // call really is in the ACTIVE state and the holding call really 2221 // is in the HOLDING state, since you *can't* actually swap calls 2222 // when the foreground call is DIALING or ALERTING.) 2223 return !cm.hasActiveRingingCall() 2224 && (cm.getActiveFgCall().getState() == Call.State.ACTIVE) 2225 && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING); 2226 } else { 2227 throw new IllegalStateException("Unexpected phone type: " + phoneType); 2228 } 2229 } 2230 2231 /** 2232 * @return true if we're allowed to merge calls, given the current 2233 * state of the Phone. 2234 */ 2235 /* package */ static boolean okToMergeCalls(CallManager cm) { 2236 int phoneType = cm.getFgPhone().getPhoneType(); 2237 if (phoneType == Phone.PHONE_TYPE_CDMA) { 2238 // CDMA: "Merge" is enabled only when the user is in a 3Way call. 2239 PhoneApp app = PhoneApp.getInstance(); 2240 return ((app.cdmaPhoneCallState.getCurrentCallState() 2241 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) 2242 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); 2243 } else { 2244 // GSM: "Merge" is available if both lines are in use and there's no 2245 // incoming call, *and* the current conference isn't already 2246 // "full". 2247 // TODO: shall move all okToMerge logic to CallManager 2248 return !cm.hasActiveRingingCall() && cm.hasActiveFgCall() 2249 && cm.hasActiveBgCall() 2250 && cm.canConference(cm.getFirstActiveBgCall()); 2251 } 2252 } 2253 2254 /** 2255 * @return true if the UI should let you add a new call, given the current 2256 * state of the Phone. 2257 */ 2258 /* package */ static boolean okToAddCall(CallManager cm) { 2259 Phone phone = cm.getActiveFgCall().getPhone(); 2260 2261 // "Add call" is never allowed in emergency callback mode (ECM). 2262 if (isPhoneInEcm(phone)) { 2263 return false; 2264 } 2265 2266 int phoneType = phone.getPhoneType(); 2267 final Call.State fgCallState = cm.getActiveFgCall().getState(); 2268 if (phoneType == Phone.PHONE_TYPE_CDMA) { 2269 // CDMA: "Add call" button is only enabled when: 2270 // - ForegroundCall is in ACTIVE state 2271 // - After 30 seconds of user Ignoring/Missing a Call Waiting call. 2272 PhoneApp app = PhoneApp.getInstance(); 2273 return ((fgCallState == Call.State.ACTIVE) 2274 && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting())); 2275 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 2276 || (phoneType == Phone.PHONE_TYPE_SIP)) { 2277 // GSM: "Add call" is available only if ALL of the following are true: 2278 // - There's no incoming ringing call 2279 // - There's < 2 lines in use 2280 // - The foreground call is ACTIVE or IDLE or DISCONNECTED. 2281 // (We mainly need to make sure it *isn't* DIALING or ALERTING.) 2282 final boolean hasRingingCall = cm.hasActiveRingingCall(); 2283 final boolean hasActiveCall = cm.hasActiveFgCall(); 2284 final boolean hasHoldingCall = cm.hasActiveBgCall(); 2285 final boolean allLinesTaken = hasActiveCall && hasHoldingCall; 2286 2287 return !hasRingingCall 2288 && !allLinesTaken 2289 && ((fgCallState == Call.State.ACTIVE) 2290 || (fgCallState == Call.State.IDLE) 2291 || (fgCallState == Call.State.DISCONNECTED)); 2292 } else { 2293 throw new IllegalStateException("Unexpected phone type: " + phoneType); 2294 } 2295 } 2296 2297 /** 2298 * Based on the input CNAP number string, 2299 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings. 2300 * Otherwise, return CNAP_SPECIAL_CASE_NO. 2301 */ 2302 private static int checkCnapSpecialCases(String n) { 2303 if (n.equals("PRIVATE") || 2304 n.equals("P") || 2305 n.equals("RES")) { 2306 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n); 2307 return Connection.PRESENTATION_RESTRICTED; 2308 } else if (n.equals("UNAVAILABLE") || 2309 n.equals("UNKNOWN") || 2310 n.equals("UNA") || 2311 n.equals("U")) { 2312 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n); 2313 return Connection.PRESENTATION_UNKNOWN; 2314 } else { 2315 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n); 2316 return CNAP_SPECIAL_CASE_NO; 2317 } 2318 } 2319 2320 /** 2321 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers 2322 * from the network to indicate different number presentations, convert them to 2323 * expected number and presentation values within the CallerInfo object. 2324 * @param number number we use to verify if we are in a corner case 2325 * @param presentation presentation value used to verify if we are in a corner case 2326 * @return the new String that should be used for the phone number 2327 */ 2328 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci, 2329 String number, int presentation) { 2330 // Obviously we return number if ci == null, but still return number if 2331 // number == null, because in these cases the correct string will still be 2332 // displayed/logged after this function returns based on the presentation value. 2333 if (ci == null || number == null) return number; 2334 2335 if (DBG) { 2336 log("modifyForSpecialCnapCases: initially, number=" 2337 + toLogSafePhoneNumber(number) 2338 + ", presentation=" + presentation + " ci " + ci); 2339 } 2340 2341 // "ABSENT NUMBER" is a possible value we could get from the network as the 2342 // phone number, so if this happens, change it to "Unknown" in the CallerInfo 2343 // and fix the presentation to be the same. 2344 if (number.equals(context.getString(R.string.absent_num)) 2345 && presentation == Connection.PRESENTATION_ALLOWED) { 2346 number = context.getString(R.string.unknown); 2347 ci.numberPresentation = Connection.PRESENTATION_UNKNOWN; 2348 } 2349 2350 // Check for other special "corner cases" for CNAP and fix them similarly. Corner 2351 // cases only apply if we received an allowed presentation from the network, so check 2352 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't 2353 // match the presentation passed in for verification (meaning we changed it previously 2354 // because it's a corner case and we're being called from a different entry point). 2355 if (ci.numberPresentation == Connection.PRESENTATION_ALLOWED 2356 || (ci.numberPresentation != presentation 2357 && presentation == Connection.PRESENTATION_ALLOWED)) { 2358 int cnapSpecialCase = checkCnapSpecialCases(number); 2359 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) { 2360 // For all special strings, change number & numberPresentation. 2361 if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) { 2362 number = context.getString(R.string.private_num); 2363 } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) { 2364 number = context.getString(R.string.unknown); 2365 } 2366 if (DBG) { 2367 log("SpecialCnap: number=" + toLogSafePhoneNumber(number) 2368 + "; presentation now=" + cnapSpecialCase); 2369 } 2370 ci.numberPresentation = cnapSpecialCase; 2371 } 2372 } 2373 if (DBG) { 2374 log("modifyForSpecialCnapCases: returning number string=" 2375 + toLogSafePhoneNumber(number)); 2376 } 2377 return number; 2378 } 2379 2380 // 2381 // Support for 3rd party phone service providers. 2382 // 2383 2384 /** 2385 * Check if all the provider's info is present in the intent. 2386 * @param intent Expected to have the provider's extra. 2387 * @return true if the intent has all the extras to build the 2388 * in-call screen's provider info overlay. 2389 */ 2390 /* package */ static boolean hasPhoneProviderExtras(Intent intent) { 2391 if (null == intent) { 2392 return false; 2393 } 2394 final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2395 final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); 2396 2397 return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri); 2398 } 2399 2400 /** 2401 * Copy all the expected extras set when a 3rd party provider is 2402 * used from the source intent to the destination one. Checks all 2403 * the required extras are present, if any is missing, none will 2404 * be copied. 2405 * @param src Intent which may contain the provider's extras. 2406 * @param dst Intent where a copy of the extras will be added if applicable. 2407 */ 2408 /* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) { 2409 if (!hasPhoneProviderExtras(src)) { 2410 Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing."); 2411 return; 2412 } 2413 2414 dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE, 2415 src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE)); 2416 dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI, 2417 src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI)); 2418 } 2419 2420 /** 2421 * Get the provider's label from the intent. 2422 * @param context to lookup the provider's package name. 2423 * @param intent with an extra set to the provider's package name. 2424 * @return The provider's application label. null if an error 2425 * occurred during the lookup of the package name or the label. 2426 */ 2427 /* package */ static CharSequence getProviderLabel(Context context, Intent intent) { 2428 String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2429 PackageManager pm = context.getPackageManager(); 2430 2431 try { 2432 ApplicationInfo info = pm.getApplicationInfo(packageName, 0); 2433 2434 return pm.getApplicationLabel(info); 2435 } catch (PackageManager.NameNotFoundException e) { 2436 return null; 2437 } 2438 } 2439 2440 /** 2441 * Get the provider's icon. 2442 * @param context to lookup the provider's icon. 2443 * @param intent with an extra set to the provider's package name. 2444 * @return The provider's application icon. null if an error occured during the icon lookup. 2445 */ 2446 /* package */ static Drawable getProviderIcon(Context context, Intent intent) { 2447 String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2448 PackageManager pm = context.getPackageManager(); 2449 2450 try { 2451 return pm.getApplicationIcon(packageName); 2452 } catch (PackageManager.NameNotFoundException e) { 2453 return null; 2454 } 2455 } 2456 2457 /** 2458 * Return the gateway uri from the intent. 2459 * @param intent With the gateway uri extra. 2460 * @return The gateway URI or null if not found. 2461 */ 2462 /* package */ static Uri getProviderGatewayUri(Intent intent) { 2463 String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); 2464 return TextUtils.isEmpty(uri) ? null : Uri.parse(uri); 2465 } 2466 2467 /** 2468 * Return a formatted version of the uri's scheme specific 2469 * part. E.g for 'tel:12345678', return '1-234-5678'. 2470 * @param uri A 'tel:' URI with the gateway phone number. 2471 * @return the provider's address (from the gateway uri) formatted 2472 * for user display. null if uri was null or its scheme was not 'tel:'. 2473 */ 2474 /* package */ static String formatProviderUri(Uri uri) { 2475 if (null != uri) { 2476 if (Constants.SCHEME_TEL.equals(uri.getScheme())) { 2477 return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart()); 2478 } else { 2479 return uri.toString(); 2480 } 2481 } 2482 return null; 2483 } 2484 2485 /** 2486 * Check if a phone number can be route through a 3rd party 2487 * gateway. The number must be a global phone number in numerical 2488 * form (1-800-666-SEXY won't work). 2489 * 2490 * MMI codes and the like cannot be used as a dial number for the 2491 * gateway either. 2492 * 2493 * @param number To be dialed via a 3rd party gateway. 2494 * @return true If the number can be routed through the 3rd party network. 2495 */ 2496 /* package */ static boolean isRoutableViaGateway(String number) { 2497 if (TextUtils.isEmpty(number)) { 2498 return false; 2499 } 2500 number = PhoneNumberUtils.stripSeparators(number); 2501 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) { 2502 return false; 2503 } 2504 number = PhoneNumberUtils.extractNetworkPortion(number); 2505 return PhoneNumberUtils.isGlobalPhoneNumber(number); 2506 } 2507 2508 /** 2509 * This function is called when phone answers or places a call. 2510 * Check if the phone is in a car dock or desk dock. 2511 * If yes, turn on the speaker, when no wired or BT headsets are connected. 2512 * Otherwise do nothing. 2513 * @return true if activated 2514 */ 2515 private static boolean activateSpeakerIfDocked(Phone phone) { 2516 if (DBG) log("activateSpeakerIfDocked()..."); 2517 2518 boolean activated = false; 2519 if (PhoneApp.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) { 2520 if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker."); 2521 PhoneApp app = PhoneApp.getInstance(); 2522 BluetoothHandsfree bthf = app.getBluetoothHandsfree(); 2523 2524 if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) { 2525 turnOnSpeaker(phone.getContext(), true, true); 2526 activated = true; 2527 } 2528 } 2529 return activated; 2530 } 2531 2532 2533 /** 2534 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not. 2535 */ 2536 /* package */ static boolean isPhoneInEcm(Phone phone) { 2537 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) { 2538 // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true". 2539 // TODO: There ought to be a better API for this than just 2540 // exposing a system property all the way up to the app layer, 2541 // probably a method like "inEcm()" provided by the telephony 2542 // layer. 2543 String ecmMode = 2544 SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE); 2545 if (ecmMode != null) { 2546 return ecmMode.equals("true"); 2547 } 2548 } 2549 return false; 2550 } 2551 2552 /** 2553 * Returns the most appropriate Phone object to handle a call 2554 * to the specified number. 2555 * 2556 * @param cm the CallManager. 2557 * @param scheme the scheme from the data URI that the number originally came from. 2558 * @param number the phone number, or SIP address. 2559 */ 2560 public static Phone pickPhoneBasedOnNumber(CallManager cm, 2561 String scheme, String number, String primarySipUri) { 2562 if (DBG) { 2563 log("pickPhoneBasedOnNumber: scheme " + scheme 2564 + ", number " + toLogSafePhoneNumber(number) 2565 + ", sipUri " 2566 + (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null")); 2567 } 2568 2569 if (primarySipUri != null) { 2570 Phone phone = getSipPhoneFromUri(cm, primarySipUri); 2571 if (phone != null) return phone; 2572 } 2573 return cm.getDefaultPhone(); 2574 } 2575 2576 public static Phone getSipPhoneFromUri(CallManager cm, String target) { 2577 for (Phone phone : cm.getAllPhones()) { 2578 if (phone.getPhoneType() == Phone.PHONE_TYPE_SIP) { 2579 String sipUri = ((SipPhone) phone).getSipUri(); 2580 if (target.equals(sipUri)) { 2581 if (DBG) log("- pickPhoneBasedOnNumber:" + 2582 "found SipPhone! obj = " + phone + ", " 2583 + phone.getClass()); 2584 return phone; 2585 } 2586 } 2587 } 2588 return null; 2589 } 2590 2591 /** 2592 * Returns true when the given call is in INCOMING state and there's no foreground phone call, 2593 * meaning the call is the first real incoming call the phone is having. 2594 */ 2595 public static boolean isRealIncomingCall(Call.State state) { 2596 return (state == Call.State.INCOMING && !PhoneApp.getInstance().mCM.hasActiveFgCall()); 2597 } 2598 2599 private static boolean sVoipSupported = false; 2600 static { 2601 PhoneApp app = PhoneApp.getInstance(); 2602 sVoipSupported = SipManager.isVoipSupported(app) 2603 && app.getResources().getBoolean(com.android.internal.R.bool.config_built_in_sip_phone) 2604 && app.getResources().getBoolean(com.android.internal.R.bool.config_voice_capable); 2605 } 2606 2607 /** 2608 * @return true if this device supports voice calls using the built-in SIP stack. 2609 */ 2610 static boolean isVoipSupported() { 2611 return sVoipSupported; 2612 } 2613 2614 /** 2615 * On GSM devices, we never use short tones. 2616 * On CDMA devices, it depends upon the settings. 2617 */ 2618 public static boolean useShortDtmfTones(Phone phone, Context context) { 2619 int phoneType = phone.getPhoneType(); 2620 if (phoneType == Phone.PHONE_TYPE_GSM) { 2621 return false; 2622 } else if (phoneType == Phone.PHONE_TYPE_CDMA) { 2623 int toneType = android.provider.Settings.System.getInt( 2624 context.getContentResolver(), 2625 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, 2626 CallFeaturesSetting.DTMF_TONE_TYPE_NORMAL); 2627 if (toneType == CallFeaturesSetting.DTMF_TONE_TYPE_NORMAL) { 2628 return true; 2629 } else { 2630 return false; 2631 } 2632 } else if (phoneType == Phone.PHONE_TYPE_SIP) { 2633 return false; 2634 } else { 2635 throw new IllegalStateException("Unexpected phone type: " + phoneType); 2636 } 2637 } 2638 2639 public static String getPresentationString(Context context, int presentation) { 2640 String name = context.getString(R.string.unknown); 2641 if (presentation == Connection.PRESENTATION_RESTRICTED) { 2642 name = context.getString(R.string.private_num); 2643 } else if (presentation == Connection.PRESENTATION_PAYPHONE) { 2644 name = context.getString(R.string.payphone); 2645 } 2646 return name; 2647 } 2648 2649 public static void sendViewNotificationAsync(Context context, Uri contactUri) { 2650 if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")"); 2651 Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri); 2652 intent.setClassName("com.android.contacts", 2653 "com.android.contacts.ViewNotificationService"); 2654 context.startService(intent); 2655 } 2656 2657 // 2658 // General phone and call state debugging/testing code 2659 // 2660 2661 /* package */ static void dumpCallState(Phone phone) { 2662 PhoneApp app = PhoneApp.getInstance(); 2663 Log.d(LOG_TAG, "dumpCallState():"); 2664 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName() 2665 + ", state = " + phone.getState()); 2666 2667 StringBuilder b = new StringBuilder(128); 2668 2669 Call call = phone.getForegroundCall(); 2670 b.setLength(0); 2671 b.append(" - FG call: ").append(call.getState()); 2672 b.append(" isAlive ").append(call.getState().isAlive()); 2673 b.append(" isRinging ").append(call.getState().isRinging()); 2674 b.append(" isDialing ").append(call.getState().isDialing()); 2675 b.append(" isIdle ").append(call.isIdle()); 2676 b.append(" hasConnections ").append(call.hasConnections()); 2677 Log.d(LOG_TAG, b.toString()); 2678 2679 call = phone.getBackgroundCall(); 2680 b.setLength(0); 2681 b.append(" - BG call: ").append(call.getState()); 2682 b.append(" isAlive ").append(call.getState().isAlive()); 2683 b.append(" isRinging ").append(call.getState().isRinging()); 2684 b.append(" isDialing ").append(call.getState().isDialing()); 2685 b.append(" isIdle ").append(call.isIdle()); 2686 b.append(" hasConnections ").append(call.hasConnections()); 2687 Log.d(LOG_TAG, b.toString()); 2688 2689 call = phone.getRingingCall(); 2690 b.setLength(0); 2691 b.append(" - RINGING call: ").append(call.getState()); 2692 b.append(" isAlive ").append(call.getState().isAlive()); 2693 b.append(" isRinging ").append(call.getState().isRinging()); 2694 b.append(" isDialing ").append(call.getState().isDialing()); 2695 b.append(" isIdle ").append(call.isIdle()); 2696 b.append(" hasConnections ").append(call.hasConnections()); 2697 Log.d(LOG_TAG, b.toString()); 2698 2699 2700 final boolean hasRingingCall = !phone.getRingingCall().isIdle(); 2701 final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); 2702 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); 2703 final boolean allLinesTaken = hasActiveCall && hasHoldingCall; 2704 b.setLength(0); 2705 b.append(" - hasRingingCall ").append(hasRingingCall); 2706 b.append(" hasActiveCall ").append(hasActiveCall); 2707 b.append(" hasHoldingCall ").append(hasHoldingCall); 2708 b.append(" allLinesTaken ").append(allLinesTaken); 2709 Log.d(LOG_TAG, b.toString()); 2710 2711 // On CDMA phones, dump out the CdmaPhoneCallState too: 2712 if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { 2713 if (app.cdmaPhoneCallState != null) { 2714 Log.d(LOG_TAG, " - CDMA call state: " 2715 + app.cdmaPhoneCallState.getCurrentCallState()); 2716 } else { 2717 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!"); 2718 } 2719 } 2720 2721 // Watch out: the isRinging() call below does NOT tell us anything 2722 // about the state of the telephony layer; it merely tells us whether 2723 // the Ringer manager is currently playing the ringtone. 2724 boolean ringing = app.getRinger().isRinging(); 2725 Log.d(LOG_TAG, " - Ringer state: " + ringing); 2726 } 2727 2728 private static void log(String msg) { 2729 Log.d(LOG_TAG, msg); 2730 } 2731 2732 static void dumpCallManager() { 2733 Call call; 2734 CallManager cm = PhoneApp.getInstance().mCM; 2735 StringBuilder b = new StringBuilder(128); 2736 2737 2738 2739 Log.d(LOG_TAG, "############### dumpCallManager() ##############"); 2740 // TODO: Don't log "cm" itself, since CallManager.toString() 2741 // already spews out almost all this same information. 2742 // We should fix CallManager.toString() to be more minimal, and 2743 // use an explicit dumpState() method for the verbose dump. 2744 // Log.d(LOG_TAG, "CallManager: " + cm 2745 // + ", state = " + cm.getState()); 2746 Log.d(LOG_TAG, "CallManager: state = " + cm.getState()); 2747 b.setLength(0); 2748 call = cm.getActiveFgCall(); 2749 b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO "); 2750 b.append(call); 2751 b.append( " State: ").append(cm.getActiveFgCallState()); 2752 b.append( " Conn: ").append(cm.getFgCallConnections()); 2753 Log.d(LOG_TAG, b.toString()); 2754 b.setLength(0); 2755 call = cm.getFirstActiveBgCall(); 2756 b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO "); 2757 b.append(call); 2758 b.append( " State: ").append(cm.getFirstActiveBgCall().getState()); 2759 b.append( " Conn: ").append(cm.getBgCallConnections()); 2760 Log.d(LOG_TAG, b.toString()); 2761 b.setLength(0); 2762 call = cm.getFirstActiveRingingCall(); 2763 b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO "); 2764 b.append(call); 2765 b.append( " State: ").append(cm.getFirstActiveRingingCall().getState()); 2766 Log.d(LOG_TAG, b.toString()); 2767 2768 2769 2770 for (Phone phone : CallManager.getInstance().getAllPhones()) { 2771 if (phone != null) { 2772 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName() 2773 + ", state = " + phone.getState()); 2774 b.setLength(0); 2775 call = phone.getForegroundCall(); 2776 b.append(" - FG call: ").append(call); 2777 b.append( " State: ").append(call.getState()); 2778 b.append( " Conn: ").append(call.hasConnections()); 2779 Log.d(LOG_TAG, b.toString()); 2780 b.setLength(0); 2781 call = phone.getBackgroundCall(); 2782 b.append(" - BG call: ").append(call); 2783 b.append( " State: ").append(call.getState()); 2784 b.append( " Conn: ").append(call.hasConnections()); 2785 Log.d(LOG_TAG, b.toString());b.setLength(0); 2786 call = phone.getRingingCall(); 2787 b.append(" - RINGING call: ").append(call); 2788 b.append( " State: ").append(call.getState()); 2789 b.append( " Conn: ").append(call.hasConnections()); 2790 Log.d(LOG_TAG, b.toString()); 2791 } 2792 } 2793 2794 Log.d(LOG_TAG, "############## END dumpCallManager() ###############"); 2795 } 2796} 2797