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