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