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
17package com.android.phone;
18
19import android.app.Activity;
20import android.app.ActivityManagerNative;
21import android.app.AlertDialog;
22import android.app.AppOpsManager;
23import android.app.Dialog;
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.net.Uri;
31import android.os.Bundle;
32import android.os.Handler;
33import android.os.Message;
34import android.os.RemoteException;
35import android.os.SystemProperties;
36import android.os.UserHandle;
37import android.telecom.PhoneAccount;
38import android.telephony.PhoneNumberUtils;
39import android.text.TextUtils;
40import android.util.Log;
41import android.view.View;
42import android.widget.ProgressBar;
43
44import com.android.internal.telephony.PhoneConstants;
45import com.android.internal.telephony.TelephonyCapabilities;
46
47/**
48 * OutgoingCallBroadcaster receives CALL and CALL_PRIVILEGED Intents, and broadcasts the
49 * ACTION_NEW_OUTGOING_CALL intent. ACTION_NEW_OUTGOING_CALL is an ordered broadcast intent which
50 * contains the phone number being dialed. Applications can use this intent to (1) see which numbers
51 * are being dialed, (2) redirect a call (change the number being dialed), or (3) prevent a call
52 * from being placed.
53 *
54 * After the other applications have had a chance to see the
55 * ACTION_NEW_OUTGOING_CALL intent, it finally reaches the
56 * {@link OutgoingCallReceiver}, which passes the (possibly modified)
57 * intent on to the {@link SipCallOptionHandler}, which will
58 * ultimately start the call using the CallController.placeCall() API.
59 *
60 * Calls where no number is present (like for a CDMA "empty flash" or a nonexistent voicemail
61 * number) are exempt from being broadcast.
62 * Calls to emergency numbers are still broadcast for informative purposes. The call is placed
63 * prior to sending ACTION_NEW_OUTGOING_CALL and cannot be redirected nor prevented.
64 */
65public class OutgoingCallBroadcaster extends Activity
66        implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
67
68    private static final String TAG = "OutgoingCallBroadcaster";
69    private static final boolean DBG =
70            (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
71    // Do not check in with VDBG = true, since that may write PII to the system log.
72    private static final boolean VDBG = false;
73
74    /** Required permission for any app that wants to consume ACTION_NEW_OUTGOING_CALL. */
75    private static final String PERMISSION = android.Manifest.permission.PROCESS_OUTGOING_CALLS;
76
77    public static final String ACTION_SIP_SELECT_PHONE = "com.android.phone.SIP_SELECT_PHONE";
78    public static final String EXTRA_ALREADY_CALLED = "android.phone.extra.ALREADY_CALLED";
79    public static final String EXTRA_ORIGINAL_URI = "android.phone.extra.ORIGINAL_URI";
80    public static final String EXTRA_NEW_CALL_INTENT = "android.phone.extra.NEW_CALL_INTENT";
81    public static final String EXTRA_SIP_PHONE_URI = "android.phone.extra.SIP_PHONE_URI";
82    public static final String EXTRA_ACTUAL_NUMBER_TO_DIAL =
83            "android.phone.extra.ACTUAL_NUMBER_TO_DIAL";
84    public static final String EXTRA_THIRD_PARTY_CALL_COMPONENT =
85            "android.phone.extra.THIRD_PARTY_CALL_COMPONENT";
86
87    /**
88     * Identifier for intent extra for sending an empty Flash message for
89     * CDMA networks. This message is used by the network to simulate a
90     * press/depress of the "hookswitch" of a landline phone. Aka "empty flash".
91     *
92     * TODO: Receiving an intent extra to tell the phone to send this flash is a
93     * temporary measure. To be replaced with an external ITelephony call in the future.
94     * TODO: Keep in sync with the string defined in TwelveKeyDialer.java in Contacts app
95     * until this is replaced with the ITelephony API.
96     */
97    public static final String EXTRA_SEND_EMPTY_FLASH =
98            "com.android.phone.extra.SEND_EMPTY_FLASH";
99
100    // Dialog IDs
101    private static final int DIALOG_NOT_VOICE_CAPABLE = 1;
102
103    /** Note message codes < 100 are reserved for the PhoneApp. */
104    private static final int EVENT_OUTGOING_CALL_TIMEOUT = 101;
105    private static final int EVENT_DELAYED_FINISH = 102;
106
107    private static final int OUTGOING_CALL_TIMEOUT_THRESHOLD = 2000; // msec
108    private static final int DELAYED_FINISH_TIME = 2000; // msec
109
110    /**
111     * ProgressBar object with "spinner" style, which will be shown if we take more than
112     * {@link #EVENT_OUTGOING_CALL_TIMEOUT} msec to handle the incoming Intent.
113     */
114    private ProgressBar mWaitingSpinner;
115    private final Handler mHandler = new Handler() {
116        @Override
117        public void handleMessage(Message msg) {
118            if (msg.what == EVENT_OUTGOING_CALL_TIMEOUT) {
119                Log.i(TAG, "Outgoing call takes too long. Showing the spinner.");
120                mWaitingSpinner.setVisibility(View.VISIBLE);
121            } else if (msg.what == EVENT_DELAYED_FINISH) {
122                finish();
123            } else {
124                Log.wtf(TAG, "Unknown message id: " + msg.what);
125            }
126        }
127    };
128
129    /**
130     * Starts the delayed finish() of OutgoingCallBroadcaster in order to give the UI
131     * some time to start up.
132     */
133    private void startDelayedFinish() {
134        mHandler.sendEmptyMessageDelayed(EVENT_DELAYED_FINISH, DELAYED_FINISH_TIME);
135    }
136
137    /**
138     * OutgoingCallReceiver finishes NEW_OUTGOING_CALL broadcasts, starting
139     * the InCallScreen if the broadcast has not been canceled, possibly with
140     * a modified phone number and optional provider info (uri + package name + remote views.)
141     */
142    public class OutgoingCallReceiver extends BroadcastReceiver {
143        private static final String TAG = "OutgoingCallReceiver";
144
145        @Override
146        public void onReceive(Context context, Intent intent) {
147            mHandler.removeMessages(EVENT_OUTGOING_CALL_TIMEOUT);
148            final boolean isAttemptingCall = doReceive(context, intent);
149            if (DBG) Log.v(TAG, "OutgoingCallReceiver is going to finish the Activity itself.");
150
151            // We cannot finish the activity immediately here because it would cause the temporary
152            // black screen of OutgoingBroadcaster to go away and we need it to stay up until the
153            // UI (in a different process) has time to come up.
154            // However, if we know we are not attemping a call, we need to finish the activity
155            // immediately so that subsequent CALL intents will retrigger a new
156            // OutgoingCallReceiver. see b/10857203
157            if (isAttemptingCall) {
158                startDelayedFinish();
159            } else {
160                finish();
161            }
162        }
163
164
165        /**
166         * Handes receipt of ordered new_outgoing_call intent. Verifies that the return from the
167         * ordered intent is valid.
168         * @return true if the call is being attempted; false if we are canceling the call.
169         */
170        public boolean doReceive(Context context, Intent intent) {
171            if (DBG) Log.v(TAG, "doReceive: " + intent);
172
173            boolean alreadyCalled;
174            String number;
175            String originalUri;
176
177            alreadyCalled = intent.getBooleanExtra(
178                    OutgoingCallBroadcaster.EXTRA_ALREADY_CALLED, false);
179            if (alreadyCalled) {
180                if (DBG) Log.v(TAG, "CALL already placed -- returning.");
181                return false;
182            }
183
184            // Once the NEW_OUTGOING_CALL broadcast is finished, the resultData
185            // is used as the actual number to call. (If null, no call will be
186            // placed.)
187
188            number = getResultData();
189            if (VDBG) Log.v(TAG, "- got number from resultData: '" + number + "'");
190
191            final PhoneGlobals app = PhoneGlobals.getInstance();
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(app.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(app.phone)
238                    && (app.phone.getState() != PhoneConstants.State.IDLE)
239                    && (app.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     */
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
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     */
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.OWNER,
639                PERMISSION, new OutgoingCallReceiver(),
640                null,  // scheduler
641                Activity.RESULT_OK,  // initialCode
642                number,  // initialData: initial value for the result data
643                null);  // initialExtras
644    }
645
646    @Override
647    protected void onStop() {
648        // Clean up (and dismiss if necessary) any managed dialogs.
649        //
650        // We don't do this in onPause() since we can be paused/resumed
651        // due to orientation changes (in which case we don't want to
652        // disturb the dialog), but we *do* need it here in onStop() to be
653        // sure we clean up if the user hits HOME while the dialog is up.
654        //
655        // Note it's safe to call removeDialog() even if there's no dialog
656        // associated with that ID.
657        removeDialog(DIALOG_NOT_VOICE_CAPABLE);
658
659        super.onStop();
660    }
661
662    /**
663     * Handle the specified CALL or CALL_* intent on a non-voice-capable
664     * device.
665     *
666     * This method may launch a different intent (if there's some useful
667     * alternative action to take), or otherwise display an error dialog,
668     * and in either case will finish() the current activity when done.
669     */
670    private void handleNonVoiceCapable(Intent intent) {
671        if (DBG) Log.v(TAG, "handleNonVoiceCapable: handling " + intent
672                       + " on non-voice-capable device...");
673
674        // Just show a generic "voice calling not supported" dialog.
675        showDialog(DIALOG_NOT_VOICE_CAPABLE);
676        // ...and we'll eventually finish() when the user dismisses
677        // or cancels the dialog.
678    }
679
680    @Override
681    protected Dialog onCreateDialog(int id) {
682        Dialog dialog;
683        switch(id) {
684            case DIALOG_NOT_VOICE_CAPABLE:
685                dialog = new AlertDialog.Builder(this)
686                        .setTitle(R.string.not_voice_capable)
687                        .setIconAttribute(android.R.attr.alertDialogIcon)
688                        .setPositiveButton(android.R.string.ok, this)
689                        .setOnCancelListener(this)
690                        .create();
691                break;
692            default:
693                Log.w(TAG, "onCreateDialog: unexpected ID " + id);
694                dialog = null;
695                break;
696        }
697        return dialog;
698    }
699
700    /** DialogInterface.OnClickListener implementation */
701    @Override
702    public void onClick(DialogInterface dialog, int id) {
703        // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far
704        // at least), and its only button is "OK".
705        finish();
706    }
707
708    /** DialogInterface.OnCancelListener implementation */
709    @Override
710    public void onCancel(DialogInterface dialog) {
711        // DIALOG_NOT_VOICE_CAPABLE is the only dialog we ever use (so far
712        // at least), and canceling it is just like hitting "OK".
713        finish();
714    }
715
716    /**
717     * Implement onConfigurationChanged() purely for debugging purposes,
718     * to make sure that the android:configChanges element in our manifest
719     * is working properly.
720     */
721    @Override
722    public void onConfigurationChanged(Configuration newConfig) {
723        super.onConfigurationChanged(newConfig);
724        if (DBG) Log.v(TAG, "onConfigurationChanged: newConfig = " + newConfig);
725    }
726}
727