blob: c1bd1b64ddec24b652c86b112388ff3bc1756a3c [file] [log] [blame]
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001/*
2 * Copyright (C) 2006 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.AlertDialog;
20import android.app.Dialog;
21import android.app.ProgressDialog;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070022import android.content.ActivityNotFoundException;
Sailesh Nepalbfb68322013-11-07 14:07:41 -080023import android.content.ComponentName;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070024import android.content.Context;
25import android.content.DialogInterface;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070026import android.net.Uri;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070027import android.os.Handler;
28import android.os.Message;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070029import android.telecom.PhoneAccount;
Andrew Leed5165b02014-12-05 15:53:58 -080030import android.telecom.PhoneAccountHandle;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070031import android.telecom.VideoProfile;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070032import android.telephony.PhoneNumberUtils;
Santos Cordonf69df962015-02-03 11:15:19 -080033import android.telephony.SubscriptionManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070034import android.text.TextUtils;
35import android.util.Log;
Andrew Leeb3ee4dc2015-01-23 17:35:00 -080036import android.view.ContextThemeWrapper;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070037import android.view.KeyEvent;
38import android.view.LayoutInflater;
39import android.view.View;
40import android.view.WindowManager;
41import android.widget.EditText;
42import android.widget.Toast;
43
44import com.android.internal.telephony.Call;
45import com.android.internal.telephony.CallManager;
46import com.android.internal.telephony.CallStateException;
47import com.android.internal.telephony.CallerInfo;
48import com.android.internal.telephony.CallerInfoAsyncQuery;
49import com.android.internal.telephony.Connection;
Stuart Scottdcf40a92014-12-09 10:45:01 -080050import com.android.internal.telephony.IccCard;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070051import com.android.internal.telephony.MmiCode;
52import com.android.internal.telephony.Phone;
53import com.android.internal.telephony.PhoneConstants;
Stuart Scottdcf40a92014-12-09 10:45:01 -080054import com.android.internal.telephony.PhoneFactory;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070055import com.android.internal.telephony.TelephonyCapabilities;
Santos Cordon69a69192013-08-22 14:25:42 -070056import com.android.phone.CallGatewayManager.RawGatewayInfo;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070057
Santos Cordon7d4ddf62013-07-10 11:58:08 -070058import java.util.Arrays;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070059import java.util.List;
60
61/**
62 * Misc utilities for the Phone app.
63 */
64public class PhoneUtils {
Brad Ebingerd3edc222016-03-23 19:44:38 -070065 public static final String EMERGENCY_ACCOUNT_HANDLE_ID = "E";
Santos Cordon7d4ddf62013-07-10 11:58:08 -070066 private static final String LOG_TAG = "PhoneUtils";
67 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
68
69 // Do not check in with VDBG = true, since that may write PII to the system log.
70 private static final boolean VDBG = false;
71
Santos Cordon7d4ddf62013-07-10 11:58:08 -070072 // Return codes from placeCall()
fionaxuf7885142016-11-27 16:08:39 -080073 public static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed
74 public static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code
75 public static final int CALL_STATUS_FAILED = 2; // The call failed
Santos Cordon7d4ddf62013-07-10 11:58:08 -070076
Santos Cordon7d4ddf62013-07-10 11:58:08 -070077 // USSD string length for MMI operations
78 static final int MIN_USSD_LEN = 1;
79 static final int MAX_USSD_LEN = 160;
80
Santos Cordon7d4ddf62013-07-10 11:58:08 -070081 /** Define for not a special CNAP string */
82 private static final int CNAP_SPECIAL_CASE_NO = -1;
83
Yorke Leee0f2b792014-10-15 12:30:44 -070084 /**
85 * Theme to use for dialogs displayed by utility methods in this class. This is needed
86 * because these dialogs are displayed using the application context, which does not resolve
87 * the dialog theme correctly.
88 */
Zheng Zhangd889c772017-11-02 15:49:37 -070089 private static final int THEME = com.android.internal.R.style.Theme_DeviceDefault_Dialog_Alert;
Yorke Leee0f2b792014-10-15 12:30:44 -070090
Etan Cohen37abbab2014-03-07 16:57:03 -080091 /** USSD information used to aggregate all USSD messages */
92 private static AlertDialog sUssdDialog = null;
93 private static StringBuilder sUssdMsg = new StringBuilder();
94
Tony Mak4c8f3c62015-12-07 02:30:37 +000095 private static final ComponentName PSTN_CONNECTION_SERVICE_COMPONENT =
96 new ComponentName("com.android.phone",
97 "com.android.services.telephony.TelephonyConnectionService");
98
Santos Cordon7d4ddf62013-07-10 11:58:08 -070099 /** This class is never instantiated. */
100 private PhoneUtils() {
101 }
102
103 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700104 * For a CDMA phone, advance the call state upon making a new
105 * outgoing call.
106 *
107 * <pre>
108 * IDLE -> SINGLE_ACTIVE
109 * or
110 * SINGLE_ACTIVE -> THRWAY_ACTIVE
111 * </pre>
112 * @param app The phone instance.
113 */
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700114 private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app,
115 Connection connection) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700116 if (app.cdmaPhoneCallState.getCurrentCallState() ==
117 CdmaPhoneCallState.PhoneCallState.IDLE) {
118 // This is the first outgoing call. Set the Phone Call State to ACTIVE
119 app.cdmaPhoneCallState.setCurrentCallState(
120 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
121 } else {
122 // This is the second outgoing call. Set the Phone Call State to 3WAY
123 app.cdmaPhoneCallState.setCurrentCallState(
124 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700125
Santos Cordonda120f42014-08-06 04:44:34 -0700126 // TODO: Remove this code.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700127 //app.getCallModeler().setCdmaOutgoing3WayCall(connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700128 }
129 }
130
131 /**
Santos Cordon69a69192013-08-22 14:25:42 -0700132 * @see placeCall below
133 */
134 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
135 boolean isEmergencyCall) {
136 return placeCall(context, phone, number, contactRef, isEmergencyCall,
137 CallGatewayManager.EMPTY_INFO, null);
138 }
139
140 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700141 * Dial the number using the phone passed in.
142 *
143 * If the connection is establised, this method issues a sync call
144 * that may block to query the caller info.
145 * TODO: Change the logic to use the async query.
146 *
147 * @param context To perform the CallerInfo query.
148 * @param phone the Phone object.
149 * @param number to be dialed as requested by the user. This is
150 * NOT the phone number to connect to. It is used only to build the
151 * call card and to update the call log. See above for restrictions.
152 * @param contactRef that triggered the call. Typically a 'tel:'
153 * uri but can also be a 'content://contacts' one.
154 * @param isEmergencyCall indicates that whether or not this is an
155 * emergency call
156 * @param gatewayUri Is the address used to setup the connection, null
157 * if not using a gateway
Santos Cordon69a69192013-08-22 14:25:42 -0700158 * @param callGateway Class for setting gateway data on a successful call.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700159 *
160 * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
161 */
Santos Cordon69a69192013-08-22 14:25:42 -0700162 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
163 boolean isEmergencyCall, RawGatewayInfo gatewayInfo, CallGatewayManager callGateway) {
164 final Uri gatewayUri = gatewayInfo.gatewayUri;
165
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700166 if (VDBG) {
167 log("placeCall()... number: '" + number + "'"
168 + ", GW:'" + gatewayUri + "'"
169 + ", contactRef:" + contactRef
170 + ", isEmergencyCall: " + isEmergencyCall);
171 } else {
172 log("placeCall()... number: " + toLogSafePhoneNumber(number)
173 + ", GW: " + (gatewayUri != null ? "non-null" : "null")
174 + ", emergency? " + isEmergencyCall);
175 }
176 final PhoneGlobals app = PhoneGlobals.getInstance();
177
178 boolean useGateway = false;
179 if (null != gatewayUri &&
180 !isEmergencyCall &&
181 PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes.
182 useGateway = true;
183 }
184
185 int status = CALL_STATUS_DIALED;
186 Connection connection;
187 String numberToDial;
188 if (useGateway) {
189 // TODO: 'tel' should be a constant defined in framework base
190 // somewhere (it is in webkit.)
Jay Shrauner137458b2014-09-05 14:27:25 -0700191 if (null == gatewayUri || !PhoneAccount.SCHEME_TEL.equals(gatewayUri.getScheme())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700192 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
193 return CALL_STATUS_FAILED;
194 }
195
196 // We can use getSchemeSpecificPart because we don't allow #
197 // in the gateway numbers (treated a fragment delim.) However
198 // if we allow more complex gateway numbers sequence (with
199 // passwords or whatnot) that use #, this may break.
200 // TODO: Need to support MMI codes.
201 numberToDial = gatewayUri.getSchemeSpecificPart();
202 } else {
203 numberToDial = number;
204 }
205
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700206 try {
Tyler Gunnc6514352015-06-02 21:46:34 -0700207 connection = app.mCM.dial(phone, numberToDial, VideoProfile.STATE_AUDIO_ONLY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700208 } catch (CallStateException ex) {
209 // CallStateException means a new outgoing call is not currently
210 // possible: either no more call slots exist, or there's another
211 // call already in the process of dialing or ringing.
212 Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
213 return CALL_STATUS_FAILED;
214
215 // Note that it's possible for CallManager.dial() to return
216 // null *without* throwing an exception; that indicates that
217 // we dialed an MMI (see below).
218 }
219
220 int phoneType = phone.getPhoneType();
221
222 // On GSM phones, null is returned for MMI codes
223 if (null == connection) {
Santos Cordonf77a3392014-07-21 19:48:10 -0700224 status = CALL_STATUS_FAILED;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700225 } else {
226 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700227 updateCdmaCallStateOnNewOutgoingCall(app, connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700228 }
229
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700230 if (gatewayUri == null) {
231 // phone.dial() succeeded: we're now in a normal phone call.
232 // attach the URI to the CallerInfo Object if it is there,
233 // otherwise just attach the Uri Reference.
234 // if the uri does not have a "content" scheme, then we treat
235 // it as if it does NOT have a unique reference.
236 String content = context.getContentResolver().SCHEME_CONTENT;
237 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
238 Object userDataObject = connection.getUserData();
239 if (userDataObject == null) {
240 connection.setUserData(contactRef);
241 } else {
242 // TODO: This branch is dead code, we have
243 // just created the connection which has
244 // no user data (null) by default.
245 if (userDataObject instanceof CallerInfo) {
246 ((CallerInfo) userDataObject).contactRefUri = contactRef;
247 } else {
248 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
249 contactRef;
250 }
251 }
252 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700253 }
Santos Cordonc264cba2013-09-19 04:55:40 -0700254
Chiao Chenge365ba72013-09-26 14:18:12 -0700255 startGetCallerInfo(context, connection, null, null, gatewayInfo);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700256 }
257
258 return status;
259 }
260
261 /* package */ static String toLogSafePhoneNumber(String number) {
262 // For unknown number, log empty string.
263 if (number == null) {
264 return "";
265 }
266
267 if (VDBG) {
268 // When VDBG is true we emit PII.
269 return number;
270 }
271
272 // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
273 // sanitized phone numbers.
274 StringBuilder builder = new StringBuilder();
275 for (int i = 0; i < number.length(); i++) {
276 char c = number.charAt(i);
277 if (c == '-' || c == '@' || c == '.') {
278 builder.append(c);
279 } else {
280 builder.append('x');
281 }
282 }
283 return builder.toString();
284 }
285
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700286 /**
287 * Handle the MMIInitiate message and put up an alert that lets
288 * the user cancel the operation, if applicable.
289 *
290 * @param context context to get strings.
291 * @param mmiCode the MmiCode object being started.
292 * @param buttonCallbackMessage message to post when button is clicked.
293 * @param previousAlert a previous alert used in this activity.
294 * @return the dialog handle
295 */
296 static Dialog displayMMIInitiate(Context context,
297 MmiCode mmiCode,
298 Message buttonCallbackMessage,
299 Dialog previousAlert) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700300 log("displayMMIInitiate: " + android.telecom.Log.pii(mmiCode.toString()));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700301 if (previousAlert != null) {
302 previousAlert.dismiss();
303 }
304
305 // The UI paradigm we are using now requests that all dialogs have
306 // user interaction, and that any other messages to the user should
307 // be by way of Toasts.
308 //
309 // In adhering to this request, all MMI initiating "OK" dialogs
310 // (non-cancelable MMIs) that end up being closed when the MMI
311 // completes (thereby showing a completion dialog) are being
312 // replaced with Toasts.
313 //
314 // As a side effect, moving to Toasts for the non-cancelable MMIs
315 // also means that buttonCallbackMessage (which was tied into "OK")
316 // is no longer invokable for these dialogs. This is not a problem
317 // since the only callback messages we supported were for cancelable
318 // MMIs anyway.
319 //
320 // A cancelable MMI is really just a USSD request. The term
321 // "cancelable" here means that we can cancel the request when the
322 // system prompts us for a response, NOT while the network is
323 // processing the MMI request. Any request to cancel a USSD while
324 // the network is NOT ready for a response may be ignored.
325 //
326 // With this in mind, we replace the cancelable alert dialog with
327 // a progress dialog, displayed until we receive a request from
328 // the the network. For more information, please see the comments
329 // in the displayMMIComplete() method below.
330 //
331 // Anything that is NOT a USSD request is a normal MMI request,
332 // which will bring up a toast (desribed above).
333
334 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
335
336 if (!isCancelable) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700337 log("displayMMIInitiate: not a USSD code, displaying status toast.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700338 CharSequence text = context.getText(R.string.mmiStarted);
339 Toast.makeText(context, text, Toast.LENGTH_SHORT)
340 .show();
341 return null;
342 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700343 log("displayMMIInitiate: running USSD code, displaying intermediate progress.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700344
345 // create the indeterminate progress dialog and display it.
Alex Hills779841a2015-10-22 13:23:28 -0400346 ProgressDialog pd = new ProgressDialog(context, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700347 pd.setMessage(context.getText(R.string.ussdRunning));
348 pd.setCancelable(false);
349 pd.setIndeterminate(true);
350 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
351
352 pd.show();
353
354 return pd;
355 }
356
357 }
358
359 /**
360 * Handle the MMIComplete message and fire off an intent to display
361 * the message.
362 *
363 * @param context context to get strings.
364 * @param mmiCode MMI result.
365 * @param previousAlert a previous alert used in this activity.
366 */
367 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
368 Message dismissCallbackMessage,
369 AlertDialog previousAlert) {
370 final PhoneGlobals app = PhoneGlobals.getInstance();
371 CharSequence text;
372 int title = 0; // title for the progress dialog, if needed.
373 MmiCode.State state = mmiCode.getState();
374
Tyler Gunn13fe2492017-05-22 14:14:20 -0700375 log("displayMMIComplete: state=" + state);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700376
377 switch (state) {
378 case PENDING:
379 // USSD code asking for feedback from user.
380 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700381 log("displayMMIComplete: using text from PENDING MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700382 break;
383 case CANCELLED:
384 text = null;
385 break;
386 case COMPLETE:
387 if (app.getPUKEntryActivity() != null) {
388 // if an attempt to unPUK the device was made, we specify
389 // the title and the message here.
390 title = com.android.internal.R.string.PinMmi;
391 text = context.getText(R.string.puk_unlocked);
392 break;
393 }
394 // All other conditions for the COMPLETE mmi state will cause
395 // the case to fall through to message logic in common with
396 // the FAILED case.
397
398 case FAILED:
399 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700400 log("displayMMIComplete (failed): using text from MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700401 break;
402 default:
403 throw new IllegalStateException("Unexpected MmiCode state: " + state);
404 }
405
406 if (previousAlert != null) {
407 previousAlert.dismiss();
408 }
409
410 // Check to see if a UI exists for the PUK activation. If it does
411 // exist, then it indicates that we're trying to unblock the PUK.
412 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
413 if (DBG) log("displaying PUK unblocking progress dialog.");
414
415 // create the progress dialog, make sure the flags and type are
416 // set correctly.
Alex Hills779841a2015-10-22 13:23:28 -0400417 ProgressDialog pd = new ProgressDialog(app, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700418 pd.setTitle(title);
419 pd.setMessage(text);
420 pd.setCancelable(false);
421 pd.setIndeterminate(true);
422 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
423 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
424
425 // display the dialog
426 pd.show();
427
428 // indicate to the Phone app that the progress dialog has
429 // been assigned for the PUK unlock / SIM READY process.
430 app.setPukEntryProgressDialog(pd);
431
432 } else {
433 // In case of failure to unlock, we'll need to reset the
434 // PUK unlock activity, so that the user may try again.
435 if (app.getPUKEntryActivity() != null) {
436 app.setPukEntryActivity(null);
437 }
438
439 // A USSD in a pending state means that it is still
440 // interacting with the user.
441 if (state != MmiCode.State.PENDING) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700442 log("displayMMIComplete: MMI code has finished running.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700443
Tyler Gunn13fe2492017-05-22 14:14:20 -0700444 log("displayMMIComplete: Extended NW displayMMIInitiate (" + text + ")");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700445 if (text == null || text.length() == 0)
446 return;
447
448 // displaying system alert dialog on the screen instead of
449 // using another activity to display the message. This
450 // places the message at the forefront of the UI.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700451
Etan Cohen37abbab2014-03-07 16:57:03 -0800452 if (sUssdDialog == null) {
Yorke Leee0f2b792014-10-15 12:30:44 -0700453 sUssdDialog = new AlertDialog.Builder(context, THEME)
Etan Cohen37abbab2014-03-07 16:57:03 -0800454 .setPositiveButton(R.string.ok, null)
455 .setCancelable(true)
456 .setOnDismissListener(new DialogInterface.OnDismissListener() {
457 @Override
458 public void onDismiss(DialogInterface dialog) {
459 sUssdMsg.setLength(0);
460 }
461 })
462 .create();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700463
Etan Cohen37abbab2014-03-07 16:57:03 -0800464 sUssdDialog.getWindow().setType(
Brad Ebinger2eefb2b2017-08-03 11:09:30 -0700465 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
Etan Cohen37abbab2014-03-07 16:57:03 -0800466 sUssdDialog.getWindow().addFlags(
467 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
468 }
469 if (sUssdMsg.length() != 0) {
470 sUssdMsg
471 .insert(0, "\n")
472 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
473 .insert(0, "\n");
474 }
475 sUssdMsg.insert(0, text);
476 sUssdDialog.setMessage(sUssdMsg.toString());
477 sUssdDialog.show();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700478 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700479 log("displayMMIComplete: USSD code has requested user input. Constructing input "
480 + "dialog.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700481
482 // USSD MMI code that is interacting with the user. The
483 // basic set of steps is this:
484 // 1. User enters a USSD request
485 // 2. We recognize the request and displayMMIInitiate
486 // (above) creates a progress dialog.
487 // 3. Request returns and we get a PENDING or COMPLETE
488 // message.
489 // 4. These MMI messages are caught in the PhoneApp
490 // (onMMIComplete) and the InCallScreen
491 // (mHandler.handleMessage) which bring up this dialog
492 // and closes the original progress dialog,
493 // respectively.
494 // 5. If the message is anything other than PENDING,
495 // we are done, and the alert dialog (directly above)
496 // displays the outcome.
497 // 6. If the network is requesting more information from
498 // the user, the MMI will be in a PENDING state, and
499 // we display this dialog with the message.
500 // 7. User input, or cancel requests result in a return
501 // to step 1. Keep in mind that this is the only
502 // time that a USSD should be canceled.
503
504 // inflate the layout with the scrolling text area for the dialog.
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800505 ContextThemeWrapper contextThemeWrapper =
506 new ContextThemeWrapper(context, R.style.DialerAlertDialogTheme);
507 LayoutInflater inflater = (LayoutInflater) contextThemeWrapper.getSystemService(
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700508 Context.LAYOUT_INFLATER_SERVICE);
509 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
510
511 // get the input field.
512 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
513
514 // specify the dialog's click listener, with SEND and CANCEL logic.
515 final DialogInterface.OnClickListener mUSSDDialogListener =
516 new DialogInterface.OnClickListener() {
517 public void onClick(DialogInterface dialog, int whichButton) {
518 switch (whichButton) {
519 case DialogInterface.BUTTON_POSITIVE:
520 // As per spec 24.080, valid length of ussd string
521 // is 1 - 160. If length is out of the range then
522 // display toast message & Cancel MMI operation.
523 if (inputText.length() < MIN_USSD_LEN
524 || inputText.length() > MAX_USSD_LEN) {
525 Toast.makeText(app,
526 app.getResources().getString(R.string.enter_input,
527 MIN_USSD_LEN, MAX_USSD_LEN),
528 Toast.LENGTH_LONG).show();
529 if (mmiCode.isCancelable()) {
530 mmiCode.cancel();
531 }
532 } else {
533 phone.sendUssdResponse(inputText.getText().toString());
534 }
535 break;
536 case DialogInterface.BUTTON_NEGATIVE:
537 if (mmiCode.isCancelable()) {
538 mmiCode.cancel();
539 }
540 break;
541 }
542 }
543 };
544
545 // build the dialog
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800546 final AlertDialog newDialog = new AlertDialog.Builder(contextThemeWrapper)
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700547 .setMessage(text)
548 .setView(dialogView)
549 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
550 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
551 .setCancelable(false)
552 .create();
553
554 // attach the key listener to the dialog's input field and make
555 // sure focus is set.
556 final View.OnKeyListener mUSSDDialogInputListener =
557 new View.OnKeyListener() {
558 public boolean onKey(View v, int keyCode, KeyEvent event) {
559 switch (keyCode) {
560 case KeyEvent.KEYCODE_CALL:
561 case KeyEvent.KEYCODE_ENTER:
562 if(event.getAction() == KeyEvent.ACTION_DOWN) {
563 phone.sendUssdResponse(inputText.getText().toString());
564 newDialog.dismiss();
565 }
566 return true;
567 }
568 return false;
569 }
570 };
571 inputText.setOnKeyListener(mUSSDDialogInputListener);
572 inputText.requestFocus();
573
574 // set the window properties of the dialog
575 newDialog.getWindow().setType(
576 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
577 newDialog.getWindow().addFlags(
578 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
579
580 // now show the dialog!
581 newDialog.show();
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800582
583 newDialog.getButton(DialogInterface.BUTTON_POSITIVE)
584 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
585 newDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
586 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700587 }
588 }
589 }
590
591 /**
592 * Cancels the current pending MMI operation, if applicable.
593 * @return true if we canceled an MMI operation, or false
594 * if the current pending MMI wasn't cancelable
595 * or if there was no current pending MMI at all.
596 *
597 * @see displayMMIInitiate
598 */
599 static boolean cancelMmiCode(Phone phone) {
600 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
601 int count = pendingMmis.size();
602 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
603
604 boolean canceled = false;
605 if (count > 0) {
606 // assume that we only have one pending MMI operation active at a time.
607 // I don't think it's possible to enter multiple MMI codes concurrently
608 // in the phone UI, because during the MMI operation, an Alert panel
609 // is displayed, which prevents more MMI code from being entered.
610 MmiCode mmiCode = pendingMmis.get(0);
611 if (mmiCode.isCancelable()) {
612 mmiCode.cancel();
613 canceled = true;
614 }
615 }
616 return canceled;
617 }
618
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700619 /**
620 * Returns the caller-id info corresponding to the specified Connection.
621 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
622 * extract a phone number from the specified Connection, and feed that
623 * number into CallerInfo.getCallerInfo().)
624 *
625 * The returned CallerInfo may be null in certain error cases, like if the
626 * specified Connection was null, or if we weren't able to get a valid
627 * phone number from the Connection.
628 *
629 * Finally, if the getCallerInfo() call did succeed, we save the resulting
630 * CallerInfo object in the "userData" field of the Connection.
631 *
632 * NOTE: This API should be avoided, with preference given to the
633 * asynchronous startGetCallerInfo API.
634 */
635 static CallerInfo getCallerInfo(Context context, Connection c) {
636 CallerInfo info = null;
637
638 if (c != null) {
639 //See if there is a URI attached. If there is, this means
640 //that there is no CallerInfo queried yet, so we'll need to
641 //replace the URI with a full CallerInfo object.
642 Object userDataObject = c.getUserData();
643 if (userDataObject instanceof Uri) {
644 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
645 if (info != null) {
646 c.setUserData(info);
647 }
648 } else {
649 if (userDataObject instanceof CallerInfoToken) {
650 //temporary result, while query is running
651 info = ((CallerInfoToken) userDataObject).currentInfo;
652 } else {
653 //final query result
654 info = (CallerInfo) userDataObject;
655 }
656 if (info == null) {
657 // No URI, or Existing CallerInfo, so we'll have to make do with
658 // querying a new CallerInfo using the connection's phone number.
659 String number = c.getAddress();
660
661 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
662
663 if (!TextUtils.isEmpty(number)) {
664 info = CallerInfo.getCallerInfo(context, number);
665 if (info != null) {
666 c.setUserData(info);
667 }
668 }
669 }
670 }
671 }
672 return info;
673 }
674
675 /**
676 * Class returned by the startGetCallerInfo call to package a temporary
677 * CallerInfo Object, to be superceded by the CallerInfo Object passed
678 * into the listener when the query with token mAsyncQueryToken is complete.
679 */
680 public static class CallerInfoToken {
681 /**indicates that there will no longer be updates to this request.*/
682 public boolean isFinal;
683
684 public CallerInfo currentInfo;
685 public CallerInfoAsyncQuery asyncQuery;
686 }
687
688 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700689 * place a temporary callerinfo object in the hands of the caller and notify
690 * caller when the actual query is done.
691 */
692 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -0700693 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
694 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700695 CallerInfoToken cit;
696
697 if (c == null) {
698 //TODO: perhaps throw an exception here.
699 cit = new CallerInfoToken();
700 cit.asyncQuery = null;
701 return cit;
702 }
703
704 Object userDataObject = c.getUserData();
705
706 // There are now 3 states for the Connection's userData object:
707 //
708 // (1) Uri - query has not been executed yet
709 //
710 // (2) CallerInfoToken - query is executing, but has not completed.
711 //
712 // (3) CallerInfo - query has executed.
713 //
714 // In each case we have slightly different behaviour:
715 // 1. If the query has not been executed yet (Uri or null), we start
716 // query execution asynchronously, and note it by attaching a
717 // CallerInfoToken as the userData.
718 // 2. If the query is executing (CallerInfoToken), we've essentially
719 // reached a state where we've received multiple requests for the
720 // same callerInfo. That means that once the query is complete,
721 // we'll need to execute the additional listener requested.
722 // 3. If the query has already been executed (CallerInfo), we just
723 // return the CallerInfo object as expected.
724 // 4. Regarding isFinal - there are cases where the CallerInfo object
725 // will not be attached, like when the number is empty (caller id
726 // blocking). This flag is used to indicate that the
727 // CallerInfoToken object is going to be permanent since no
728 // query results will be returned. In the case where a query
729 // has been completed, this flag is used to indicate to the caller
730 // that the data will not be updated since it is valid.
731 //
732 // Note: For the case where a number is NOT retrievable, we leave
733 // the CallerInfo as null in the CallerInfoToken. This is
734 // something of a departure from the original code, since the old
735 // code manufactured a CallerInfo object regardless of the query
736 // outcome. From now on, we will append an empty CallerInfo
737 // object, to mirror previous behaviour, and to avoid Null Pointer
738 // Exceptions.
739
740 if (userDataObject instanceof Uri) {
741 // State (1): query has not been executed yet
742
743 //create a dummy callerinfo, populate with what we know from URI.
744 cit = new CallerInfoToken();
745 cit.currentInfo = new CallerInfo();
746 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
747 (Uri) userDataObject, sCallerInfoQueryListener, c);
748 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
749 cit.isFinal = false;
750
751 c.setUserData(cit);
752
753 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
754
755 } else if (userDataObject == null) {
756 // No URI, or Existing CallerInfo, so we'll have to make do with
757 // querying a new CallerInfo using the connection's phone number.
758 String number = c.getAddress();
759
Chiao Cheng685dcb62013-10-02 11:51:06 -0700760 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -0700761 // Gateway number, the connection number is actually the gateway number.
762 // need to lookup via dialed number.
763 number = info.trueNumber;
764 }
765
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700766 if (DBG) {
767 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
768 log("- number (address): " + toLogSafePhoneNumber(number));
769 log("- c: " + c);
770 log("- phone: " + c.getCall().getPhone());
771 int phoneType = c.getCall().getPhone().getPhoneType();
772 log("- phoneType: " + phoneType);
773 switch (phoneType) {
774 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
775 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -0700776 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700777 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
778 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700779 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
780 log(" ==> PHONE_TYPE_THIRD_PARTY");
781 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700782 default: log(" ==> Unknown phone type"); break;
783 }
784 }
785
786 cit = new CallerInfoToken();
787 cit.currentInfo = new CallerInfo();
788
789 // Store CNAP information retrieved from the Connection (we want to do this
790 // here regardless of whether the number is empty or not).
791 cit.currentInfo.cnapName = c.getCnapName();
792 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
793 // by ContactInfo later
794 cit.currentInfo.numberPresentation = c.getNumberPresentation();
795 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
796
797 if (VDBG) {
798 log("startGetCallerInfo: number = " + number);
799 log("startGetCallerInfo: CNAP Info from FW(1): name="
800 + cit.currentInfo.cnapName
801 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
802 }
803
804 // handling case where number is null (caller id hidden) as well.
805 if (!TextUtils.isEmpty(number)) {
806 // Check for special CNAP cases and modify the CallerInfo accordingly
807 // to be sure we keep the right information to display/log later
808 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
809 cit.currentInfo.numberPresentation);
810
811 cit.currentInfo.phoneNumber = number;
812 // For scenarios where we may receive a valid number from the network but a
813 // restricted/unavailable presentation, we do not want to perform a contact query
814 // (see note on isFinal above). So we set isFinal to true here as well.
815 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
816 cit.isFinal = true;
817 } else {
818 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
819 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
820 number, sCallerInfoQueryListener, c);
821 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
822 cit.isFinal = false;
823 }
824 } else {
825 // This is the case where we are querying on a number that
826 // is null or empty, like a caller whose caller id is
827 // blocked or empty (CLIR). The previous behaviour was to
828 // throw a null CallerInfo object back to the user, but
829 // this departure is somewhat cleaner.
830 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
831 cit.isFinal = true; // please see note on isFinal, above.
832 }
833
834 c.setUserData(cit);
835
836 if (DBG) {
837 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
838 }
839
840 } else if (userDataObject instanceof CallerInfoToken) {
841 // State (2): query is executing, but has not completed.
842
843 // just tack on this listener to the queue.
844 cit = (CallerInfoToken) userDataObject;
845
846 // handling case where number is null (caller id hidden) as well.
847 if (cit.asyncQuery != null) {
848 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
849
850 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
851 listener.getClass().toString());
852 } else {
853 // handling case where number/name gets updated later on by the network
854 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -0700855
856 if (info != null) {
857 // Gateway number, the connection number is actually the gateway number.
858 // need to lookup via dialed number.
859 updatedNumber = info.trueNumber;
860 }
861
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700862 if (DBG) {
863 log("startGetCallerInfo: updatedNumber initially = "
864 + toLogSafePhoneNumber(updatedNumber));
865 }
866 if (!TextUtils.isEmpty(updatedNumber)) {
867 // Store CNAP information retrieved from the Connection
868 cit.currentInfo.cnapName = c.getCnapName();
869 // This can still get overwritten by ContactInfo
870 cit.currentInfo.name = cit.currentInfo.cnapName;
871 cit.currentInfo.numberPresentation = c.getNumberPresentation();
872 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
873
874 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
875 updatedNumber, cit.currentInfo.numberPresentation);
876
877 cit.currentInfo.phoneNumber = updatedNumber;
878 if (DBG) {
879 log("startGetCallerInfo: updatedNumber="
880 + toLogSafePhoneNumber(updatedNumber));
881 }
882 if (VDBG) {
883 log("startGetCallerInfo: CNAP Info from FW(2): name="
884 + cit.currentInfo.cnapName
885 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
886 } else if (DBG) {
887 log("startGetCallerInfo: CNAP Info from FW(2)");
888 }
889 // For scenarios where we may receive a valid number from the network but a
890 // restricted/unavailable presentation, we do not want to perform a contact query
891 // (see note on isFinal above). So we set isFinal to true here as well.
892 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
893 cit.isFinal = true;
894 } else {
895 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
896 updatedNumber, sCallerInfoQueryListener, c);
897 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
898 cit.isFinal = false;
899 }
900 } else {
901 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
902 if (cit.currentInfo == null) {
903 cit.currentInfo = new CallerInfo();
904 }
905 // Store CNAP information retrieved from the Connection
906 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
907 // overwritten by ContactInfo
908 cit.currentInfo.name = cit.currentInfo.cnapName;
909 cit.currentInfo.numberPresentation = c.getNumberPresentation();
910 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
911
912 if (VDBG) {
913 log("startGetCallerInfo: CNAP Info from FW(3): name="
914 + cit.currentInfo.cnapName
915 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
916 } else if (DBG) {
917 log("startGetCallerInfo: CNAP Info from FW(3)");
918 }
919 cit.isFinal = true; // please see note on isFinal, above.
920 }
921 }
922 } else {
923 // State (3): query is complete.
924
925 // The connection's userDataObject is a full-fledged
926 // CallerInfo instance. Wrap it in a CallerInfoToken and
927 // return it to the user.
928
929 cit = new CallerInfoToken();
930 cit.currentInfo = (CallerInfo) userDataObject;
931 cit.asyncQuery = null;
932 cit.isFinal = true;
933 // since the query is already done, call the listener.
934 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
935 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
936 }
937 return cit;
938 }
939
940 /**
941 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
942 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
943 */
944 private static final int QUERY_TOKEN = -1;
945 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
946 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
947 /**
948 * When the query completes, we stash the resulting CallerInfo
949 * object away in the Connection's "userData" (where it will
950 * later be retrieved by the in-call UI.)
951 */
952 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
953 if (DBG) log("query complete, updating connection.userdata");
954 Connection conn = (Connection) cookie;
955
956 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
957 // If no ContactInfo, then we want to use CNAP information coming from network
958 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
959 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
960 // If the number presentation has not been set by
961 // the ContactInfo, use the one from the
962 // connection.
963
964 // TODO: Need a new util method to merge the info
965 // from the Connection in a CallerInfo object.
966 // Here 'ci' is a new CallerInfo instance read
967 // from the DB. It has lost all the connection
968 // info preset before the query (see PhoneUtils
969 // line 1334). We should have a method to merge
970 // back into this new instance the info from the
971 // connection object not set by the DB. If the
972 // Connection already has a CallerInfo instance in
973 // userData, then we could use this instance to
974 // fill 'ci' in. The same routine could be used in
975 // PhoneUtils.
976 if (0 == ci.numberPresentation) {
977 ci.numberPresentation = conn.getNumberPresentation();
978 }
979 } else {
980 // No matching contact was found for this number.
981 // Return a new CallerInfo based solely on the CNAP
982 // information from the network.
983
984 CallerInfo newCi = getCallerInfo(null, conn);
985
986 // ...but copy over the (few) things we care about
987 // from the original CallerInfo object:
988 if (newCi != null) {
989 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
990 newCi.geoDescription = ci.geoDescription; // To get geo description string
991 ci = newCi;
992 }
993 }
994
995 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
996 conn.setUserData(ci);
997 }
998 };
999
1000
1001 /**
1002 * Returns a single "name" for the specified given a CallerInfo object.
1003 * If the name is null, return defaultString as the default value, usually
1004 * context.getString(R.string.unknown).
1005 */
1006 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1007 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1008
1009 String compactName = null;
1010 if (ci != null) {
1011 if (TextUtils.isEmpty(ci.name)) {
1012 // Perform any modifications for special CNAP cases to
1013 // the phone number being displayed, if applicable.
1014 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1015 ci.numberPresentation);
1016 } else {
1017 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1018 compactName = ci.name;
1019 }
1020 }
1021
1022 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1023 // If we're still null/empty here, then check if we have a presentation
1024 // string that takes precedence that we could return, otherwise display
1025 // "unknown" string.
1026 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1027 compactName = context.getString(R.string.private_num);
1028 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1029 compactName = context.getString(R.string.payphone);
1030 } else {
1031 compactName = context.getString(R.string.unknown);
1032 }
1033 }
1034 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1035 return compactName;
1036 }
1037
Tyler Gunna1abb582018-09-14 16:12:01 -07001038 static boolean isInEmergencyCall(CallManager cm) {
1039 Call fgCall = cm.getActiveFgCall();
1040 // isIdle includes checks for the DISCONNECTING/DISCONNECTED state.
1041 if(!fgCall.isIdle()) {
1042 for (Connection cn : fgCall.getConnections()) {
1043 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
1044 cn.getAddress())) {
1045 return true;
1046 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001047 }
1048 }
1049 return false;
1050 }
1051
1052 //
1053 // Misc UI policy helper functions
1054 //
1055
1056 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001057 * Based on the input CNAP number string,
1058 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1059 * Otherwise, return CNAP_SPECIAL_CASE_NO.
1060 */
1061 private static int checkCnapSpecialCases(String n) {
1062 if (n.equals("PRIVATE") ||
1063 n.equals("P") ||
1064 n.equals("RES")) {
1065 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1066 return PhoneConstants.PRESENTATION_RESTRICTED;
1067 } else if (n.equals("UNAVAILABLE") ||
1068 n.equals("UNKNOWN") ||
1069 n.equals("UNA") ||
1070 n.equals("U")) {
1071 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1072 return PhoneConstants.PRESENTATION_UNKNOWN;
1073 } else {
1074 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1075 return CNAP_SPECIAL_CASE_NO;
1076 }
1077 }
1078
1079 /**
1080 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
1081 * from the network to indicate different number presentations, convert them to
1082 * expected number and presentation values within the CallerInfo object.
1083 * @param number number we use to verify if we are in a corner case
1084 * @param presentation presentation value used to verify if we are in a corner case
1085 * @return the new String that should be used for the phone number
1086 */
1087 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
1088 String number, int presentation) {
1089 // Obviously we return number if ci == null, but still return number if
1090 // number == null, because in these cases the correct string will still be
1091 // displayed/logged after this function returns based on the presentation value.
1092 if (ci == null || number == null) return number;
1093
1094 if (DBG) {
1095 log("modifyForSpecialCnapCases: initially, number="
1096 + toLogSafePhoneNumber(number)
1097 + ", presentation=" + presentation + " ci " + ci);
1098 }
1099
1100 // "ABSENT NUMBER" is a possible value we could get from the network as the
1101 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
1102 // and fix the presentation to be the same.
1103 final String[] absentNumberValues =
1104 context.getResources().getStringArray(R.array.absent_num);
1105 if (Arrays.asList(absentNumberValues).contains(number)
1106 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
1107 number = context.getString(R.string.unknown);
1108 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
1109 }
1110
1111 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
1112 // cases only apply if we received an allowed presentation from the network, so check
1113 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
1114 // match the presentation passed in for verification (meaning we changed it previously
1115 // because it's a corner case and we're being called from a different entry point).
1116 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
1117 || (ci.numberPresentation != presentation
1118 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
1119 int cnapSpecialCase = checkCnapSpecialCases(number);
1120 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
1121 // For all special strings, change number & numberPresentation.
1122 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
1123 number = context.getString(R.string.private_num);
1124 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
1125 number = context.getString(R.string.unknown);
1126 }
1127 if (DBG) {
1128 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
1129 + "; presentation now=" + cnapSpecialCase);
1130 }
1131 ci.numberPresentation = cnapSpecialCase;
1132 }
1133 }
1134 if (DBG) {
1135 log("modifyForSpecialCnapCases: returning number string="
1136 + toLogSafePhoneNumber(number));
1137 }
1138 return number;
1139 }
1140
1141 //
1142 // Support for 3rd party phone service providers.
1143 //
1144
1145 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001146 * Check if a phone number can be route through a 3rd party
1147 * gateway. The number must be a global phone number in numerical
1148 * form (1-800-666-SEXY won't work).
1149 *
1150 * MMI codes and the like cannot be used as a dial number for the
1151 * gateway either.
1152 *
1153 * @param number To be dialed via a 3rd party gateway.
1154 * @return true If the number can be routed through the 3rd party network.
1155 */
Santos Cordon69a69192013-08-22 14:25:42 -07001156 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001157 if (TextUtils.isEmpty(number)) {
1158 return false;
1159 }
1160 number = PhoneNumberUtils.stripSeparators(number);
1161 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
1162 return false;
1163 }
1164 number = PhoneNumberUtils.extractNetworkPortion(number);
1165 return PhoneNumberUtils.isGlobalPhoneNumber(number);
1166 }
1167
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001168 /**
1169 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
1170 */
1171 /* package */ static boolean isPhoneInEcm(Phone phone) {
1172 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
Shuo Qiandd210312017-04-12 22:11:33 +00001173 return phone.isInEcm();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001174 }
1175 return false;
1176 }
1177
1178 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001179 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
1180 * meaning the call is the first real incoming call the phone is having.
1181 */
1182 public static boolean isRealIncomingCall(Call.State state) {
1183 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
1184 }
1185
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001186 //
1187 // General phone and call state debugging/testing code
1188 //
1189
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001190 private static void log(String msg) {
1191 Log.d(LOG_TAG, msg);
1192 }
1193
Nancy Chene53a0642015-03-12 11:20:12 -07001194 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
1195 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
1196 }
1197
Nancy Chen32031f42015-03-04 21:00:07 -08001198 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
1199 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
1200 }
1201
Andrew Leed5165b02014-12-05 15:53:58 -08001202 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
1203 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
1204 }
1205
1206 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1207 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08001208 // TODO: Should use some sort of special hidden flag to decorate this account as
1209 // an emergency-only account
Brad Ebingerd3edc222016-03-23 19:44:38 -07001210 String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
Brad Ebinger4fe48112016-04-13 11:21:53 -07001211 String.valueOf(phone.getFullIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07001212 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
1213 }
1214
1215 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1216 String id, String prefix, boolean isEmergency) {
1217 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08001218 return new PhoneAccountHandle(pstnConnectionServiceName, id);
1219 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08001220
Santos Cordonf69df962015-02-03 11:15:19 -08001221 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08001222 if (phoneAccount != null
1223 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
1224 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
1225 }
1226 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1227 }
1228
1229 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001230 Phone phone = getPhoneForPhoneAccountHandle(handle);
1231 if (phone != null) {
1232 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08001233 }
1234 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1235 }
1236
Ta-wei Yen845f6992016-06-16 12:53:46 -07001237 public static Phone getPhoneForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001238 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
1239 return getPhoneFromIccId(handle.getId());
1240 }
1241 return null;
1242 }
1243
Nancy Chene53a0642015-03-12 11:20:12 -07001244 /**
1245 * Determine if a given phone account corresponds to an active SIM
1246 *
1247 * @param sm An instance of the subscription manager so it is not recreated for each calling of
1248 * this method.
1249 * @param handle The handle for the phone account to check
1250 * @return {@code true} If there is an active SIM for this phone account,
1251 * {@code false} otherwise.
1252 */
1253 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
1254 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
1255 }
1256
Santos Cordonf69df962015-02-03 11:15:19 -08001257 private static ComponentName getPstnConnectionServiceName() {
Tony Mak4c8f3c62015-12-07 02:30:37 +00001258 return PSTN_CONNECTION_SERVICE_COMPONENT;
Santos Cordonf69df962015-02-03 11:15:19 -08001259 }
1260
Santos Cordon80855d52015-02-10 04:33:36 -08001261 private static Phone getPhoneFromIccId(String iccId) {
1262 if (!TextUtils.isEmpty(iccId)) {
1263 for (Phone phone : PhoneFactory.getPhones()) {
Brad Ebinger4fe48112016-04-13 11:21:53 -07001264 String phoneIccId = phone.getFullIccSerialNumber();
Santos Cordon80855d52015-02-10 04:33:36 -08001265 if (iccId.equals(phoneIccId)) {
1266 return phone;
1267 }
1268 }
1269 }
Santos Cordon80855d52015-02-10 04:33:36 -08001270 return null;
1271 }
1272
Stuart Scottdcf40a92014-12-09 10:45:01 -08001273 /**
1274 * Register ICC status for all phones.
1275 */
1276 static final void registerIccStatus(Handler handler, int event) {
1277 for (Phone phone : PhoneFactory.getPhones()) {
1278 IccCard sim = phone.getIccCard();
1279 if (sim != null) {
1280 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
1281 sim.registerForNetworkLocked(handler, event, phone);
1282 }
1283 }
1284 }
1285
1286 /**
1287 * Set the radio power on/off state for all phones.
1288 *
1289 * @param enabled true means on, false means off.
1290 */
1291 static final void setRadioPower(boolean enabled) {
1292 for (Phone phone : PhoneFactory.getPhones()) {
1293 phone.setRadioPower(enabled);
1294 }
1295 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001296}