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