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