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