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