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