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 = phone.dial(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 phone.sendUssdResponse(inputText.getText().toString()); 1102 newDialog.dismiss(); 1103 return true; 1104 } 1105 return false; 1106 } 1107 }; 1108 inputText.setOnKeyListener(mUSSDDialogInputListener); 1109 inputText.requestFocus(); 1110 1111 // set the window properties of the dialog 1112 newDialog.getWindow().setType( 1113 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); 1114 newDialog.getWindow().addFlags( 1115 WindowManager.LayoutParams.FLAG_DIM_BEHIND); 1116 1117 // now show the dialog! 1118 newDialog.show(); 1119 } 1120 } 1121 } 1122 1123 /** 1124 * Cancels the current pending MMI operation, if applicable. 1125 * @return true if we canceled an MMI operation, or false 1126 * if the current pending MMI wasn't cancelable 1127 * or if there was no current pending MMI at all. 1128 * 1129 * @see displayMMIInitiate 1130 */ 1131 static boolean cancelMmiCode(Phone phone) { 1132 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes(); 1133 int count = pendingMmis.size(); 1134 if (DBG) log("cancelMmiCode: num pending MMIs = " + count); 1135 1136 boolean canceled = false; 1137 if (count > 0) { 1138 // assume that we only have one pending MMI operation active at a time. 1139 // I don't think it's possible to enter multiple MMI codes concurrently 1140 // in the phone UI, because during the MMI operation, an Alert panel 1141 // is displayed, which prevents more MMI code from being entered. 1142 MmiCode mmiCode = pendingMmis.get(0); 1143 if (mmiCode.isCancelable()) { 1144 mmiCode.cancel(); 1145 canceled = true; 1146 } 1147 } 1148 1149 //clear timeout message and pre-set MMI command 1150 if (mNwService != null) { 1151 try { 1152 mNwService.clearMmiString(); 1153 } catch (RemoteException e) { 1154 mNwService = null; 1155 } 1156 } 1157 if (mMmiTimeoutCbMsg != null) { 1158 mMmiTimeoutCbMsg = null; 1159 } 1160 return canceled; 1161 } 1162 1163 public static class VoiceMailNumberMissingException extends Exception { 1164 VoiceMailNumberMissingException() { 1165 super(); 1166 } 1167 1168 VoiceMailNumberMissingException(String msg) { 1169 super(msg); 1170 } 1171 } 1172 1173 /** 1174 * Gets the phone number to be called from an intent. Requires a Context 1175 * to access the contacts database, and a Phone to access the voicemail 1176 * number. 1177 * 1178 * <p>If <code>phone</code> is <code>null</code>, the function will return 1179 * <code>null</code> for <code>voicemail:</code> URIs; 1180 * if <code>context</code> is <code>null</code>, the function will return 1181 * <code>null</code> for person/phone URIs.</p> 1182 * 1183 * <p>If the intent contains a <code>sip:</code> URI, the returned 1184 * "number" is actually the SIP address. 1185 * 1186 * @param context a context to use (or 1187 * @param intent the intent 1188 * 1189 * @throws VoiceMailNumberMissingException if <code>intent</code> contains 1190 * a <code>voicemail:</code> URI, but <code>phone</code> does not 1191 * have a voicemail number set. 1192 * 1193 * @return the phone number (or SIP address) that would be called by the intent, 1194 * or <code>null</code> if the number cannot be found. 1195 */ 1196 static String getNumberFromIntent(Context context, Intent intent) 1197 throws VoiceMailNumberMissingException { 1198 Uri uri = intent.getData(); 1199 String scheme = uri.getScheme(); 1200 1201 // The sip: scheme is simple: just treat the rest of the URI as a 1202 // SIP address. 1203 if (scheme.equals("sip")) { 1204 return uri.getSchemeSpecificPart(); 1205 } 1206 1207 // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle 1208 // the other cases (i.e. tel: and voicemail: and contact: URIs.) 1209 1210 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context); 1211 1212 // Check for a voicemail-dialing request. If the voicemail number is 1213 // empty, throw a VoiceMailNumberMissingException. 1214 if (scheme.equals("voicemail") && 1215 (number == null || TextUtils.isEmpty(number))) 1216 throw new VoiceMailNumberMissingException(); 1217 1218 return number; 1219 } 1220 1221 /** 1222 * Returns the caller-id info corresponding to the specified Connection. 1223 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we 1224 * extract a phone number from the specified Connection, and feed that 1225 * number into CallerInfo.getCallerInfo().) 1226 * 1227 * The returned CallerInfo may be null in certain error cases, like if the 1228 * specified Connection was null, or if we weren't able to get a valid 1229 * phone number from the Connection. 1230 * 1231 * Finally, if the getCallerInfo() call did succeed, we save the resulting 1232 * CallerInfo object in the "userData" field of the Connection. 1233 * 1234 * NOTE: This API should be avoided, with preference given to the 1235 * asynchronous startGetCallerInfo API. 1236 */ 1237 static CallerInfo getCallerInfo(Context context, Connection c) { 1238 CallerInfo info = null; 1239 1240 if (c != null) { 1241 //See if there is a URI attached. If there is, this means 1242 //that there is no CallerInfo queried yet, so we'll need to 1243 //replace the URI with a full CallerInfo object. 1244 Object userDataObject = c.getUserData(); 1245 if (userDataObject instanceof Uri) { 1246 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject); 1247 if (info != null) { 1248 c.setUserData(info); 1249 } 1250 } else { 1251 if (userDataObject instanceof CallerInfoToken) { 1252 //temporary result, while query is running 1253 info = ((CallerInfoToken) userDataObject).currentInfo; 1254 } else { 1255 //final query result 1256 info = (CallerInfo) userDataObject; 1257 } 1258 if (info == null) { 1259 // No URI, or Existing CallerInfo, so we'll have to make do with 1260 // querying a new CallerInfo using the connection's phone number. 1261 String number = c.getAddress(); 1262 1263 if (DBG) log("getCallerInfo: number = " + number); 1264 1265 if (!TextUtils.isEmpty(number)) { 1266 info = CallerInfo.getCallerInfo(context, number); 1267 if (info != null) { 1268 c.setUserData(info); 1269 } 1270 } 1271 } 1272 } 1273 } 1274 return info; 1275 } 1276 1277 /** 1278 * Class returned by the startGetCallerInfo call to package a temporary 1279 * CallerInfo Object, to be superceded by the CallerInfo Object passed 1280 * into the listener when the query with token mAsyncQueryToken is complete. 1281 */ 1282 public static class CallerInfoToken { 1283 /**indicates that there will no longer be updates to this request.*/ 1284 public boolean isFinal; 1285 1286 public CallerInfo currentInfo; 1287 public CallerInfoAsyncQuery asyncQuery; 1288 } 1289 1290 /** 1291 * Start a CallerInfo Query based on the earliest connection in the call. 1292 */ 1293 static CallerInfoToken startGetCallerInfo(Context context, Call call, 1294 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { 1295 PhoneApp app = PhoneApp.getInstance(); 1296 Connection conn = null; 1297 int phoneType = call.getPhone().getPhoneType(); 1298 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1299 conn = call.getLatestConnection(); 1300 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 1301 || (phoneType == Phone.PHONE_TYPE_SIP)) { 1302 conn = call.getEarliestConnection(); 1303 } else { 1304 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1305 } 1306 1307 return startGetCallerInfo(context, conn, listener, cookie); 1308 } 1309 1310 /** 1311 * place a temporary callerinfo object in the hands of the caller and notify 1312 * caller when the actual query is done. 1313 */ 1314 static CallerInfoToken startGetCallerInfo(Context context, Connection c, 1315 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { 1316 CallerInfoToken cit; 1317 1318 if (c == null) { 1319 //TODO: perhaps throw an exception here. 1320 cit = new CallerInfoToken(); 1321 cit.asyncQuery = null; 1322 return cit; 1323 } 1324 1325 // There are now 3 states for the userdata. 1326 // 1. Uri - query has not been executed yet 1327 // 2. CallerInfoToken - query is executing, but has not completed. 1328 // 3. CallerInfo - query has executed. 1329 // In each case we have slightly different behaviour: 1330 // 1. If the query has not been executed yet (Uri or null), we start 1331 // query execution asynchronously, and note it by attaching a 1332 // CallerInfoToken as the userData. 1333 // 2. If the query is executing (CallerInfoToken), we've essentially 1334 // reached a state where we've received multiple requests for the 1335 // same callerInfo. That means that once the query is complete, 1336 // we'll need to execute the additional listener requested. 1337 // 3. If the query has already been executed (CallerInfo), we just 1338 // return the CallerInfo object as expected. 1339 // 4. Regarding isFinal - there are cases where the CallerInfo object 1340 // will not be attached, like when the number is empty (caller id 1341 // blocking). This flag is used to indicate that the 1342 // CallerInfoToken object is going to be permanent since no 1343 // query results will be returned. In the case where a query 1344 // has been completed, this flag is used to indicate to the caller 1345 // that the data will not be updated since it is valid. 1346 // 1347 // Note: For the case where a number is NOT retrievable, we leave 1348 // the CallerInfo as null in the CallerInfoToken. This is 1349 // something of a departure from the original code, since the old 1350 // code manufactured a CallerInfo object regardless of the query 1351 // outcome. From now on, we will append an empty CallerInfo 1352 // object, to mirror previous behaviour, and to avoid Null Pointer 1353 // Exceptions. 1354 Object userDataObject = c.getUserData(); 1355 if (userDataObject instanceof Uri) { 1356 //create a dummy callerinfo, populate with what we know from URI. 1357 cit = new CallerInfoToken(); 1358 cit.currentInfo = new CallerInfo(); 1359 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1360 (Uri) userDataObject, sCallerInfoQueryListener, c); 1361 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1362 cit.isFinal = false; 1363 1364 c.setUserData(cit); 1365 1366 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject); 1367 1368 } else if (userDataObject == null) { 1369 // No URI, or Existing CallerInfo, so we'll have to make do with 1370 // querying a new CallerInfo using the connection's phone number. 1371 String number = c.getAddress(); 1372 1373 if (DBG) { 1374 log("###### PhoneUtils.startGetCallerInfo: new query for phone number #####"); 1375 log("- number (address): " + number); 1376 log("- c: " + c); 1377 log("- phone: " + c.getCall().getPhone()); 1378 int phoneType = c.getCall().getPhone().getPhoneType(); 1379 log("- phoneType: " + phoneType); 1380 switch (phoneType) { 1381 case Phone.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break; 1382 case Phone.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break; 1383 case Phone.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break; 1384 case Phone.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break; 1385 default: log(" ==> Unknown phone type"); break; 1386 } 1387 } 1388 1389 cit = new CallerInfoToken(); 1390 cit.currentInfo = new CallerInfo(); 1391 1392 // Store CNAP information retrieved from the Connection (we want to do this 1393 // here regardless of whether the number is empty or not). 1394 cit.currentInfo.cnapName = c.getCnapName(); 1395 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten 1396 // by ContactInfo later 1397 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1398 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1399 1400 if (DBG) { 1401 log("startGetCallerInfo: number = " + number); 1402 log("startGetCallerInfo: CNAP Info from FW(1): name=" 1403 + cit.currentInfo.cnapName 1404 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1405 } 1406 1407 // handling case where number is null (caller id hidden) as well. 1408 if (!TextUtils.isEmpty(number)) { 1409 // Check for special CNAP cases and modify the CallerInfo accordingly 1410 // to be sure we keep the right information to display/log later 1411 number = modifyForSpecialCnapCases(context, cit.currentInfo, number, 1412 cit.currentInfo.numberPresentation); 1413 1414 cit.currentInfo.phoneNumber = number; 1415 // For scenarios where we may receive a valid number from the network but a 1416 // restricted/unavailable presentation, we do not want to perform a contact query 1417 // (see note on isFinal above). So we set isFinal to true here as well. 1418 if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { 1419 cit.isFinal = true; 1420 } else { 1421 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()..."); 1422 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1423 number, sCallerInfoQueryListener, c); 1424 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1425 cit.isFinal = false; 1426 } 1427 } else { 1428 // This is the case where we are querying on a number that 1429 // is null or empty, like a caller whose caller id is 1430 // blocked or empty (CLIR). The previous behaviour was to 1431 // throw a null CallerInfo object back to the user, but 1432 // this departure is somewhat cleaner. 1433 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply."); 1434 cit.isFinal = true; // please see note on isFinal, above. 1435 } 1436 1437 c.setUserData(cit); 1438 1439 if (DBG) log("startGetCallerInfo: query based on number: " + number); 1440 1441 } else if (userDataObject instanceof CallerInfoToken) { 1442 // query is running, just tack on this listener to the queue. 1443 cit = (CallerInfoToken) userDataObject; 1444 1445 // handling case where number is null (caller id hidden) as well. 1446 if (cit.asyncQuery != null) { 1447 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1448 1449 if (DBG) log("startGetCallerInfo: query already running, adding listener: " + 1450 listener.getClass().toString()); 1451 } else { 1452 // handling case where number/name gets updated later on by the network 1453 String updatedNumber = c.getAddress(); 1454 if (DBG) log("startGetCallerInfo: updatedNumber initially = " + updatedNumber); 1455 if (!TextUtils.isEmpty(updatedNumber)) { 1456 // Store CNAP information retrieved from the Connection 1457 cit.currentInfo.cnapName = c.getCnapName(); 1458 // This can still get overwritten by ContactInfo 1459 cit.currentInfo.name = cit.currentInfo.cnapName; 1460 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1461 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1462 1463 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo, 1464 updatedNumber, cit.currentInfo.numberPresentation); 1465 1466 cit.currentInfo.phoneNumber = updatedNumber; 1467 if (DBG) log("startGetCallerInfo: updatedNumber=" + updatedNumber); 1468 if (DBG) log("startGetCallerInfo: CNAP Info from FW(2): name=" 1469 + cit.currentInfo.cnapName 1470 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1471 // For scenarios where we may receive a valid number from the network but a 1472 // restricted/unavailable presentation, we do not want to perform a contact query 1473 // (see note on isFinal above). So we set isFinal to true here as well. 1474 if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) { 1475 cit.isFinal = true; 1476 } else { 1477 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, 1478 updatedNumber, sCallerInfoQueryListener, c); 1479 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); 1480 cit.isFinal = false; 1481 } 1482 } else { 1483 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply."); 1484 if (cit.currentInfo == null) { 1485 cit.currentInfo = new CallerInfo(); 1486 } 1487 // Store CNAP information retrieved from the Connection 1488 cit.currentInfo.cnapName = c.getCnapName(); // This can still get 1489 // overwritten by ContactInfo 1490 cit.currentInfo.name = cit.currentInfo.cnapName; 1491 cit.currentInfo.numberPresentation = c.getNumberPresentation(); 1492 cit.currentInfo.namePresentation = c.getCnapNamePresentation(); 1493 1494 if (DBG) log("startGetCallerInfo: CNAP Info from FW(3): name=" 1495 + cit.currentInfo.cnapName 1496 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation); 1497 cit.isFinal = true; // please see note on isFinal, above. 1498 } 1499 } 1500 } else { 1501 cit = new CallerInfoToken(); 1502 cit.currentInfo = (CallerInfo) userDataObject; 1503 cit.asyncQuery = null; 1504 cit.isFinal = true; 1505 // since the query is already done, call the listener. 1506 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo"); 1507 } 1508 return cit; 1509 } 1510 1511 /** 1512 * Implemented for CallerInfo.OnCallerInfoQueryCompleteListener interface. 1513 * Updates the connection's userData when called. 1514 */ 1515 private static final int QUERY_TOKEN = -1; 1516 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener = 1517 new CallerInfoAsyncQuery.OnQueryCompleteListener () { 1518 public void onQueryComplete(int token, Object cookie, CallerInfo ci) { 1519 if (DBG) log("query complete, updating connection.userdata"); 1520 Connection conn = (Connection) cookie; 1521 1522 // Added a check if CallerInfo is coming from ContactInfo or from Connection. 1523 // If no ContactInfo, then we want to use CNAP information coming from network 1524 if (DBG) log("- onQueryComplete: CallerInfo:" + ci); 1525 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) { 1526 // If the number presentation has not been set by 1527 // the ContactInfo, use the one from the 1528 // connection. 1529 1530 // TODO: Need a new util method to merge the info 1531 // from the Connection in a CallerInfo object. 1532 // Here 'ci' is a new CallerInfo instance read 1533 // from the DB. It has lost all the connection 1534 // info preset before the query (see PhoneUtils 1535 // line 1334). We should have a method to merge 1536 // back into this new instance the info from the 1537 // connection object not set by the DB. If the 1538 // Connection already has a CallerInfo instance in 1539 // userData, then we could use this instance to 1540 // fill 'ci' in. The same routine could be used in 1541 // PhoneUtils. 1542 if (0 == ci.numberPresentation) { 1543 ci.numberPresentation = conn.getNumberPresentation(); 1544 } 1545 } else { 1546 CallerInfo newCi = getCallerInfo(null, conn); 1547 if (newCi != null) { 1548 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number 1549 ci = newCi; 1550 } 1551 } 1552 conn.setUserData(ci); 1553 } 1554 }; 1555 1556 1557 /** 1558 * Returns a single "name" for the specified given a CallerInfo object. 1559 * If the name is null, return defaultString as the default value, usually 1560 * context.getString(R.string.unknown). 1561 */ 1562 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) { 1563 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci); 1564 1565 String compactName = null; 1566 if (ci != null) { 1567 if (TextUtils.isEmpty(ci.name)) { 1568 // Perform any modifications for special CNAP cases to 1569 // the phone number being displayed, if applicable. 1570 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber, 1571 ci.numberPresentation); 1572 } else { 1573 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795. 1574 compactName = ci.name; 1575 } 1576 } 1577 1578 if ((compactName == null) || (TextUtils.isEmpty(compactName))) { 1579 // If we're still null/empty here, then check if we have a presentation 1580 // string that takes precedence that we could return, otherwise display 1581 // "unknown" string. 1582 if (ci != null && ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) { 1583 compactName = context.getString(R.string.private_num); 1584 } else if (ci != null && ci.numberPresentation == Connection.PRESENTATION_PAYPHONE) { 1585 compactName = context.getString(R.string.payphone); 1586 } else { 1587 compactName = context.getString(R.string.unknown); 1588 } 1589 } 1590 if (DBG) log("getCompactNameFromCallerInfo: compactName=" + compactName); 1591 return compactName; 1592 } 1593 1594 /** 1595 * Returns true if the specified Call is a "conference call", meaning 1596 * that it owns more than one Connection object. This information is 1597 * used to trigger certain UI changes that appear when a conference 1598 * call is active (like displaying the label "Conference call", and 1599 * enabling the "Manage conference" UI.) 1600 * 1601 * Watch out: This method simply checks the number of Connections, 1602 * *not* their states. So if a Call has (for example) one ACTIVE 1603 * connection and one DISCONNECTED connection, this method will return 1604 * true (which is unintuitive, since the Call isn't *really* a 1605 * conference call any more.) 1606 * 1607 * @return true if the specified call has more than one connection (in any state.) 1608 */ 1609 static boolean isConferenceCall(Call call) { 1610 // CDMA phones don't have the same concept of "conference call" as 1611 // GSM phones do; there's no special "conference call" state of 1612 // the UI or a "manage conference" function. (Instead, when 1613 // you're in a 3-way call, all we can do is display the "generic" 1614 // state of the UI.) So as far as the in-call UI is concerned, 1615 // Conference corresponds to generic display. 1616 PhoneApp app = PhoneApp.getInstance(); 1617 int phoneType = call.getPhone().getPhoneType(); 1618 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1619 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState(); 1620 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL) 1621 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) 1622 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) { 1623 return true; 1624 } 1625 } else { 1626 List<Connection> connections = call.getConnections(); 1627 if (connections != null && connections.size() > 1) { 1628 return true; 1629 } 1630 } 1631 return false; 1632 1633 // TODO: We may still want to change the semantics of this method 1634 // to say that a given call is only really a conference call if 1635 // the number of ACTIVE connections, not the total number of 1636 // connections, is greater than one. (See warning comment in the 1637 // javadoc above.) 1638 // Here's an implementation of that: 1639 // if (connections == null) { 1640 // return false; 1641 // } 1642 // int numActiveConnections = 0; 1643 // for (Connection conn : connections) { 1644 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState()); 1645 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++; 1646 // if (numActiveConnections > 1) { 1647 // return true; 1648 // } 1649 // } 1650 // return false; 1651 } 1652 1653 /** 1654 * Launch the Dialer to start a new call. 1655 * This is just a wrapper around the ACTION_DIAL intent. 1656 */ 1657 static void startNewCall(final CallManager cm) { 1658 // Sanity-check that this is OK given the current state of the phone. 1659 if (!okToAddCall(cm)) { 1660 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state"); 1661 dumpCallManager(); 1662 return; 1663 } 1664 1665 // if applicable, mute the call while we're showing the add call UI. 1666 if (cm.hasActiveFgCall()) { 1667 setMuteInternal(cm.getActiveFgCall().getPhone(), true); 1668 // Inform the phone app that this mute state was NOT done 1669 // voluntarily by the User. 1670 PhoneApp.getInstance().setRestoreMuteOnInCallResume(true); 1671 } 1672 1673 Intent intent = new Intent(Intent.ACTION_DIAL); 1674 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1675 1676 // when we request the dialer come up, we also want to inform 1677 // it that we're going through the "add call" option from the 1678 // InCallScreen / PhoneUtils. 1679 intent.putExtra(ADD_CALL_MODE_KEY, true); 1680 1681 PhoneApp.getInstance().startActivity(intent); 1682 } 1683 1684 static void turnOnSpeaker(Context context, boolean flag, boolean store) { 1685 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")..."); 1686 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1687 1688 audioManager.setSpeakerphoneOn(flag); 1689 // record the speaker-enable value 1690 if (store) { 1691 sIsSpeakerEnabled = flag; 1692 } 1693 if (flag) { 1694 NotificationMgr.getDefault().notifySpeakerphone(); 1695 } else { 1696 NotificationMgr.getDefault().cancelSpeakerphone(); 1697 } 1698 1699 // We also need to make a fresh call to PhoneApp.updateWakeState() 1700 // any time the speaker state changes, since the screen timeout is 1701 // sometimes different depending on whether or not the speaker is 1702 // in use. 1703 PhoneApp app = PhoneApp.getInstance(); 1704 app.updateWakeState(); 1705 1706 // Update the Proximity sensor based on speaker state 1707 app.updateProximitySensorMode(app.mCM.getState()); 1708 1709 app.mCM.setEchoSuppressionEnabled(flag); 1710 } 1711 1712 /** 1713 * Restore the speaker mode, called after a wired headset disconnect 1714 * event. 1715 */ 1716 static void restoreSpeakerMode(Context context) { 1717 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled); 1718 1719 // change the mode if needed. 1720 if (isSpeakerOn(context) != sIsSpeakerEnabled) { 1721 turnOnSpeaker(context, sIsSpeakerEnabled, false); 1722 } 1723 } 1724 1725 static boolean isSpeakerOn(Context context) { 1726 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1727 return audioManager.isSpeakerphoneOn(); 1728 } 1729 1730 1731 static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) { 1732 if (DBG) log("turnOnNoiseSuppression: " + flag); 1733 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1734 1735 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1736 return; 1737 } 1738 1739 if (flag) { 1740 audioManager.setParameters("noise_suppression=auto"); 1741 } else { 1742 audioManager.setParameters("noise_suppression=off"); 1743 } 1744 1745 // record the speaker-enable value 1746 if (store) { 1747 sIsNoiseSuppressionEnabled = flag; 1748 } 1749 1750 // TODO: implement and manage ICON 1751 1752 } 1753 1754 static void restoreNoiseSuppression(Context context) { 1755 if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled); 1756 1757 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1758 return; 1759 } 1760 1761 // change the mode if needed. 1762 if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) { 1763 turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false); 1764 } 1765 } 1766 1767 static boolean isNoiseSuppressionOn(Context context) { 1768 1769 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) { 1770 return false; 1771 } 1772 1773 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 1774 String noiseSuppression = audioManager.getParameters("noise_suppression"); 1775 if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression); 1776 if (noiseSuppression.contains("off")) { 1777 return false; 1778 } else { 1779 return true; 1780 } 1781 } 1782 1783 /** 1784 * 1785 * Mute / umute the foreground phone, which has the current foreground call 1786 * 1787 * All muting / unmuting from the in-call UI should go through this 1788 * wrapper. 1789 * 1790 * Wrapper around Phone.setMute() and setMicrophoneMute(). 1791 * It also updates the connectionMuteTable and mute icon in the status bar. 1792 * 1793 */ 1794 static void setMute(boolean muted) { 1795 CallManager cm = PhoneApp.getInstance().mCM; 1796 1797 // make the call to mute the audio 1798 setMuteInternal(cm.getFgPhone(), muted); 1799 1800 1801 // update the foreground connections to match. This includes 1802 // all the connections on conference calls. 1803 for (Connection cn : cm.getActiveFgCall().getConnections()) { 1804 if (sConnectionMuteTable.get(cn) == null) { 1805 if (DBG) log("problem retrieving mute value for this connection."); 1806 } 1807 sConnectionMuteTable.put(cn, Boolean.valueOf(muted)); 1808 } 1809 } 1810 1811 /** 1812 * Internally used muting function. 1813 */ 1814 private static void setMuteInternal(Phone phone, boolean muted) { 1815 if (DBG) log("setMuteInternal: " + muted); 1816 Context context = phone.getContext(); 1817 boolean routeToAudioManager = 1818 context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); 1819 if (routeToAudioManager) { 1820 AudioManager audioManager = 1821 (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE); 1822 if (DBG) log("setMicrophoneMute: " + muted); 1823 audioManager.setMicrophoneMute(muted); 1824 } else { 1825 phone.setMute(muted); 1826 } 1827 NotificationMgr.getDefault().updateMuteNotification(); 1828 } 1829 1830 /** 1831 * Get the mute state of foreground phone, which has the current 1832 * foreground call 1833 */ 1834 static boolean getMute() { 1835 Phone phone = PhoneApp.getInstance().mCM.getFgPhone(); 1836 1837 Context context = phone.getContext(); 1838 boolean routeToAudioManager = 1839 context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager); 1840 if (routeToAudioManager) { 1841 AudioManager audioManager = 1842 (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE); 1843 return audioManager.isMicrophoneMute(); 1844 } else { 1845 return phone.getMute(); 1846 } 1847 } 1848 1849 /* package */ static void setAudioMode() { 1850 setAudioMode(PhoneApp.getInstance().mCM); 1851 } 1852 1853 /** 1854 * Sets the audio mode per current phone state. 1855 */ 1856 /* package */ static void setAudioMode(CallManager cm) { 1857 if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState()); 1858 1859 Context context = PhoneApp.getInstance(); 1860 AudioManager audioManager = (AudioManager) 1861 context.getSystemService(Context.AUDIO_SERVICE); 1862 int modeBefore = audioManager.getMode(); 1863 cm.setAudioMode(); 1864 int modeAfter = audioManager.getMode(); 1865 1866 if (modeBefore != modeAfter) { 1867 // Enable stack dump only when actively debugging ("new Throwable()" is expensive!) 1868 if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump")); 1869 } else { 1870 if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: " 1871 + audioModeToString(modeBefore)); 1872 } 1873 } 1874 private static String audioModeToString(int mode) { 1875 switch (mode) { 1876 case AudioManager.MODE_INVALID: return "MODE_INVALID"; 1877 case AudioManager.MODE_CURRENT: return "MODE_CURRENT"; 1878 case AudioManager.MODE_NORMAL: return "MODE_NORMAL"; 1879 case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE"; 1880 case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL"; 1881 default: return String.valueOf(mode); 1882 } 1883 } 1884 1885 /** 1886 * Handles the wired headset button while in-call. 1887 * 1888 * This is called from the PhoneApp, not from the InCallScreen, 1889 * since the HEADSETHOOK button means "mute or unmute the current 1890 * call" *any* time a call is active, even if the user isn't actually 1891 * on the in-call screen. 1892 * 1893 * @return true if we consumed the event. 1894 */ 1895 /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) { 1896 if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount()); 1897 1898 // If the phone is totally idle, we ignore HEADSETHOOK events 1899 // (and instead let them fall through to the media player.) 1900 if (phone.getState() == Phone.State.IDLE) { 1901 return false; 1902 } 1903 1904 // Ok, the phone is in use. 1905 // The headset button button means "Answer" if an incoming call is 1906 // ringing. If not, it toggles the mute / unmute state. 1907 // 1908 // And in any case we *always* consume this event; this means 1909 // that the usual mediaplayer-related behavior of the headset 1910 // button will NEVER happen while the user is on a call. 1911 1912 final boolean hasRingingCall = !phone.getRingingCall().isIdle(); 1913 final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); 1914 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); 1915 1916 if (hasRingingCall && 1917 event.getRepeatCount() == 0 && 1918 event.getAction() == KeyEvent.ACTION_UP) { 1919 // If an incoming call is ringing, answer it (just like with the 1920 // CALL button): 1921 int phoneType = phone.getPhoneType(); 1922 if (phoneType == Phone.PHONE_TYPE_CDMA) { 1923 answerCall(phone.getRingingCall()); 1924 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 1925 || (phoneType == Phone.PHONE_TYPE_SIP)) { 1926 if (hasActiveCall && hasHoldingCall) { 1927 if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!"); 1928 answerAndEndActive(PhoneApp.getInstance().mCM, phone.getRingingCall()); 1929 } else { 1930 if (DBG) log("handleHeadsetHook: ringing ==> answer!"); 1931 answerCall(phone.getRingingCall()); // Automatically holds the current active call, 1932 // if there is one 1933 } 1934 } else { 1935 throw new IllegalStateException("Unexpected phone type: " + phoneType); 1936 } 1937 } else { 1938 // No incoming ringing call. 1939 if (event.isLongPress()) { 1940 if (DBG) log("handleHeadsetHook: longpress -> hangup"); 1941 hangup(PhoneApp.getInstance().mCM); 1942 } 1943 else if (event.getAction() == KeyEvent.ACTION_UP && 1944 event.getRepeatCount() == 0) { 1945 Connection c = phone.getForegroundCall().getLatestConnection(); 1946 // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook. 1947 if (c != null && !PhoneNumberUtils.isEmergencyNumber(c.getAddress())) { 1948 if (getMute()) { 1949 if (DBG) log("handleHeadsetHook: UNmuting..."); 1950 setMute(false); 1951 } else { 1952 if (DBG) log("handleHeadsetHook: muting..."); 1953 setMute(true); 1954 } 1955 } 1956 } 1957 } 1958 1959 // Even if the InCallScreen is the current activity, there's no 1960 // need to force it to update, because (1) if we answered a 1961 // ringing call, the InCallScreen will imminently get a phone 1962 // state change event (causing an update), and (2) if we muted or 1963 // unmuted, the setMute() call automagically updates the status 1964 // bar, and there's no "mute" indication in the InCallScreen 1965 // itself (other than the menu item, which only ever stays 1966 // onscreen for a second anyway.) 1967 // TODO: (2) isn't entirely true anymore. Once we return our result 1968 // to the PhoneApp, we ask InCallScreen to update its control widgets 1969 // in case we changed mute or speaker state and phones with touch- 1970 // screen [toggle] buttons need to update themselves. 1971 1972 return true; 1973 } 1974 1975 /** 1976 * Look for ANY connections on the phone that qualify as being 1977 * disconnected. 1978 * 1979 * @return true if we find a connection that is disconnected over 1980 * all the phone's call objects. 1981 */ 1982 /* package */ static boolean hasDisconnectedConnections(Phone phone) { 1983 return hasDisconnectedConnections(phone.getForegroundCall()) || 1984 hasDisconnectedConnections(phone.getBackgroundCall()) || 1985 hasDisconnectedConnections(phone.getRingingCall()); 1986 } 1987 1988 /** 1989 * Iterate over all connections in a call to see if there are any 1990 * that are not alive (disconnected or idle). 1991 * 1992 * @return true if we find a connection that is disconnected, and 1993 * pending removal via 1994 * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}. 1995 */ 1996 private static final boolean hasDisconnectedConnections(Call call) { 1997 // look through all connections for non-active ones. 1998 for (Connection c : call.getConnections()) { 1999 if (!c.isAlive()) { 2000 return true; 2001 } 2002 } 2003 return false; 2004 } 2005 2006 // 2007 // Misc UI policy helper functions 2008 // 2009 2010 /** 2011 * @return true if we're allowed to swap calls, given the current 2012 * state of the Phone. 2013 */ 2014 /* package */ static boolean okToSwapCalls(CallManager cm) { 2015 int phoneType = cm.getDefaultPhone().getPhoneType(); 2016 if (phoneType == Phone.PHONE_TYPE_CDMA) { 2017 // CDMA: "Swap" is enabled only when the phone reaches a *generic*. 2018 // state by either accepting a Call Waiting or by merging two calls 2019 PhoneApp app = PhoneApp.getInstance(); 2020 return (app.cdmaPhoneCallState.getCurrentCallState() 2021 == CdmaPhoneCallState.PhoneCallState.CONF_CALL); 2022 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 2023 || (phoneType == Phone.PHONE_TYPE_SIP)) { 2024 // GSM: "Swap" is available if both lines are in use and there's no 2025 // incoming call. (Actually we need to verify that the active 2026 // call really is in the ACTIVE state and the holding call really 2027 // is in the HOLDING state, since you *can't* actually swap calls 2028 // when the foreground call is DIALING or ALERTING.) 2029 return !cm.hasActiveRingingCall() 2030 && (cm.getActiveFgCall().getState() == Call.State.ACTIVE) 2031 && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING); 2032 } else { 2033 throw new IllegalStateException("Unexpected phone type: " + phoneType); 2034 } 2035 } 2036 2037 /** 2038 * @return true if we're allowed to merge calls, given the current 2039 * state of the Phone. 2040 */ 2041 /* package */ static boolean okToMergeCalls(CallManager cm) { 2042 int phoneType = cm.getFgPhone().getPhoneType(); 2043 if (phoneType == Phone.PHONE_TYPE_CDMA) { 2044 // CDMA: "Merge" is enabled only when the user is in a 3Way call. 2045 PhoneApp app = PhoneApp.getInstance(); 2046 return ((app.cdmaPhoneCallState.getCurrentCallState() 2047 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) 2048 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); 2049 } else { 2050 // GSM: "Merge" is available if both lines are in use and there's no 2051 // incoming call, *and* the current conference isn't already 2052 // "full". 2053 // TODO: shall move all okToMerge logic to CallManager 2054 return !cm.hasActiveRingingCall() && cm.hasActiveFgCall() 2055 && cm.hasActiveBgCall() 2056 && cm.canConference(cm.getFirstActiveBgCall()); 2057 } 2058 } 2059 2060 /** 2061 * @return true if the UI should let you add a new call, given the current 2062 * state of the Phone. 2063 */ 2064 /* package */ static boolean okToAddCall(CallManager cm) { 2065 Phone phone = cm.getActiveFgCall().getPhone(); 2066 2067 int phoneType = phone.getPhoneType(); 2068 final Call.State fgCallState = cm.getActiveFgCall().getState(); 2069 if (phoneType == Phone.PHONE_TYPE_CDMA) { 2070 // CDMA: "Add call" menu item is only enabled when the call is in 2071 // - ForegroundCall is in ACTIVE state 2072 // - After 30 seconds of user Ignoring/Missing a Call Waiting call. 2073 PhoneApp app = PhoneApp.getInstance(); 2074 return ((fgCallState == Call.State.ACTIVE) 2075 && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting())); 2076 } else if ((phoneType == Phone.PHONE_TYPE_GSM) 2077 || (phoneType == Phone.PHONE_TYPE_SIP)) { 2078 // GSM: "Add call" is available only if ALL of the following are true: 2079 // - There's no incoming ringing call 2080 // - There's < 2 lines in use 2081 // - The foreground call is ACTIVE or IDLE or DISCONNECTED. 2082 // (We mainly need to make sure it *isn't* DIALING or ALERTING.) 2083 final boolean hasRingingCall = cm.hasActiveRingingCall(); 2084 final boolean hasActiveCall = cm.hasActiveFgCall(); 2085 final boolean hasHoldingCall = cm.hasActiveBgCall(); 2086 final boolean allLinesTaken = hasActiveCall && hasHoldingCall; 2087 2088 return !hasRingingCall 2089 && !allLinesTaken 2090 && ((fgCallState == Call.State.ACTIVE) 2091 || (fgCallState == Call.State.IDLE) 2092 || (fgCallState == Call.State.DISCONNECTED)); 2093 } else { 2094 throw new IllegalStateException("Unexpected phone type: " + phoneType); 2095 } 2096 } 2097 2098 /** 2099 * Based on the input CNAP number string, 2100 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings. 2101 * Otherwise, return CNAP_SPECIAL_CASE_NO. 2102 */ 2103 private static int checkCnapSpecialCases(String n) { 2104 if (n.equals("PRIVATE") || 2105 n.equals("P") || 2106 n.equals("RES")) { 2107 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n); 2108 return Connection.PRESENTATION_RESTRICTED; 2109 } else if (n.equals("UNAVAILABLE") || 2110 n.equals("UNKNOWN") || 2111 n.equals("UNA") || 2112 n.equals("U")) { 2113 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n); 2114 return Connection.PRESENTATION_UNKNOWN; 2115 } else { 2116 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n); 2117 return CNAP_SPECIAL_CASE_NO; 2118 } 2119 } 2120 2121 /** 2122 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers 2123 * from the network to indicate different number presentations, convert them to 2124 * expected number and presentation values within the CallerInfo object. 2125 * @param number number we use to verify if we are in a corner case 2126 * @param presentation presentation value used to verify if we are in a corner case 2127 * @return the new String that should be used for the phone number 2128 */ 2129 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci, 2130 String number, int presentation) { 2131 // Obviously we return number if ci == null, but still return number if 2132 // number == null, because in these cases the correct string will still be 2133 // displayed/logged after this function returns based on the presentation value. 2134 if (ci == null || number == null) return number; 2135 2136 if (DBG) log("modifyForSpecialCnapCases: initially, number=" + number 2137 + ", presentation=" + presentation + " ci " + ci); 2138 2139 // "ABSENT NUMBER" is a possible value we could get from the network as the 2140 // phone number, so if this happens, change it to "Unknown" in the CallerInfo 2141 // and fix the presentation to be the same. 2142 if (number.equals(context.getString(R.string.absent_num)) 2143 && presentation == Connection.PRESENTATION_ALLOWED) { 2144 number = context.getString(R.string.unknown); 2145 ci.numberPresentation = Connection.PRESENTATION_UNKNOWN; 2146 } 2147 2148 // Check for other special "corner cases" for CNAP and fix them similarly. Corner 2149 // cases only apply if we received an allowed presentation from the network, so check 2150 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't 2151 // match the presentation passed in for verification (meaning we changed it previously 2152 // because it's a corner case and we're being called from a different entry point). 2153 if (ci.numberPresentation == Connection.PRESENTATION_ALLOWED 2154 || (ci.numberPresentation != presentation 2155 && presentation == Connection.PRESENTATION_ALLOWED)) { 2156 int cnapSpecialCase = checkCnapSpecialCases(number); 2157 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) { 2158 // For all special strings, change number & numberPresentation. 2159 if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) { 2160 number = context.getString(R.string.private_num); 2161 } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) { 2162 number = context.getString(R.string.unknown); 2163 } 2164 if (DBG) log("SpecialCnap: number=" + number 2165 + "; presentation now=" + cnapSpecialCase); 2166 ci.numberPresentation = cnapSpecialCase; 2167 } 2168 } 2169 if (DBG) log("modifyForSpecialCnapCases: returning number string=" + number); 2170 return number; 2171 } 2172 2173 // 2174 // Support for 3rd party phone service providers. 2175 // 2176 2177 /** 2178 * Check if all the provider's info is present in the intent. 2179 * @param intent Expected to have the provider's extra. 2180 * @return true if the intent has all the extras to build the 2181 * in-call screen's provider info overlay. 2182 */ 2183 /* package */ static boolean hasPhoneProviderExtras(Intent intent) { 2184 if (null == intent) { 2185 return false; 2186 } 2187 final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2188 final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); 2189 2190 return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri); 2191 } 2192 2193 /** 2194 * Copy all the expected extras set when a 3rd party provider is 2195 * used from the source intent to the destination one. Checks all 2196 * the required extras are present, if any is missing, none will 2197 * be copied. 2198 * @param src Intent which may contain the provider's extras. 2199 * @param dst Intent where a copy of the extras will be added if applicable. 2200 */ 2201 /* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) { 2202 if (!hasPhoneProviderExtras(src)) { 2203 Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing."); 2204 return; 2205 } 2206 2207 dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE, 2208 src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE)); 2209 dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI, 2210 src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI)); 2211 } 2212 2213 /** 2214 * Get the provider's label from the intent. 2215 * @param context to lookup the provider's package name. 2216 * @param intent with an extra set to the provider's package name. 2217 * @return The provider's application label. null if an error 2218 * occurred during the lookup of the package name or the label. 2219 */ 2220 /* package */ static CharSequence getProviderLabel(Context context, Intent intent) { 2221 String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2222 PackageManager pm = context.getPackageManager(); 2223 2224 try { 2225 ApplicationInfo info = pm.getApplicationInfo(packageName, 0); 2226 2227 return pm.getApplicationLabel(info); 2228 } catch (PackageManager.NameNotFoundException e) { 2229 return null; 2230 } 2231 } 2232 2233 /** 2234 * Get the provider's icon. 2235 * @param context to lookup the provider's icon. 2236 * @param intent with an extra set to the provider's package name. 2237 * @return The provider's application icon. null if an error occured during the icon lookup. 2238 */ 2239 /* package */ static Drawable getProviderIcon(Context context, Intent intent) { 2240 String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE); 2241 PackageManager pm = context.getPackageManager(); 2242 2243 try { 2244 return pm.getApplicationIcon(packageName); 2245 } catch (PackageManager.NameNotFoundException e) { 2246 return null; 2247 } 2248 } 2249 2250 /** 2251 * Return the gateway uri from the intent. 2252 * @param intent With the gateway uri extra. 2253 * @return The gateway URI or null if not found. 2254 */ 2255 /* package */ static Uri getProviderGatewayUri(Intent intent) { 2256 String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI); 2257 return TextUtils.isEmpty(uri) ? null : Uri.parse(uri); 2258 } 2259 2260 /** 2261 * Return a formatted version of the uri's scheme specific 2262 * part. E.g for 'tel:12345678', return '1-234-5678'. 2263 * @param uri A 'tel:' URI with the gateway phone number. 2264 * @return the provider's address (from the gateway uri) formatted 2265 * for user display. null if uri was null or its scheme was not 'tel:'. 2266 */ 2267 /* package */ static String formatProviderUri(Uri uri) { 2268 if (null != uri) { 2269 if ("tel".equals(uri.getScheme())) { 2270 return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart()); 2271 } else { 2272 return uri.toString(); 2273 } 2274 } 2275 return null; 2276 } 2277 2278 /** 2279 * Check if a phone number can be route through a 3rd party 2280 * gateway. The number must be a global phone number in numerical 2281 * form (1-800-666-SEXY won't work). 2282 * 2283 * MMI codes and the like cannot be used as a dial number for the 2284 * gateway either. 2285 * 2286 * @param number To be dialed via a 3rd party gateway. 2287 * @return true If the number can be routed through the 3rd party network. 2288 */ 2289 /* package */ static boolean isRoutableViaGateway(String number) { 2290 if (TextUtils.isEmpty(number)) { 2291 return false; 2292 } 2293 number = PhoneNumberUtils.stripSeparators(number); 2294 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) { 2295 return false; 2296 } 2297 number = PhoneNumberUtils.extractNetworkPortion(number); 2298 return PhoneNumberUtils.isGlobalPhoneNumber(number); 2299 } 2300 2301 /** 2302 * This function is called when phone answers or places a call. 2303 * Check if the phone is in a car dock or desk dock. 2304 * If yes, turn on the speaker, when no wired or BT headsets are connected. 2305 * Otherwise do nothing. 2306 */ 2307 private static void activateSpeakerIfDocked(Phone phone) { 2308 if (DBG) log("activateSpeakerIfDocked()..."); 2309 2310 if (PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_DESK || 2311 PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_CAR) { 2312 if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker."); 2313 PhoneApp app = PhoneApp.getInstance(); 2314 BluetoothHandsfree bthf = app.getBluetoothHandsfree(); 2315 2316 if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) { 2317 turnOnSpeaker(phone.getContext(), true, true); 2318 } 2319 } 2320 } 2321 2322 2323 /** 2324 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not. 2325 */ 2326 /* package */ static boolean isPhoneInEcm(Phone phone) { 2327 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) { 2328 // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true". 2329 // TODO: There ought to be a better API for this than just 2330 // exposing a system property all the way up to the app layer, 2331 // probably a method like "inEcm()" provided by the telephony 2332 // layer. 2333 String ecmMode = 2334 SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE); 2335 if (ecmMode != null) { 2336 return ecmMode.equals("true"); 2337 } 2338 } 2339 return false; 2340 } 2341 2342 /** 2343 * Returns the most appropriate Phone object to handle a call 2344 * to the specified number. 2345 * 2346 * @param cm the CallManager. 2347 * @param scheme the scheme from the data URI that the number originally came from. 2348 * @param number the phone number, or SIP address. 2349 */ 2350 public static Phone pickPhoneBasedOnNumber(CallManager cm, 2351 String scheme, String number, String primarySipUri) { 2352 if (DBG) log("pickPhoneBasedOnNumber: scheme " + scheme 2353 + ", number " + number + ", sipUri " + primarySipUri); 2354 2355 if (primarySipUri != null) { 2356 Phone phone = getSipPhoneFromUri(cm, primarySipUri); 2357 if (phone != null) return phone; 2358 } 2359 return cm.getDefaultPhone(); 2360 } 2361 2362 public static Phone getSipPhoneFromUri(CallManager cm, String target) { 2363 for (Phone phone : cm.getAllPhones()) { 2364 if (phone.getPhoneType() == Phone.PHONE_TYPE_SIP) { 2365 String sipUri = ((SipPhone) phone).getSipUri(); 2366 if (target.equals(sipUri)) { 2367 if (DBG) log("- pickPhoneBasedOnNumber:" + 2368 "found SipPhone! obj = " + phone + ", " 2369 + phone.getClass()); 2370 return phone; 2371 } 2372 } 2373 } 2374 return null; 2375 } 2376 2377 public static boolean isRealIncomingCall(Call.State state) { 2378 return (state == Call.State.INCOMING && !PhoneApp.getInstance().mCM.hasActiveFgCall()); 2379 2380 } 2381 2382 // 2383 // General phone and call state debugging/testing code 2384 // 2385 2386 private static void dumpStateForCall(Call call, String prefix) { 2387 StringBuilder b = new StringBuilder(128); 2388 b.append(prefix).append(call.getState()); 2389 b.append(" ").append(call.getPhone().getPhoneName()); 2390 b.append(" isAlive ").append(call.getState().isAlive()); 2391 b.append(" isRinging ").append(call.getState().isRinging()); 2392 b.append(" isDialing ").append(call.getState().isDialing()); 2393 b.append(" isIdle ").append(call.isIdle()); 2394 b.append(" hasConnections ").append(call.hasConnections()); 2395 Log.d(LOG_TAG, b.toString()); 2396 } 2397 2398 /* package */ static void dumpCallState() { 2399 PhoneApp app = PhoneApp.getInstance(); 2400 CallManager cm = app.mCM; 2401 Log.d(LOG_TAG, "dumpCallState():"); 2402 Log.d(LOG_TAG, "- Call state = " + cm.getState()); 2403 2404 dumpStateForCall(cm.getActiveFgCall(), " - FG call: "); 2405 dumpStateForCall(cm.getFirstActiveBgCall(), " - BG call: "); 2406 dumpStateForCall(cm.getFirstActiveRingingCall(), " - RINGING call: "); 2407 2408 final boolean hasRingingCall = cm.hasActiveRingingCall(); 2409 final boolean hasActiveCall = cm.hasActiveFgCall(); 2410 final boolean hasHoldingCall = cm.hasActiveBgCall(); 2411 final boolean allLinesTaken = hasActiveCall && hasHoldingCall; 2412 StringBuilder b = new StringBuilder(128); 2413 b.append(" - hasRingingCall ").append(hasRingingCall); 2414 b.append(" hasActiveCall ").append(hasActiveCall); 2415 b.append(" hasHoldingCall ").append(hasHoldingCall); 2416 b.append(" allLinesTaken ").append(allLinesTaken); 2417 Log.d(LOG_TAG, b.toString()); 2418 2419 Phone phone = cm.getDefaultPhone(); 2420 // On CDMA phones, dump out the CdmaPhoneCallState too: 2421 if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { 2422 if (app.cdmaPhoneCallState != null) { 2423 Log.d(LOG_TAG, " - CDMA call state: " 2424 + app.cdmaPhoneCallState.getCurrentCallState()); 2425 } else { 2426 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!"); 2427 } 2428 } 2429 2430 // Watch out: the isRinging() call below does NOT tell us anything 2431 // about the state of the telephony layer; it merely tells us whether 2432 // the Ringer manager is currently playing the ringtone. 2433 boolean ringing = app.getRinger().isRinging(); 2434 Log.d(LOG_TAG, " - Ringer state: " + ringing); 2435 } 2436 2437 /* package */ static void dumpCallState(Phone phone) { 2438 PhoneApp app = PhoneApp.getInstance(); 2439 Log.d(LOG_TAG, "dumpCallState():"); 2440 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName() 2441 + ", state = " + phone.getState()); 2442 2443 StringBuilder b = new StringBuilder(128); 2444 2445 Call call = phone.getForegroundCall(); 2446 b.setLength(0); 2447 b.append(" - FG call: ").append(call.getState()); 2448 b.append(" isAlive ").append(call.getState().isAlive()); 2449 b.append(" isRinging ").append(call.getState().isRinging()); 2450 b.append(" isDialing ").append(call.getState().isDialing()); 2451 b.append(" isIdle ").append(call.isIdle()); 2452 b.append(" hasConnections ").append(call.hasConnections()); 2453 Log.d(LOG_TAG, b.toString()); 2454 2455 call = phone.getBackgroundCall(); 2456 b.setLength(0); 2457 b.append(" - BG call: ").append(call.getState()); 2458 b.append(" isAlive ").append(call.getState().isAlive()); 2459 b.append(" isRinging ").append(call.getState().isRinging()); 2460 b.append(" isDialing ").append(call.getState().isDialing()); 2461 b.append(" isIdle ").append(call.isIdle()); 2462 b.append(" hasConnections ").append(call.hasConnections()); 2463 Log.d(LOG_TAG, b.toString()); 2464 2465 call = phone.getRingingCall(); 2466 b.setLength(0); 2467 b.append(" - RINGING call: ").append(call.getState()); 2468 b.append(" isAlive ").append(call.getState().isAlive()); 2469 b.append(" isRinging ").append(call.getState().isRinging()); 2470 b.append(" isDialing ").append(call.getState().isDialing()); 2471 b.append(" isIdle ").append(call.isIdle()); 2472 b.append(" hasConnections ").append(call.hasConnections()); 2473 Log.d(LOG_TAG, b.toString()); 2474 2475 2476 final boolean hasRingingCall = !phone.getRingingCall().isIdle(); 2477 final boolean hasActiveCall = !phone.getForegroundCall().isIdle(); 2478 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle(); 2479 final boolean allLinesTaken = hasActiveCall && hasHoldingCall; 2480 b.setLength(0); 2481 b.append(" - hasRingingCall ").append(hasRingingCall); 2482 b.append(" hasActiveCall ").append(hasActiveCall); 2483 b.append(" hasHoldingCall ").append(hasHoldingCall); 2484 b.append(" allLinesTaken ").append(allLinesTaken); 2485 Log.d(LOG_TAG, b.toString()); 2486 2487 // On CDMA phones, dump out the CdmaPhoneCallState too: 2488 if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { 2489 if (app.cdmaPhoneCallState != null) { 2490 Log.d(LOG_TAG, " - CDMA call state: " 2491 + app.cdmaPhoneCallState.getCurrentCallState()); 2492 } else { 2493 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!"); 2494 } 2495 } 2496 2497 // Watch out: the isRinging() call below does NOT tell us anything 2498 // about the state of the telephony layer; it merely tells us whether 2499 // the Ringer manager is currently playing the ringtone. 2500 boolean ringing = app.getRinger().isRinging(); 2501 Log.d(LOG_TAG, " - Ringer state: " + ringing); 2502 } 2503 2504 private static void log(String msg) { 2505 Log.d(LOG_TAG, msg); 2506 } 2507 2508 static void dumpCallManager() { 2509 Call call; 2510 CallManager cm = PhoneApp.getInstance().mCM; 2511 StringBuilder b = new StringBuilder(128); 2512 2513 Log.d(LOG_TAG, "############### dumpCallManager() ##############"); 2514 Log.d(LOG_TAG, "CallManager: " + cm 2515 + ", state = " + cm.getState()); 2516 b.setLength(0); 2517 call = cm.getActiveFgCall(); 2518 b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO "); 2519 b.append(call); 2520 b.append( " State: ").append(cm.getActiveFgCallState()); 2521 b.append( " Conn: ").append(cm.getFgCallConnections()); 2522 Log.d(LOG_TAG, b.toString()); 2523 b.setLength(0); 2524 call = cm.getFirstActiveBgCall(); 2525 b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO "); 2526 b.append(call); 2527 b.append( " State: ").append(cm.getFirstActiveBgCall().getState()); 2528 b.append( " Conn: ").append(cm.getBgCallConnections()); 2529 Log.d(LOG_TAG, b.toString()); 2530 b.setLength(0); 2531 call = cm.getFirstActiveRingingCall(); 2532 b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO "); 2533 b.append(call); 2534 b.append( " State: ").append(cm.getFirstActiveRingingCall().getState()); 2535 Log.d(LOG_TAG, b.toString()); 2536 2537 2538 2539 for (Phone phone : CallManager.getInstance().getAllPhones()) { 2540 if (phone != null) { 2541 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName() 2542 + ", state = " + phone.getState()); 2543 b.setLength(0); 2544 call = phone.getForegroundCall(); 2545 b.append(" - FG call: ").append(call); 2546 b.append( " State: ").append(call.getState()); 2547 b.append( " Conn: ").append(call.hasConnections()); 2548 Log.d(LOG_TAG, b.toString()); 2549 b.setLength(0); 2550 call = phone.getBackgroundCall(); 2551 b.append(" - BG call: ").append(call); 2552 b.append( " State: ").append(call.getState()); 2553 b.append( " Conn: ").append(call.hasConnections()); 2554 Log.d(LOG_TAG, b.toString());b.setLength(0); 2555 call = phone.getRingingCall(); 2556 b.append(" - RINGING call: ").append(call); 2557 b.append( " State: ").append(call.getState()); 2558 b.append( " Conn: ").append(call.hasConnections()); 2559 Log.d(LOG_TAG, b.toString()); 2560 } 2561 } 2562 2563 Log.d(LOG_TAG, "############## END dumpCallManager() ###############"); 2564 } 2565 2566 } 2567