1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.phone;
18 
19 import android.Manifest;
20 import android.app.Activity;
21 import android.app.ActivityManagerNative;
22 import android.app.AlertDialog;
23 import android.app.AppOpsManager;
24 import android.app.Dialog;
25 import android.content.BroadcastReceiver;
26 import android.content.Context;
27 import android.content.DialogInterface;
28 import android.content.Intent;
29 import android.content.res.Configuration;
30 import android.content.res.Resources;
31 import android.net.Uri;
32 import android.os.Bundle;
33 import android.os.Handler;
34 import android.os.Message;
35 import android.os.RemoteException;
36 import android.os.SystemProperties;
37 import android.os.UserHandle;
38 import android.telecom.PhoneAccount;
39 import android.telephony.PhoneNumberUtils;
40 import android.text.TextUtils;
41 import android.util.Log;
42 import android.view.View;
43 import android.widget.ProgressBar;
44 
45 import com.android.internal.telephony.Phone;
46 import com.android.internal.telephony.PhoneConstants;
47 import com.android.internal.telephony.TelephonyCapabilities;
48 
49 /**
50  * OutgoingCallBroadcaster receives CALL and CALL_PRIVILEGED Intents, and broadcasts the
51  * ACTION_NEW_OUTGOING_CALL intent. ACTION_NEW_OUTGOING_CALL is an ordered broadcast intent which
52  * contains the phone number being dialed. Applications can use this intent to (1) see which numbers
53  * are being dialed, (2) redirect a call (change the number being dialed), or (3) prevent a call
54  * from being placed.
55  *
56  * After the other applications have had a chance to see the
57  * ACTION_NEW_OUTGOING_CALL intent, it finally reaches the
58  * {@link OutgoingCallReceiver}, which passes the (possibly modified)
59  * intent on to the {@link SipCallOptionHandler}, which will
60  * ultimately start the call using the CallController.placeCall() API.
61  *
62  * Calls where no number is present (like for a CDMA "empty flash" or a nonexistent voicemail
63  * number) are exempt from being broadcast.
64  * Calls to emergency numbers are still broadcast for informative purposes. The call is placed
65  * prior to sending ACTION_NEW_OUTGOING_CALL and cannot be redirected nor prevented.
66  */
67 public class OutgoingCallBroadcaster extends Activity
68         implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
69 
70     private static final String TAG = "OutgoingCallBroadcaster";
71     private static final boolean DBG =
72             (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
73     // Do not check in with VDBG = true, since that may write PII to the system log.
74     private static final boolean VDBG = false;
75 
76     public static final String ACTION_SIP_SELECT_PHONE = "com.android.phone.SIP_SELECT_PHONE";
77     public static final String EXTRA_ALREADY_CALLED = "android.phone.extra.ALREADY_CALLED";
78     public static final String EXTRA_ORIGINAL_URI = "android.phone.extra.ORIGINAL_URI";
79     public static final String EXTRA_NEW_CALL_INTENT = "android.phone.extra.NEW_CALL_INTENT";
80     public static final String EXTRA_SIP_PHONE_URI = "android.phone.extra.SIP_PHONE_URI";
81     public static final String EXTRA_ACTUAL_NUMBER_TO_DIAL =
82             "android.phone.extra.ACTUAL_NUMBER_TO_DIAL";
83     public static final String EXTRA_THIRD_PARTY_CALL_COMPONENT =
84             "android.phone.extra.THIRD_PARTY_CALL_COMPONENT";
85 
86     /**
87      * Identifier for intent extra for sending an empty Flash message for
88      * CDMA networks. This message is used by the network to simulate a
89      * press/depress of the "hookswitch" of a landline phone. Aka "empty flash".
90      *
91      * TODO: Receiving an intent extra to tell the phone to send this flash is a
92      * temporary measure. To be replaced with an external ITelephony call in the future.
93      * TODO: Keep in sync with the string defined in TwelveKeyDialer.java in Contacts app
94      * until this is replaced with the ITelephony API.
95      */
96     public static final String EXTRA_SEND_EMPTY_FLASH =
97             "com.android.phone.extra.SEND_EMPTY_FLASH";
98 
99     // Dialog IDs
100     private static final int DIALOG_NOT_VOICE_CAPABLE = 1;
101 
102     /** Note message codes < 100 are reserved for the PhoneApp. */
103     private static final int EVENT_OUTGOING_CALL_TIMEOUT = 101;
104     private static final int EVENT_DELAYED_FINISH = 102;
105 
106     private static final int OUTGOING_CALL_TIMEOUT_THRESHOLD = 2000; // msec
107     private static final int DELAYED_FINISH_TIME = 2000; // msec
108 
109     /**
110      * ProgressBar object with "spinner" style, which will be shown if we take more than
111      * {@link #EVENT_OUTGOING_CALL_TIMEOUT} msec to handle the incoming Intent.
112      */
113     private ProgressBar mWaitingSpinner;
114     private final Handler mHandler = new Handler() {
115         @Override
116         public void handleMessage(Message msg) {
117             if (msg.what == EVENT_OUTGOING_CALL_TIMEOUT) {
118                 Log.i(TAG, "Outgoing call takes too long. Showing the spinner.");
119                 mWaitingSpinner.setVisibility(View.VISIBLE);
120             } else if (msg.what == EVENT_DELAYED_FINISH) {
121                 finish();
122             } else {
123                 Log.wtf(TAG, "Unknown message id: " + msg.what);
124             }
125         }
126     };
127 
128     /**
129      * Starts the delayed finish() of OutgoingCallBroadcaster in order to give the UI
130      * some time to start up.
131      */
startDelayedFinish()132     private void startDelayedFinish() {
133         mHandler.sendEmptyMessageDelayed(EVENT_DELAYED_FINISH, DELAYED_FINISH_TIME);
134     }
135 
136     /**
137      * OutgoingCallReceiver finishes NEW_OUTGOING_CALL broadcasts, starting
138      * the InCallScreen if the broadcast has not been canceled, possibly with
139      * a modified phone number and optional provider info (uri + package name + remote views.)
140      */
141     public class OutgoingCallReceiver extends BroadcastReceiver {
142         private static final String TAG = "OutgoingCallReceiver";
143 
144         @Override
onReceive(Context context, Intent intent)145         public void onReceive(Context context, Intent intent) {
146             mHandler.removeMessages(EVENT_OUTGOING_CALL_TIMEOUT);
147             final boolean isAttemptingCall = doReceive(context, intent);
148             if (DBG) Log.v(TAG, "OutgoingCallReceiver is going to finish the Activity itself.");
149 
150             // We cannot finish the activity immediately here because it would cause the temporary
151             // black screen of OutgoingBroadcaster to go away and we need it to stay up until the
152             // UI (in a different process) has time to come up.
153             // However, if we know we are not attemping a call, we need to finish the activity
154             // immediately so that subsequent CALL intents will retrigger a new
155             // OutgoingCallReceiver. see b/10857203
156             if (isAttemptingCall) {
157                 startDelayedFinish();
158             } else {
159                 finish();
160             }
161         }
162 
163 
164         /**
165          * Handes receipt of ordered new_outgoing_call intent. Verifies that the return from the
166          * ordered intent is valid.
167          * @return true if the call is being attempted; false if we are canceling the call.
168          */
doReceive(Context context, Intent intent)169         public boolean doReceive(Context context, Intent intent) {
170             if (DBG) Log.v(TAG, "doReceive: " + intent);
171 
172             boolean alreadyCalled;
173             String number;
174             String originalUri;
175 
176             alreadyCalled = intent.getBooleanExtra(
177                     OutgoingCallBroadcaster.EXTRA_ALREADY_CALLED, false);
178             if (alreadyCalled) {
179                 if (DBG) Log.v(TAG, "CALL already placed -- returning.");
180                 return false;
181             }
182 
183             // Once the NEW_OUTGOING_CALL broadcast is finished, the resultData
184             // is used as the actual number to call. (If null, no call will be
185             // placed.)
186 
187             number = getResultData();
188             if (VDBG) Log.v(TAG, "- got number from resultData: '" + number + "'");
189 
190             final PhoneGlobals app = PhoneGlobals.getInstance();
191             final Phone phone = PhoneGlobals.getPhone();
192 
193             // OTASP-specific checks.
194             // TODO: This should probably all happen in
195             // OutgoingCallBroadcaster.onCreate(), since there's no reason to
196             // even bother with the NEW_OUTGOING_CALL broadcast if we're going
197             // to disallow the outgoing call anyway...
198             if (TelephonyCapabilities.supportsOtasp(phone)) {
199                 boolean activateState = (app.cdmaOtaScreenState.otaScreenState
200                         == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION);
201                 boolean dialogState = (app.cdmaOtaScreenState.otaScreenState
202                         == OtaUtils.CdmaOtaScreenState.OtaScreenState
203                         .OTA_STATUS_SUCCESS_FAILURE_DLG);
204                 boolean isOtaCallActive = false;
205 
206                 // TODO: Need cleaner way to check if OTA is active.
207                 // Also, this check seems to be broken in one obscure case: if
208                 // you interrupt an OTASP call by pressing Back then Skip,
209                 // otaScreenState somehow gets left in either PROGRESS or
210                 // LISTENING.
211                 if ((app.cdmaOtaScreenState.otaScreenState
212                         == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_PROGRESS)
213                         || (app.cdmaOtaScreenState.otaScreenState
214                         == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_LISTENING)) {
215                     isOtaCallActive = true;
216                 }
217 
218                 if (activateState || dialogState) {
219                     // The OTASP sequence is active, but either (1) the call
220                     // hasn't started yet, or (2) the call has ended and we're
221                     // showing the success/failure screen.  In either of these
222                     // cases it's OK to make a new outgoing call, but we need
223                     // to take down any OTASP-related UI first.
224                     if (dialogState) app.dismissOtaDialogs();
225                     app.clearOtaState();
226                 } else if (isOtaCallActive) {
227                     // The actual OTASP call is active.  Don't allow new
228                     // outgoing calls at all from this state.
229                     Log.w(TAG, "OTASP call is active: disallowing a new outgoing call.");
230                     return false;
231                 }
232             }
233 
234             if (number == null) {
235                 if (DBG) Log.v(TAG, "CALL cancelled (null number), returning...");
236                 return false;
237             } else if (TelephonyCapabilities.supportsOtasp(phone)
238                     && (phone.getState() != PhoneConstants.State.IDLE)
239                     && (phone.isOtaSpNumber(number))) {
240                 if (DBG) Log.v(TAG, "Call is active, a 2nd OTA call cancelled -- returning.");
241                 return false;
242             } else if (PhoneNumberUtils.isPotentialLocalEmergencyNumber(context, number)) {
243                 // Just like 3rd-party apps aren't allowed to place emergency
244                 // calls via the ACTION_CALL intent, we also don't allow 3rd
245                 // party apps to use the NEW_OUTGOING_CALL broadcast to rewrite
246                 // an outgoing call into an emergency number.
247                 Log.w(TAG, "Cannot modify outgoing call to emergency number " + number + ".");
248                 return false;
249             }
250 
251             originalUri = intent.getStringExtra(
252                     OutgoingCallBroadcaster.EXTRA_ORIGINAL_URI);
253             if (originalUri == null) {
254                 Log.e(TAG, "Intent is missing EXTRA_ORIGINAL_URI -- returning.");
255                 return false;
256             }
257 
258             Uri uri = Uri.parse(originalUri);
259 
260             // We already called convertKeypadLettersToDigits() and
261             // stripSeparators() way back in onCreate(), before we sent out the
262             // NEW_OUTGOING_CALL broadcast.  But we need to do it again here
263             // too, since the number might have been modified/rewritten during
264             // the broadcast (and may now contain letters or separators again.)
265             number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
266             number = PhoneNumberUtils.stripSeparators(number);
267 
268             if (DBG) Log.v(TAG, "doReceive: proceeding with call...");
269             if (VDBG) Log.v(TAG, "- uri: " + uri);
270             if (VDBG) Log.v(TAG, "- actual number to dial: '" + number + "'");
271 
272             startSipCallOptionHandler(context, intent, uri, number);
273 
274             return true;
275         }
276     }
277 
278     /**
279      * Launch the SipCallOptionHandler, which is the next step(*) in the
280      * outgoing-call sequence after the outgoing call broadcast is
281      * complete.
282      *
283      * (*) We now know exactly what phone number we need to dial, so the next
284      *     step is for the SipCallOptionHandler to decide which Phone type (SIP
285      *     or PSTN) should be used.  (Depending on the user's preferences, this
286      *     decision may also involve popping up a dialog to ask the user to
287      *     choose what type of call this should be.)
288      *
289      * @param context used for the startActivity() call
290      *
291      * @param intent the intent from the previous step of the outgoing-call
292      *   sequence.  Normally this will be the NEW_OUTGOING_CALL broadcast intent
293      *   that came in to the OutgoingCallReceiver, although it can also be the
294      *   original ACTION_CALL intent that started the whole sequence (in cases
295      *   where we don't do the NEW_OUTGOING_CALL broadcast at all, like for
296      *   emergency numbers or SIP addresses).
297      *
298      * @param uri the data URI from the original CALL intent, presumably either
299      *   a tel: or sip: URI.  For tel: URIs, note that the scheme-specific part
300      *   does *not* necessarily have separators and keypad letters stripped (so
301      *   we might see URIs like "tel:(650)%20555-1234" or "tel:1-800-GOOG-411"
302      *   here.)
303      *
304      * @param number the actual number (or SIP address) to dial.  This is
305      *   guaranteed to be either a PSTN phone number with separators stripped
306      *   out and keypad letters converted to digits (like "16505551234"), or a
307      *   raw SIP address (like "user@example.com").
308      */
startSipCallOptionHandler(Context context, Intent intent, Uri uri, String number)309     private void startSipCallOptionHandler(Context context, Intent intent,
310             Uri uri, String number) {
311         // TODO: Remove this code.
312     }
313 
314     /**
315      * This method is the single point of entry for the CALL intent, which is used (by built-in
316      * apps like Contacts / Dialer, as well as 3rd-party apps) to initiate an outgoing voice call.
317      *
318      *
319      */
320     @Override
onCreate(Bundle icicle)321     protected void onCreate(Bundle icicle) {
322         super.onCreate(icicle);
323         setContentView(R.layout.outgoing_call_broadcaster);
324         mWaitingSpinner = (ProgressBar) findViewById(R.id.spinner);
325 
326         Intent intent = getIntent();
327         if (DBG) {
328             final Configuration configuration = getResources().getConfiguration();
329             Log.v(TAG, "onCreate: this = " + this + ", icicle = " + icicle);
330             Log.v(TAG, " - getIntent() = " + intent);
331             Log.v(TAG, " - configuration = " + configuration);
332         }
333 
334         if (icicle != null) {
335             // A non-null icicle means that this activity is being
336             // re-initialized after previously being shut down.
337             //
338             // In practice this happens very rarely (because the lifetime
339             // of this activity is so short!), but it *can* happen if the
340             // framework detects a configuration change at exactly the
341             // right moment; see bug 2202413.
342             //
343             // In this case, do nothing.  Our onCreate() method has already
344             // run once (with icicle==null the first time), which means
345             // that the NEW_OUTGOING_CALL broadcast for this new call has
346             // already been sent.
347             Log.i(TAG, "onCreate: non-null icicle!  "
348                   + "Bailing out, not sending NEW_OUTGOING_CALL broadcast...");
349 
350             // No need to finish() here, since the OutgoingCallReceiver from
351             // our original instance will do that.  (It'll actually call
352             // finish() on our original instance, which apparently works fine
353             // even though the ActivityManager has already shut that instance
354             // down.  And note that if we *do* call finish() here, that just
355             // results in an "ActivityManager: Duplicate finish request"
356             // warning when the OutgoingCallReceiver runs.)
357 
358             return;
359         }
360 
361         processIntent(intent);
362 
363         // isFinishing() return false when 1. broadcast is still ongoing, or 2. dialog is being
364         // shown. Otherwise finish() is called inside processIntent(), is isFinishing() here will
365         // return true.
366         if (DBG) Log.v(TAG, "At the end of onCreate(). isFinishing(): " + isFinishing());
367     }
368 
369     /**
370      * Interprets a given Intent and starts something relevant to the Intent.
371      *
372      * This method will handle three kinds of actions:
373      *
374      * - CALL (action for usual outgoing voice calls)
375      * - CALL_PRIVILEGED (can come from built-in apps like contacts / voice dialer / bluetooth)
376      * - CALL_EMERGENCY (from the EmergencyDialer that's reachable from the lockscreen.)
377      *
378      * The exact behavior depends on the intent's data:
379      *
380      * - The most typical is a tel: URI, which we handle by starting the
381      *   NEW_OUTGOING_CALL broadcast.  That broadcast eventually triggers
382      *   the sequence OutgoingCallReceiver -> SipCallOptionHandler ->
383      *   InCallScreen.
384      *
385      * - Or, with a sip: URI we skip the NEW_OUTGOING_CALL broadcast and
386      *   go directly to SipCallOptionHandler, which then leads to the
387      *   InCallScreen.
388      *
389      * - voicemail: URIs take the same path as regular tel: URIs.
390      *
391      * Other special cases:
392      *
393      * - Outgoing calls are totally disallowed on non-voice-capable
394      *   devices (see handleNonVoiceCapable()).
395      *
396      * - A CALL intent with the EXTRA_SEND_EMPTY_FLASH extra (and
397      *   presumably no data at all) means "send an empty flash" (which
398      *   is only meaningful on CDMA devices while a call is already
399      *   active.)
400      *
401      */
processIntent(Intent intent)402     private void processIntent(Intent intent) {
403         if (DBG) {
404             Log.v(TAG, "processIntent() = " + intent + ", thread: " + Thread.currentThread());
405         }
406         final Configuration configuration = getResources().getConfiguration();
407 
408         // Outgoing phone calls are only allowed on "voice-capable" devices.
409         if (!PhoneGlobals.sVoiceCapable) {
410             Log.i(TAG, "This device is detected as non-voice-capable device.");
411             handleNonVoiceCapable(intent);
412             return;
413         }
414 
415         String action = intent.getAction();
416         String number = PhoneNumberUtils.getNumberFromIntent(intent, this);
417         // Check the number, don't convert for sip uri
418         // TODO put uriNumber under PhoneNumberUtils
419         if (number != null) {
420             if (!PhoneNumberUtils.isUriNumber(number)) {
421                 number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
422                 number = PhoneNumberUtils.stripSeparators(number);
423             }
424         } else {
425             Log.w(TAG, "The number obtained from Intent is null.");
426         }
427 
428         AppOpsManager appOps = (AppOpsManager)getSystemService(Context.APP_OPS_SERVICE);
429         int launchedFromUid;
430         String launchedFromPackage;
431         try {
432             launchedFromUid = ActivityManagerNative.getDefault().getLaunchedFromUid(
433                     getActivityToken());
434             launchedFromPackage = ActivityManagerNative.getDefault().getLaunchedFromPackage(
435                     getActivityToken());
436         } catch (RemoteException e) {
437             launchedFromUid = -1;
438             launchedFromPackage = null;
439         }
440         if (appOps.noteOpNoThrow(AppOpsManager.OP_CALL_PHONE, launchedFromUid, launchedFromPackage)
441                 != AppOpsManager.MODE_ALLOWED) {
442             Log.w(TAG, "Rejecting call from uid " + launchedFromUid + " package "
443                     + launchedFromPackage);
444             finish();
445             return;
446         }
447 
448         // If true, this flag will indicate that the current call is a special kind
449         // of call (most likely an emergency number) that 3rd parties aren't allowed
450         // to intercept or affect in any way.  (In that case, we start the call
451         // immediately rather than going through the NEW_OUTGOING_CALL sequence.)
452         boolean callNow;
453 
454         if (getClass().getName().equals(intent.getComponent().getClassName())) {
455             // If we were launched directly from the OutgoingCallBroadcaster,
456             // not one of its more privileged aliases, then make sure that
457             // only the non-privileged actions are allowed.
458             if (!Intent.ACTION_CALL.equals(intent.getAction())) {
459                 Log.w(TAG, "Attempt to deliver non-CALL action; forcing to CALL");
460                 intent.setAction(Intent.ACTION_CALL);
461             }
462         }
463 
464         // Check whether or not this is an emergency number, in order to
465         // enforce the restriction that only the CALL_PRIVILEGED and
466         // CALL_EMERGENCY intents are allowed to make emergency calls.
467         //
468         // (Note that the ACTION_CALL check below depends on the result of
469         // isPotentialLocalEmergencyNumber() rather than just plain
470         // isLocalEmergencyNumber(), to be 100% certain that we *don't*
471         // allow 3rd party apps to make emergency calls by passing in an
472         // "invalid" number like "9111234" that isn't technically an
473         // emergency number but might still result in an emergency call
474         // with some networks.)
475         final boolean isExactEmergencyNumber =
476                 (number != null) && PhoneNumberUtils.isLocalEmergencyNumber(this, number);
477         final boolean isPotentialEmergencyNumber =
478                 (number != null) && PhoneNumberUtils.isPotentialLocalEmergencyNumber(this, number);
479         if (VDBG) {
480             Log.v(TAG, " - Checking restrictions for number '" + number + "':");
481             Log.v(TAG, "     isExactEmergencyNumber     = " + isExactEmergencyNumber);
482             Log.v(TAG, "     isPotentialEmergencyNumber = " + isPotentialEmergencyNumber);
483         }
484 
485         /* Change CALL_PRIVILEGED into CALL or CALL_EMERGENCY as needed. */
486         // TODO: This code is redundant with some code in InCallScreen: refactor.
487         if (Intent.ACTION_CALL_PRIVILEGED.equals(action)) {
488             // We're handling a CALL_PRIVILEGED intent, so we know this request came
489             // from a trusted source (like the built-in dialer.)  So even a number
490             // that's *potentially* an emergency number can safely be promoted to
491             // CALL_EMERGENCY (since we *should* allow you to dial "91112345" from
492             // the dialer if you really want to.)
493             if (isPotentialEmergencyNumber) {
494                 Log.i(TAG, "ACTION_CALL_PRIVILEGED is used while the number is a potential"
495                         + " emergency number. Use ACTION_CALL_EMERGENCY as an action instead.");
496                 action = Intent.ACTION_CALL_EMERGENCY;
497             } else {
498                 action = Intent.ACTION_CALL;
499             }
500             if (DBG) Log.v(TAG, " - updating action from CALL_PRIVILEGED to " + action);
501             intent.setAction(action);
502         }
503 
504         if (Intent.ACTION_CALL.equals(action)) {
505             if (isPotentialEmergencyNumber) {
506                 Log.w(TAG, "Cannot call potential emergency number '" + number
507                         + "' with CALL Intent " + intent + ".");
508                 Log.i(TAG, "Launching default dialer instead...");
509 
510                 Intent invokeFrameworkDialer = new Intent();
511 
512                 // TwelveKeyDialer is in a tab so we really want
513                 // DialtactsActivity.  Build the intent 'manually' to
514                 // use the java resolver to find the dialer class (as
515                 // opposed to a Context which look up known android
516                 // packages only)
517                 final Resources resources = getResources();
518                 invokeFrameworkDialer.setClassName(
519                         resources.getString(R.string.ui_default_package),
520                         resources.getString(R.string.dialer_default_class));
521                 invokeFrameworkDialer.setAction(Intent.ACTION_DIAL);
522                 invokeFrameworkDialer.setData(intent.getData());
523                 if (DBG) Log.v(TAG, "onCreate(): calling startActivity for Dialer: "
524                                + invokeFrameworkDialer);
525                 startActivity(invokeFrameworkDialer);
526                 finish();
527                 return;
528             }
529             callNow = false;
530         } else if (Intent.ACTION_CALL_EMERGENCY.equals(action)) {
531             // ACTION_CALL_EMERGENCY case: this is either a CALL_PRIVILEGED
532             // intent that we just turned into a CALL_EMERGENCY intent (see
533             // above), or else it really is an CALL_EMERGENCY intent that
534             // came directly from some other app (e.g. the EmergencyDialer
535             // activity built in to the Phone app.)
536             // Make sure it's at least *possible* that this is really an
537             // emergency number.
538             if (!isPotentialEmergencyNumber) {
539                 Log.w(TAG, "Cannot call non-potential-emergency number " + number
540                         + " with EMERGENCY_CALL Intent " + intent + "."
541                         + " Finish the Activity immediately.");
542                 finish();
543                 return;
544             }
545             callNow = true;
546         } else {
547             Log.e(TAG, "Unhandled Intent " + intent + ". Finish the Activity immediately.");
548             finish();
549             return;
550         }
551 
552         // Make sure the screen is turned on.  This is probably the right
553         // thing to do, and more importantly it works around an issue in the
554         // activity manager where we will not launch activities consistently
555         // when the screen is off (since it is trying to keep them paused
556         // and has...  issues).
557         //
558         // Also, this ensures the device stays awake while doing the following
559         // broadcast; technically we should be holding a wake lock here
560         // as well.
561         PhoneGlobals.getInstance().wakeUpScreen();
562 
563         // If number is null, we're probably trying to call a non-existent voicemail number,
564         // send an empty flash or something else is fishy.  Whatever the problem, there's no
565         // number, so there's no point in allowing apps to modify the number.
566         if (TextUtils.isEmpty(number)) {
567             if (intent.getBooleanExtra(EXTRA_SEND_EMPTY_FLASH, false)) {
568                 Log.i(TAG, "onCreate: SEND_EMPTY_FLASH...");
569                 PhoneUtils.sendEmptyFlash(PhoneGlobals.getPhone());
570                 finish();
571                 return;
572             } else {
573                 Log.i(TAG, "onCreate: null or empty number, setting callNow=true...");
574                 callNow = true;
575             }
576         }
577 
578         if (callNow) {
579             // This is a special kind of call (most likely an emergency number)
580             // that 3rd parties aren't allowed to intercept or affect in any way.
581             // So initiate the outgoing call immediately.
582 
583             Log.i(TAG, "onCreate(): callNow case! Calling placeCall(): " + intent);
584 
585             // Initiate the outgoing call, and simultaneously launch the
586             // InCallScreen to display the in-call UI:
587             PhoneGlobals.getInstance().callController.placeCall(intent);
588 
589             // Note we do *not* "return" here, but instead continue and
590             // send the ACTION_NEW_OUTGOING_CALL broadcast like for any
591             // other outgoing call.  (But when the broadcast finally
592             // reaches the OutgoingCallReceiver, we'll know not to
593             // initiate the call again because of the presence of the
594             // EXTRA_ALREADY_CALLED extra.)
595         }
596 
597         // For now, SIP calls will be processed directly without a
598         // NEW_OUTGOING_CALL broadcast.
599         //
600         // TODO: In the future, though, 3rd party apps *should* be allowed to
601         // intercept outgoing calls to SIP addresses as well.  To do this, we should
602         // (1) update the NEW_OUTGOING_CALL intent documentation to explain this
603         // case, and (2) pass the outgoing SIP address by *not* overloading the
604         // EXTRA_PHONE_NUMBER extra, but instead using a new separate extra to hold
605         // the outgoing SIP address.  (Be sure to document whether it's a URI or just
606         // a plain address, whether it could be a tel: URI, etc.)
607         Uri uri = intent.getData();
608         String scheme = uri.getScheme();
609         if (PhoneAccount.SCHEME_SIP.equals(scheme) || PhoneNumberUtils.isUriNumber(number)) {
610             Log.i(TAG, "The requested number was detected as SIP call.");
611             startSipCallOptionHandler(this, intent, uri, number);
612             finish();
613             return;
614 
615             // TODO: if there's ever a way for SIP calls to trigger a
616             // "callNow=true" case (see above), we'll need to handle that
617             // case here too (most likely by just doing nothing at all.)
618         }
619 
620         Intent broadcastIntent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL);
621         if (number != null) {
622             broadcastIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
623         }
624         CallGatewayManager.checkAndCopyPhoneProviderExtras(intent, broadcastIntent);
625         broadcastIntent.putExtra(EXTRA_ALREADY_CALLED, callNow);
626         broadcastIntent.putExtra(EXTRA_ORIGINAL_URI, uri.toString());
627         // Need to raise foreground in-call UI as soon as possible while allowing 3rd party app
628         // to intercept the outgoing call.
629         broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
630         if (DBG) Log.v(TAG, " - Broadcasting intent: " + broadcastIntent + ".");
631 
632         // Set a timer so that we can prepare for unexpected delay introduced by the broadcast.
633         // If it takes too much time, the timer will show "waiting" spinner.
634         // This message will be removed when OutgoingCallReceiver#onReceive() is called before the
635         // timeout.
636         mHandler.sendEmptyMessageDelayed(EVENT_OUTGOING_CALL_TIMEOUT,
637                 OUTGOING_CALL_TIMEOUT_THRESHOLD);
638         sendOrderedBroadcastAsUser(broadcastIntent, UserHandle.SYSTEM,
639                 android.Manifest.permission.PROCESS_OUTGOING_CALLS,
640                 AppOpsManager.OP_PROCESS_OUTGOING_CALLS,
641                 new OutgoingCallReceiver(),
642                 null,  // scheduler
643                 Activity.RESULT_OK,  // initialCode
644                 number,  // initialData: initial value for the result data
645                 null);  // initialExtras
646     }
647 
648     @Override
onStop()649     protected void onStop() {
650         // Clean up (and dismiss if necessary) any managed dialogs.
651         //
652         // We don't do this in onPause() since we can be paused/resumed
653         // due to orientation changes (in which case we don't want to
654         // disturb the dialog), but we *do* need it here in onStop() to be
655         // sure we clean up if the user hits HOME while the dialog is up.
656         //
657         // Note it's safe to call removeDialog() even if there's no dialog
658         // associated with that ID.
659         removeDialog(DIALOG_NOT_VOICE_CAPABLE);
660 
661         super.onStop();
662     }
663 
664     /**
665      * Handle the specified CALL or CALL_* intent on a non-voice-capable
666      * device.
667      *
668      * This method may launch a different intent (if there's some useful
669      * alternative action to take), or otherwise display an error dialog,
670      * and in either case will finish() the current activity when done.
671      */
handleNonVoiceCapable(Intent intent)672     private void handleNonVoiceCapable(Intent intent) {
673         if (DBG) Log.v(TAG, "handleNonVoiceCapable: handling " + intent
674                        + " on non-voice-capable device...");
675 
676         // Just show a generic "voice calling not supported" dialog.
677         showDialog(DIALOG_NOT_VOICE_CAPABLE);
678         // ...and we'll eventually finish() when the user dismisses
679         // or cancels the dialog.
680     }
681 
682     @Override
onCreateDialog(int id)683     protected Dialog onCreateDialog(int id) {
684         Dialog dialog;
685         switch(id) {
686             case DIALOG_NOT_VOICE_CAPABLE:
687                 dialog = new AlertDialog.Builder(this)
688                         .setTitle(R.string.not_voice_capable)
689                         .setIconAttribute(android.R.attr.alertDialogIcon)
690                         .setPositiveButton(android.R.string.ok, this)
691                         .setOnCancelListener(this)
692                         .create();
693                 break;
694             default:
695                 Log.w(TAG, "onCreateDialog: unexpected ID " + id);
696                 dialog = null;
697                 break;
698         }
699         return dialog;
700     }
701 
702     /** DialogInterface.OnClickListener implementation */
703     @Override
onClick(DialogInterface dialog, int id)704     public void onClick(DialogInterface dialog, int id) {
705         // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far
706         // at least), and its only button is "OK".
707         finish();
708     }
709 
710     /** DialogInterface.OnCancelListener implementation */
711     @Override
onCancel(DialogInterface dialog)712     public void onCancel(DialogInterface dialog) {
713         // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far
714         // at least), and canceling it is just like hitting "OK".
715         finish();
716     }
717 
718     /**
719      * Implement onConfigurationChanged() purely for debugging purposes,
720      * to make sure that the android:configChanges element in our manifest
721      * is working properly.
722      */
723     @Override
onConfigurationChanged(Configuration newConfig)724     public void onConfigurationChanged(Configuration newConfig) {
725         super.onConfigurationChanged(newConfig);
726         if (DBG) Log.v(TAG, "onConfigurationChanged: newConfig = " + newConfig);
727     }
728 }
729