Home | History | Annotate | Download | only in phone
      1 /*
      2  * Copyright (C) 2011 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 com.android.internal.telephony.CallManager;
     20 import com.android.internal.telephony.Phone;
     21 import com.android.internal.telephony.PhoneConstants;
     22 import com.android.internal.telephony.TelephonyCapabilities;
     23 import com.android.phone.CallGatewayManager.RawGatewayInfo;
     24 import com.android.phone.Constants.CallStatusCode;
     25 import com.android.phone.ErrorDialogActivity;
     26 
     27 import android.content.Intent;
     28 import android.net.Uri;
     29 import android.os.Handler;
     30 import android.os.Message;
     31 import android.os.SystemProperties;
     32 import android.provider.CallLog.Calls;
     33 import android.telephony.PhoneNumberUtils;
     34 import android.telephony.ServiceState;
     35 import android.util.Log;
     36 
     37 /**
     38  * Phone app module in charge of "call control".
     39  *
     40  * This is a singleton object which acts as the interface to the telephony layer
     41  * (and other parts of the Android framework) for all user-initiated telephony
     42  * functionality, like making outgoing calls.
     43  *
     44  * This functionality includes things like:
     45  *   - actually running the placeCall() method and handling errors or retries
     46  *   - running the whole "emergency call in airplane mode" sequence
     47  *   - running the state machine of MMI sequences
     48  *   - restoring/resetting mute and speaker state when a new call starts
     49  *   - updating the prox sensor wake lock state
     50  *   - resolving what the voicemail: intent should mean (and making the call)
     51  *
     52  * The single CallController instance stays around forever; it's not tied
     53  * to the lifecycle of any particular Activity (like the InCallScreen).
     54  * There's also no implementation of onscreen UI here (that's all in InCallScreen).
     55  *
     56  * Note that this class does not handle asynchronous events from the telephony
     57  * layer, like reacting to an incoming call; see CallNotifier for that.  This
     58  * class purely handles actions initiated by the user, like outgoing calls.
     59  */
     60 public class CallController extends Handler {
     61     private static final String TAG = "CallController";
     62     private static final boolean DBG =
     63             (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
     64     // Do not check in with VDBG = true, since that may write PII to the system log.
     65     private static final boolean VDBG = false;
     66 
     67     /** The singleton CallController instance. */
     68     private static CallController sInstance;
     69 
     70     final private PhoneGlobals mApp;
     71     final private CallManager mCM;
     72     final private CallLogger mCallLogger;
     73     final private CallGatewayManager mCallGatewayManager;
     74 
     75     /** Helper object for emergency calls in some rare use cases.  Created lazily. */
     76     private EmergencyCallHelper mEmergencyCallHelper;
     77 
     78 
     79     //
     80     // Message codes; see handleMessage().
     81     //
     82 
     83     private static final int THREEWAY_CALLERINFO_DISPLAY_DONE = 1;
     84 
     85 
     86     //
     87     // Misc constants.
     88     //
     89 
     90     // Amount of time the UI should display "Dialing" when initiating a CDMA
     91     // 3way call.  (See comments on the THRWAY_ACTIVE case in
     92     // placeCallInternal() for more info.)
     93     private static final int THREEWAY_CALLERINFO_DISPLAY_TIME = 3000; // msec
     94 
     95 
     96     /**
     97      * Initialize the singleton CallController instance.
     98      *
     99      * This is only done once, at startup, from PhoneApp.onCreate().
    100      * From then on, the CallController instance is available via the
    101      * PhoneApp's public "callController" field, which is why there's no
    102      * getInstance() method here.
    103      */
    104     /* package */ static CallController init(PhoneGlobals app, CallLogger callLogger,
    105             CallGatewayManager callGatewayManager) {
    106         synchronized (CallController.class) {
    107             if (sInstance == null) {
    108                 sInstance = new CallController(app, callLogger, callGatewayManager);
    109             } else {
    110                 Log.wtf(TAG, "init() called multiple times!  sInstance = " + sInstance);
    111             }
    112             return sInstance;
    113         }
    114     }
    115 
    116     /**
    117      * Private constructor (this is a singleton).
    118      * @see init()
    119      */
    120     private CallController(PhoneGlobals app, CallLogger callLogger,
    121             CallGatewayManager callGatewayManager) {
    122         if (DBG) log("CallController constructor: app = " + app);
    123         mApp = app;
    124         mCM = app.mCM;
    125         mCallLogger = callLogger;
    126         mCallGatewayManager = callGatewayManager;
    127     }
    128 
    129     @Override
    130     public void handleMessage(Message msg) {
    131         if (VDBG) log("handleMessage: " + msg);
    132         switch (msg.what) {
    133 
    134             case THREEWAY_CALLERINFO_DISPLAY_DONE:
    135                 if (DBG) log("THREEWAY_CALLERINFO_DISPLAY_DONE...");
    136 
    137                 if (mApp.cdmaPhoneCallState.getCurrentCallState()
    138                     == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
    139                     // Reset the mThreeWayCallOrigStateDialing state
    140                     mApp.cdmaPhoneCallState.setThreeWayCallOrigState(false);
    141 
    142                     mApp.getCallModeler().setCdmaOutgoing3WayCall(null);
    143                 }
    144                 break;
    145 
    146             default:
    147                 Log.wtf(TAG, "handleMessage: unexpected code: " + msg);
    148                 break;
    149         }
    150     }
    151 
    152     //
    153     // Outgoing call sequence
    154     //
    155 
    156     /**
    157      * Initiate an outgoing call.
    158      *
    159      * Here's the most typical outgoing call sequence:
    160      *
    161      *  (1) OutgoingCallBroadcaster receives a CALL intent and sends the
    162      *      NEW_OUTGOING_CALL broadcast
    163      *
    164      *  (2) The broadcast finally reaches OutgoingCallReceiver, which stashes
    165      *      away a copy of the original CALL intent and launches
    166      *      SipCallOptionHandler
    167      *
    168      *  (3) SipCallOptionHandler decides whether this is a PSTN or SIP call (and
    169      *      in some cases brings up a dialog to let the user choose), and
    170      *      ultimately calls CallController.placeCall() (from the
    171      *      setResultAndFinish() method) with the stashed-away intent from step
    172      *      (2) as the "intent" parameter.
    173      *
    174      *  (4) Here in CallController.placeCall() we read the phone number or SIP
    175      *      address out of the intent and actually initiate the call, and
    176      *      simultaneously launch the InCallScreen to display the in-call UI.
    177      *
    178      *  (5) We handle various errors by directing the InCallScreen to
    179      *      display error messages or dialogs (via the InCallUiState
    180      *      "pending call status code" flag), and in some cases we also
    181      *      sometimes continue working in the background to resolve the
    182      *      problem (like in the case of an emergency call while in
    183      *      airplane mode).  Any time that some onscreen indication to the
    184      *      user needs to change, we update the "status dialog" info in
    185      *      the inCallUiState and (re)launch the InCallScreen to make sure
    186      *      it's visible.
    187      */
    188     public void placeCall(Intent intent) {
    189         log("placeCall()...  intent = " + intent);
    190         if (VDBG) log("                extras = " + intent.getExtras());
    191 
    192         // TODO: Do we need to hold a wake lock while this method runs?
    193         //       Or did we already acquire one somewhere earlier
    194         //       in this sequence (like when we first received the CALL intent?)
    195 
    196         if (intent == null) {
    197             Log.wtf(TAG, "placeCall: called with null intent");
    198             throw new IllegalArgumentException("placeCall: called with null intent");
    199         }
    200 
    201         String action = intent.getAction();
    202         Uri uri = intent.getData();
    203         if (uri == null) {
    204             Log.wtf(TAG, "placeCall: intent had no data");
    205             throw new IllegalArgumentException("placeCall: intent had no data");
    206         }
    207 
    208         String scheme = uri.getScheme();
    209         String number = PhoneNumberUtils.getNumberFromIntent(intent, mApp);
    210         if (VDBG) {
    211             log("- action: " + action);
    212             log("- uri: " + uri);
    213             log("- scheme: " + scheme);
    214             log("- number: " + number);
    215         }
    216 
    217         // This method should only be used with the various flavors of CALL
    218         // intents.  (It doesn't make sense for any other action to trigger an
    219         // outgoing call!)
    220         if (!(Intent.ACTION_CALL.equals(action)
    221               || Intent.ACTION_CALL_EMERGENCY.equals(action)
    222               || Intent.ACTION_CALL_PRIVILEGED.equals(action))) {
    223             Log.wtf(TAG, "placeCall: unexpected intent action " + action);
    224             throw new IllegalArgumentException("Unexpected action: " + action);
    225         }
    226 
    227         // Check to see if this is an OTASP call (the "activation" call
    228         // used to provision CDMA devices), and if so, do some
    229         // OTASP-specific setup.
    230         Phone phone = mApp.mCM.getDefaultPhone();
    231         if (TelephonyCapabilities.supportsOtasp(phone)) {
    232             checkForOtaspCall(intent);
    233         }
    234 
    235         // Clear out the "restore mute state" flag since we're
    236         // initiating a brand-new call.
    237         //
    238         // (This call to setRestoreMuteOnInCallResume(false) informs the
    239         // phone app that we're dealing with a new connection
    240         // (i.e. placing an outgoing call, and NOT handling an aborted
    241         // "Add Call" request), so we should let the mute state be handled
    242         // by the PhoneUtils phone state change handler.)
    243         mApp.setRestoreMuteOnInCallResume(false);
    244 
    245         CallStatusCode status = placeCallInternal(intent);
    246 
    247         switch (status) {
    248             // Call was placed successfully:
    249             case SUCCESS:
    250             case EXITED_ECM:
    251                 if (DBG) log("==> placeCall(): success from placeCallInternal(): " + status);
    252                 break;
    253 
    254             default:
    255                 // Any other status code is a failure.
    256                 log("==> placeCall(): failure code from placeCallInternal(): " + status);
    257                 // Handle the various error conditions that can occur when
    258                 // initiating an outgoing call, typically by directing the
    259                 // InCallScreen to display a diagnostic message (via the
    260                 // "pending call status code" flag.)
    261                 handleOutgoingCallError(status);
    262                 break;
    263         }
    264 
    265         // Finally, regardless of whether we successfully initiated the
    266         // outgoing call or not, force the InCallScreen to come to the
    267         // foreground.
    268         //
    269         // (For successful calls the the user will just see the normal
    270         // in-call UI.  Or if there was an error, the InCallScreen will
    271         // notice the InCallUiState pending call status code flag and display an
    272         // error indication instead.)
    273     }
    274 
    275     /**
    276      * Actually make a call to whomever the intent tells us to.
    277      *
    278      * Note that there's no need to explicitly update (or refresh) the
    279      * in-call UI at any point in this method, since a fresh InCallScreen
    280      * instance will be launched automatically after we return (see
    281      * placeCall() above.)
    282      *
    283      * @param intent the CALL intent describing whom to call
    284      * @return CallStatusCode.SUCCESS if we successfully initiated an
    285      *    outgoing call.  If there was some kind of failure, return one of
    286      *    the other CallStatusCode codes indicating what went wrong.
    287      */
    288     private CallStatusCode placeCallInternal(Intent intent) {
    289         if (DBG) log("placeCallInternal()...  intent = " + intent);
    290 
    291         // TODO: This method is too long.  Break it down into more
    292         // manageable chunks.
    293 
    294         final Uri uri = intent.getData();
    295         final String scheme = (uri != null) ? uri.getScheme() : null;
    296         String number;
    297         Phone phone = null;
    298 
    299         // Check the current ServiceState to make sure it's OK
    300         // to even try making a call.
    301         CallStatusCode okToCallStatus = checkIfOkToInitiateOutgoingCall(
    302                 mCM.getServiceState());
    303 
    304         // TODO: Streamline the logic here.  Currently, the code is
    305         // unchanged from its original form in InCallScreen.java.  But we
    306         // should fix a couple of things:
    307         // - Don't call checkIfOkToInitiateOutgoingCall() more than once
    308         // - Wrap the try/catch for VoiceMailNumberMissingException
    309         //   around *only* the call that can throw that exception.
    310 
    311         try {
    312             number = PhoneUtils.getInitialNumber(intent);
    313             if (VDBG) log("- actual number to dial: '" + number + "'");
    314 
    315             // find the phone first
    316             // TODO Need a way to determine which phone to place the call
    317             // It could be determined by SIP setting, i.e. always,
    318             // or by number, i.e. for international,
    319             // or by user selection, i.e., dialog query,
    320             // or any of combinations
    321             String sipPhoneUri = intent.getStringExtra(
    322                     OutgoingCallBroadcaster.EXTRA_SIP_PHONE_URI);
    323             phone = PhoneUtils.pickPhoneBasedOnNumber(mCM, scheme, number, sipPhoneUri);
    324             if (VDBG) log("- got Phone instance: " + phone + ", class = " + phone.getClass());
    325 
    326             // update okToCallStatus based on new phone
    327             okToCallStatus = checkIfOkToInitiateOutgoingCall(
    328                     phone.getServiceState().getState());
    329 
    330         } catch (PhoneUtils.VoiceMailNumberMissingException ex) {
    331             // If the call status is NOT in an acceptable state, it
    332             // may effect the way the voicemail number is being
    333             // retrieved.  Mask the VoiceMailNumberMissingException
    334             // with the underlying issue of the phone state.
    335             if (okToCallStatus != CallStatusCode.SUCCESS) {
    336                 if (DBG) log("Voicemail number not reachable in current SIM card state.");
    337                 return okToCallStatus;
    338             }
    339             if (DBG) log("VoiceMailNumberMissingException from getInitialNumber()");
    340             return CallStatusCode.VOICEMAIL_NUMBER_MISSING;
    341         }
    342 
    343         if (number == null) {
    344             Log.w(TAG, "placeCall: couldn't get a phone number from Intent " + intent);
    345             return CallStatusCode.NO_PHONE_NUMBER_SUPPLIED;
    346         }
    347 
    348 
    349         // Sanity-check that ACTION_CALL_EMERGENCY is used if and only if
    350         // this is a call to an emergency number
    351         // (This is just a sanity-check; this policy *should* really be
    352         // enforced in OutgoingCallBroadcaster.onCreate(), which is the
    353         // main entry point for the CALL and CALL_* intents.)
    354         boolean isEmergencyNumber = PhoneNumberUtils.isLocalEmergencyNumber(number, mApp);
    355         boolean isPotentialEmergencyNumber =
    356                 PhoneNumberUtils.isPotentialLocalEmergencyNumber(number, mApp);
    357         boolean isEmergencyIntent = Intent.ACTION_CALL_EMERGENCY.equals(intent.getAction());
    358 
    359         if (isPotentialEmergencyNumber && !isEmergencyIntent) {
    360             Log.e(TAG, "Non-CALL_EMERGENCY Intent " + intent
    361                     + " attempted to call potential emergency number " + number
    362                     + ".");
    363             return CallStatusCode.CALL_FAILED;
    364         } else if (!isPotentialEmergencyNumber && isEmergencyIntent) {
    365             Log.e(TAG, "Received CALL_EMERGENCY Intent " + intent
    366                     + " with non-potential-emergency number " + number
    367                     + " -- failing call.");
    368             return CallStatusCode.CALL_FAILED;
    369         }
    370 
    371         // If we're trying to call an emergency number, then it's OK to
    372         // proceed in certain states where we'd otherwise bring up
    373         // an error dialog:
    374         // - If we're in EMERGENCY_ONLY mode, then (obviously) you're allowed
    375         //   to dial emergency numbers.
    376         // - If we're OUT_OF_SERVICE, we still attempt to make a call,
    377         //   since the radio will register to any available network.
    378 
    379         if (isEmergencyNumber
    380             && ((okToCallStatus == CallStatusCode.EMERGENCY_ONLY)
    381                 || (okToCallStatus == CallStatusCode.OUT_OF_SERVICE))) {
    382             if (DBG) log("placeCall: Emergency number detected with status = " + okToCallStatus);
    383             okToCallStatus = CallStatusCode.SUCCESS;
    384             if (DBG) log("==> UPDATING status to: " + okToCallStatus);
    385         }
    386 
    387         if (okToCallStatus != CallStatusCode.SUCCESS) {
    388             // If this is an emergency call, launch the EmergencyCallHelperService
    389             // to turn on the radio and retry the call.
    390             if (isEmergencyNumber && (okToCallStatus == CallStatusCode.POWER_OFF)) {
    391                 Log.i(TAG, "placeCall: Trying to make emergency call while POWER_OFF!");
    392 
    393                 // If needed, lazily instantiate an EmergencyCallHelper instance.
    394                 synchronized (this) {
    395                     if (mEmergencyCallHelper == null) {
    396                         mEmergencyCallHelper = new EmergencyCallHelper(this);
    397                     }
    398                 }
    399 
    400                 // ...and kick off the "emergency call from airplane mode" sequence.
    401                 mEmergencyCallHelper.startEmergencyCallFromAirplaneModeSequence(number);
    402 
    403                 // Finally, return CallStatusCode.SUCCESS right now so
    404                 // that the in-call UI will remain visible (in order to
    405                 // display the progress indication.)
    406                 // TODO: or maybe it would be more clear to return a whole
    407                 // new CallStatusCode called "TURNING_ON_RADIO" here.
    408                 // That way, we'd update inCallUiState.progressIndication from
    409                 // the handleOutgoingCallError() method, rather than here.
    410                 return CallStatusCode.SUCCESS;
    411             } else {
    412                 // Otherwise, just return the (non-SUCCESS) status code
    413                 // back to our caller.
    414                 if (DBG) log("==> placeCallInternal(): non-success status: " + okToCallStatus);
    415 
    416                 // Log failed call.
    417                 // Note: Normally, many of these values we gather from the Connection object but
    418                 // since no such object is created for unconnected calls, we have to build them
    419                 // manually.
    420                 // TODO(santoscordon): Try to restructure code so that we can handle failure-
    421                 // condition call logging in a single place (placeCall()) that also has access to
    422                 // the number we attempted to dial (not placeCall()).
    423                 mCallLogger.logCall(null /* callerInfo */, number, 0 /* presentation */,
    424                         Calls.OUTGOING_TYPE, System.currentTimeMillis(), 0 /* duration */);
    425 
    426                 return okToCallStatus;
    427             }
    428         }
    429 
    430         // We have a valid number, so try to actually place a call:
    431         // make sure we pass along the intent's URI which is a
    432         // reference to the contact. We may have a provider gateway
    433         // phone number to use for the outgoing call.
    434         Uri contactUri = intent.getData();
    435 
    436         // If a gateway is used, extract the data here and pass that into placeCall.
    437         final RawGatewayInfo rawGatewayInfo = mCallGatewayManager.getRawGatewayInfo(intent, number);
    438 
    439         // Watch out: PhoneUtils.placeCall() returns one of the
    440         // CALL_STATUS_* constants, not a CallStatusCode enum value.
    441         int callStatus = PhoneUtils.placeCall(mApp,
    442                                               phone,
    443                                               number,
    444                                               contactUri,
    445                                               (isEmergencyNumber || isEmergencyIntent),
    446                                               rawGatewayInfo,
    447                                               mCallGatewayManager);
    448 
    449         switch (callStatus) {
    450             case PhoneUtils.CALL_STATUS_DIALED:
    451                 if (VDBG) log("placeCall: PhoneUtils.placeCall() succeeded for regular call '"
    452                              + number + "'.");
    453 
    454 
    455                 // TODO(OTASP): still need more cleanup to simplify the mApp.cdma*State objects:
    456                 // - Rather than checking inCallUiState.inCallScreenMode, the
    457                 //   code here could also check for
    458                 //   app.getCdmaOtaInCallScreenUiState() returning NORMAL.
    459                 // - But overall, app.inCallUiState.inCallScreenMode and
    460                 //   app.cdmaOtaInCallScreenUiState.state are redundant.
    461                 //   Combine them.
    462 
    463                 boolean voicemailUriSpecified = scheme != null && scheme.equals("voicemail");
    464                 // Check for an obscure ECM-related scenario: If the phone
    465                 // is currently in ECM (Emergency callback mode) and we
    466                 // dial a non-emergency number, that automatically
    467                 // *cancels* ECM.  So warn the user about it.
    468                 // (See InCallScreen.showExitingECMDialog() for more info.)
    469                 boolean exitedEcm = false;
    470                 if (PhoneUtils.isPhoneInEcm(phone) && !isEmergencyNumber) {
    471                     Log.i(TAG, "About to exit ECM because of an outgoing non-emergency call");
    472                     exitedEcm = true;  // this will cause us to return EXITED_ECM from this method
    473                 }
    474 
    475                 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
    476                     // Start the timer for 3 Way CallerInfo
    477                     if (mApp.cdmaPhoneCallState.getCurrentCallState()
    478                             == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
    479                         //Unmute for the second MO call
    480                         PhoneUtils.setMute(false);
    481 
    482                         // This is a "CDMA 3-way call", which means that you're dialing a
    483                         // 2nd outgoing call while a previous call is already in progress.
    484                         //
    485                         // Due to the limitations of CDMA this call doesn't actually go
    486                         // through the DIALING/ALERTING states, so we can't tell for sure
    487                         // when (or if) it's actually answered.  But we want to show
    488                         // *some* indication of what's going on in the UI, so we "fake it"
    489                         // by displaying the "Dialing" state for 3 seconds.
    490 
    491                         // Set the mThreeWayCallOrigStateDialing state to true
    492                         mApp.cdmaPhoneCallState.setThreeWayCallOrigState(true);
    493 
    494                         // Schedule the "Dialing" indication to be taken down in 3 seconds:
    495                         sendEmptyMessageDelayed(THREEWAY_CALLERINFO_DISPLAY_DONE,
    496                                                 THREEWAY_CALLERINFO_DISPLAY_TIME);
    497                     }
    498                 }
    499 
    500                 // Success!
    501                 if (exitedEcm) {
    502                     return CallStatusCode.EXITED_ECM;
    503                 } else {
    504                     return CallStatusCode.SUCCESS;
    505                 }
    506 
    507             case PhoneUtils.CALL_STATUS_DIALED_MMI:
    508                 if (DBG) log("placeCall: specified number was an MMI code: '" + number + "'.");
    509                 // The passed-in number was an MMI code, not a regular phone number!
    510                 // This isn't really a failure; the Dialer may have deliberately
    511                 // fired an ACTION_CALL intent to dial an MMI code, like for a
    512                 // USSD call.
    513                 //
    514                 // Presumably an MMI_INITIATE message will come in shortly
    515                 // (and we'll bring up the "MMI Started" dialog), or else
    516                 // an MMI_COMPLETE will come in (which will take us to a
    517                 // different Activity; see PhoneUtils.displayMMIComplete()).
    518                 return CallStatusCode.DIALED_MMI;
    519 
    520             case PhoneUtils.CALL_STATUS_FAILED:
    521                 Log.w(TAG, "placeCall: PhoneUtils.placeCall() FAILED for number '"
    522                       + number + "'.");
    523                 // We couldn't successfully place the call; there was some
    524                 // failure in the telephony layer.
    525 
    526                 // Log failed call.
    527                 mCallLogger.logCall(null /* callerInfo */, number, 0 /* presentation */,
    528                         Calls.OUTGOING_TYPE, System.currentTimeMillis(), 0 /* duration */);
    529 
    530                 return CallStatusCode.CALL_FAILED;
    531 
    532             default:
    533                 Log.wtf(TAG, "placeCall: unknown callStatus " + callStatus
    534                         + " from PhoneUtils.placeCall() for number '" + number + "'.");
    535                 return CallStatusCode.SUCCESS;  // Try to continue anyway...
    536         }
    537     }
    538 
    539     /**
    540      * Checks the current ServiceState to make sure it's OK
    541      * to try making an outgoing call to the specified number.
    542      *
    543      * @return CallStatusCode.SUCCESS if it's OK to try calling the specified
    544      *    number.  If not, like if the radio is powered off or we have no
    545      *    signal, return one of the other CallStatusCode codes indicating what
    546      *    the problem is.
    547      */
    548     private CallStatusCode checkIfOkToInitiateOutgoingCall(int state) {
    549         if (VDBG) log("checkIfOkToInitiateOutgoingCall: ServiceState = " + state);
    550 
    551         switch (state) {
    552             case ServiceState.STATE_IN_SERVICE:
    553                 // Normal operation.  It's OK to make outgoing calls.
    554                 return CallStatusCode.SUCCESS;
    555 
    556             case ServiceState.STATE_POWER_OFF:
    557                 // Radio is explictly powered off.
    558                 return CallStatusCode.POWER_OFF;
    559 
    560             case ServiceState.STATE_EMERGENCY_ONLY:
    561                 // The phone is registered, but locked. Only emergency
    562                 // numbers are allowed.
    563                 // Note that as of Android 2.0 at least, the telephony layer
    564                 // does not actually use ServiceState.STATE_EMERGENCY_ONLY,
    565                 // mainly since there's no guarantee that the radio/RIL can
    566                 // make this distinction.  So in practice the
    567                 // CallStatusCode.EMERGENCY_ONLY state and the string
    568                 // "incall_error_emergency_only" are totally unused.
    569                 return CallStatusCode.EMERGENCY_ONLY;
    570 
    571             case ServiceState.STATE_OUT_OF_SERVICE:
    572                 // No network connection.
    573                 return CallStatusCode.OUT_OF_SERVICE;
    574 
    575             default:
    576                 throw new IllegalStateException("Unexpected ServiceState: " + state);
    577         }
    578     }
    579 
    580 
    581 
    582     /**
    583      * Handles the various error conditions that can occur when initiating
    584      * an outgoing call.
    585      *
    586      * Most error conditions are "handled" by simply displaying an error
    587      * message to the user.
    588      *
    589      * @param status one of the CallStatusCode error codes.
    590      */
    591     private void handleOutgoingCallError(CallStatusCode status) {
    592         if (DBG) log("handleOutgoingCallError(): status = " + status);
    593         final Intent intent = new Intent(mApp, ErrorDialogActivity.class);
    594         int errorMessageId = -1;
    595         switch (status) {
    596             case SUCCESS:
    597                 // This case shouldn't happen; you're only supposed to call
    598                 // handleOutgoingCallError() if there was actually an error!
    599                 Log.wtf(TAG, "handleOutgoingCallError: SUCCESS isn't an error");
    600                 break;
    601 
    602             case CALL_FAILED:
    603                 // We couldn't successfully place the call; there was some
    604                 // failure in the telephony layer.
    605                 // TODO: Need UI spec for this failure case; for now just
    606                 // show a generic error.
    607                 errorMessageId = R.string.incall_error_call_failed;
    608                 break;
    609             case POWER_OFF:
    610                 // Radio is explictly powered off, presumably because the
    611                 // device is in airplane mode.
    612                 //
    613                 // TODO: For now this UI is ultra-simple: we simply display
    614                 // a message telling the user to turn off airplane mode.
    615                 // But it might be nicer for the dialog to offer the option
    616                 // to turn the radio on right there (and automatically retry
    617                 // the call once network registration is complete.)
    618                 errorMessageId = R.string.incall_error_power_off;
    619                 break;
    620             case EMERGENCY_ONLY:
    621                 // Only emergency numbers are allowed, but we tried to dial
    622                 // a non-emergency number.
    623                 // (This state is currently unused; see comments above.)
    624                 errorMessageId = R.string.incall_error_emergency_only;
    625                 break;
    626             case OUT_OF_SERVICE:
    627                 // No network connection.
    628                 errorMessageId = R.string.incall_error_out_of_service;
    629                 break;
    630             case NO_PHONE_NUMBER_SUPPLIED:
    631                 // The supplied Intent didn't contain a valid phone number.
    632                 // (This is rare and should only ever happen with broken
    633                 // 3rd-party apps.) For now just show a generic error.
    634                 errorMessageId = R.string.incall_error_no_phone_number_supplied;
    635                 break;
    636 
    637             case VOICEMAIL_NUMBER_MISSING:
    638                 // Bring up the "Missing Voicemail Number" dialog, which
    639                 // will ultimately take us to some other Activity (or else
    640                 // just bail out of this activity.)
    641 
    642                 // Send a request to the InCallScreen to display the
    643                 // "voicemail missing" dialog when it (the InCallScreen)
    644                 // comes to the foreground.
    645                 intent.putExtra(ErrorDialogActivity.SHOW_MISSING_VOICEMAIL_NO_DIALOG_EXTRA, true);
    646                 break;
    647 
    648             case DIALED_MMI:
    649                 // Our initial phone number was actually an MMI sequence.
    650                 // There's no real "error" here, but we do bring up the
    651                 // a Toast (as requested of the New UI paradigm).
    652                 //
    653                 // In-call MMIs do not trigger the normal MMI Initiate
    654                 // Notifications, so we should notify the user here.
    655                 // Otherwise, the code in PhoneUtils.java should handle
    656                 // user notifications in the form of Toasts or Dialogs.
    657                 //
    658                 // TODO: Rather than launching a toast from here, it would
    659                 // be cleaner to just set a pending call status code here,
    660                 // and then let the InCallScreen display the toast...
    661                 final Intent mmiIntent = new Intent(mApp, MMIDialogActivity.class);
    662                 mmiIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
    663                         Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    664                 mApp.startActivity(mmiIntent);
    665                 return;
    666             default:
    667                 Log.wtf(TAG, "handleOutgoingCallError: unexpected status code " + status);
    668                 // Show a generic "call failed" error.
    669                 errorMessageId = R.string.incall_error_call_failed;
    670                 break;
    671         }
    672         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    673         if (errorMessageId != -1) {
    674             intent.putExtra(ErrorDialogActivity.ERROR_MESSAGE_ID_EXTRA, errorMessageId);
    675         }
    676         mApp.startActivity(intent);
    677     }
    678 
    679     /**
    680      * Checks the current outgoing call to see if it's an OTASP call (the
    681      * "activation" call used to provision CDMA devices).  If so, do any
    682      * necessary OTASP-specific setup before actually placing the call.
    683      */
    684     private void checkForOtaspCall(Intent intent) {
    685         if (OtaUtils.isOtaspCallIntent(intent)) {
    686             Log.i(TAG, "checkForOtaspCall: handling OTASP intent! " + intent);
    687 
    688             // ("OTASP-specific setup" basically means creating and initializing
    689             // the OtaUtils instance.  Note that this setup needs to be here in
    690             // the CallController.placeCall() sequence, *not* in
    691             // OtaUtils.startInteractiveOtasp(), since it's also possible to
    692             // start an OTASP call by manually dialing "*228" (in which case
    693             // OtaUtils.startInteractiveOtasp() never gets run at all.)
    694             OtaUtils.setupOtaspCall(intent);
    695         } else {
    696             if (DBG) log("checkForOtaspCall: not an OTASP call.");
    697         }
    698     }
    699 
    700 
    701     //
    702     // Debugging
    703     //
    704 
    705     private static void log(String msg) {
    706         Log.d(TAG, msg);
    707     }
    708 }
    709