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