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