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