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