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