blob: 3306d4b37de71f264be2c063525d0ec7e7122201 [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
SongFerngWangdfa107a2018-10-29 20:31:58 +0800432 } else if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.FAILED)) {
433 createUssdDialog(app, context, text,
434 WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
435 // In case of failure to unlock, we'll need to reset the
436 // PUK unlock activity, so that the user may try again.
437 app.setPukEntryActivity(null);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700438 } else {
439 // In case of failure to unlock, we'll need to reset the
440 // PUK unlock activity, so that the user may try again.
441 if (app.getPUKEntryActivity() != null) {
442 app.setPukEntryActivity(null);
443 }
444
445 // A USSD in a pending state means that it is still
446 // interacting with the user.
447 if (state != MmiCode.State.PENDING) {
SongFerngWangdfa107a2018-10-29 20:31:58 +0800448 createUssdDialog(app, context, text,
449 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700450 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700451 log("displayMMIComplete: USSD code has requested user input. Constructing input "
452 + "dialog.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700453
454 // USSD MMI code that is interacting with the user. The
455 // basic set of steps is this:
456 // 1. User enters a USSD request
457 // 2. We recognize the request and displayMMIInitiate
458 // (above) creates a progress dialog.
459 // 3. Request returns and we get a PENDING or COMPLETE
460 // message.
461 // 4. These MMI messages are caught in the PhoneApp
462 // (onMMIComplete) and the InCallScreen
463 // (mHandler.handleMessage) which bring up this dialog
464 // and closes the original progress dialog,
465 // respectively.
466 // 5. If the message is anything other than PENDING,
467 // we are done, and the alert dialog (directly above)
468 // displays the outcome.
469 // 6. If the network is requesting more information from
470 // the user, the MMI will be in a PENDING state, and
471 // we display this dialog with the message.
472 // 7. User input, or cancel requests result in a return
473 // to step 1. Keep in mind that this is the only
474 // time that a USSD should be canceled.
475
476 // inflate the layout with the scrolling text area for the dialog.
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800477 ContextThemeWrapper contextThemeWrapper =
478 new ContextThemeWrapper(context, R.style.DialerAlertDialogTheme);
479 LayoutInflater inflater = (LayoutInflater) contextThemeWrapper.getSystemService(
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700480 Context.LAYOUT_INFLATER_SERVICE);
481 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
482
483 // get the input field.
484 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
485
486 // specify the dialog's click listener, with SEND and CANCEL logic.
487 final DialogInterface.OnClickListener mUSSDDialogListener =
488 new DialogInterface.OnClickListener() {
489 public void onClick(DialogInterface dialog, int whichButton) {
490 switch (whichButton) {
491 case DialogInterface.BUTTON_POSITIVE:
492 // As per spec 24.080, valid length of ussd string
493 // is 1 - 160. If length is out of the range then
494 // display toast message & Cancel MMI operation.
495 if (inputText.length() < MIN_USSD_LEN
496 || inputText.length() > MAX_USSD_LEN) {
497 Toast.makeText(app,
498 app.getResources().getString(R.string.enter_input,
499 MIN_USSD_LEN, MAX_USSD_LEN),
500 Toast.LENGTH_LONG).show();
501 if (mmiCode.isCancelable()) {
502 mmiCode.cancel();
503 }
504 } else {
505 phone.sendUssdResponse(inputText.getText().toString());
506 }
507 break;
508 case DialogInterface.BUTTON_NEGATIVE:
509 if (mmiCode.isCancelable()) {
510 mmiCode.cancel();
511 }
512 break;
513 }
514 }
515 };
516
517 // build the dialog
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800518 final AlertDialog newDialog = new AlertDialog.Builder(contextThemeWrapper)
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700519 .setMessage(text)
520 .setView(dialogView)
521 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
522 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
523 .setCancelable(false)
524 .create();
525
526 // attach the key listener to the dialog's input field and make
527 // sure focus is set.
528 final View.OnKeyListener mUSSDDialogInputListener =
529 new View.OnKeyListener() {
530 public boolean onKey(View v, int keyCode, KeyEvent event) {
531 switch (keyCode) {
532 case KeyEvent.KEYCODE_CALL:
533 case KeyEvent.KEYCODE_ENTER:
534 if(event.getAction() == KeyEvent.ACTION_DOWN) {
535 phone.sendUssdResponse(inputText.getText().toString());
536 newDialog.dismiss();
537 }
538 return true;
539 }
540 return false;
541 }
542 };
543 inputText.setOnKeyListener(mUSSDDialogInputListener);
544 inputText.requestFocus();
545
546 // set the window properties of the dialog
547 newDialog.getWindow().setType(
548 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
549 newDialog.getWindow().addFlags(
550 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
551
552 // now show the dialog!
553 newDialog.show();
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800554
555 newDialog.getButton(DialogInterface.BUTTON_POSITIVE)
556 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
557 newDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
558 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700559 }
560 }
561 }
562
SongFerngWangdfa107a2018-10-29 20:31:58 +0800563 private static void createUssdDialog(PhoneGlobals app, Context context, CharSequence text,
564 int windowType) {
565 log("displayMMIComplete: MMI code has finished running.");
566
567 log("displayMMIComplete: Extended NW displayMMIInitiate (" + text + ")");
568 if (text == null || text.length() == 0) {
569 return;
570 }
571
572 // displaying system alert dialog on the screen instead of
573 // using another activity to display the message. This
574 // places the message at the forefront of the UI.
575
576 if (sUssdDialog == null) {
577 sUssdDialog = new AlertDialog.Builder(context, THEME)
578 .setPositiveButton(R.string.ok, null)
579 .setCancelable(true)
580 .setOnDismissListener(new DialogInterface.OnDismissListener() {
581 @Override
582 public void onDismiss(DialogInterface dialog) {
583 sUssdMsg.setLength(0);
584 }
585 })
586 .create();
587
588 sUssdDialog.getWindow().setType(windowType);
589 sUssdDialog.getWindow().addFlags(
590 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
591 }
592 if (sUssdMsg.length() != 0) {
593 sUssdMsg
594 .insert(0, "\n")
595 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
596 .insert(0, "\n");
597 }
598 sUssdMsg.insert(0, text);
599 sUssdDialog.setMessage(sUssdMsg.toString());
600 sUssdDialog.show();
601 }
602
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700603 /**
604 * Cancels the current pending MMI operation, if applicable.
605 * @return true if we canceled an MMI operation, or false
606 * if the current pending MMI wasn't cancelable
607 * or if there was no current pending MMI at all.
608 *
609 * @see displayMMIInitiate
610 */
611 static boolean cancelMmiCode(Phone phone) {
612 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
613 int count = pendingMmis.size();
614 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
615
616 boolean canceled = false;
617 if (count > 0) {
618 // assume that we only have one pending MMI operation active at a time.
619 // I don't think it's possible to enter multiple MMI codes concurrently
620 // in the phone UI, because during the MMI operation, an Alert panel
621 // is displayed, which prevents more MMI code from being entered.
622 MmiCode mmiCode = pendingMmis.get(0);
623 if (mmiCode.isCancelable()) {
624 mmiCode.cancel();
625 canceled = true;
626 }
627 }
628 return canceled;
629 }
630
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700631 /**
632 * Returns the caller-id info corresponding to the specified Connection.
633 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
634 * extract a phone number from the specified Connection, and feed that
635 * number into CallerInfo.getCallerInfo().)
636 *
637 * The returned CallerInfo may be null in certain error cases, like if the
638 * specified Connection was null, or if we weren't able to get a valid
639 * phone number from the Connection.
640 *
641 * Finally, if the getCallerInfo() call did succeed, we save the resulting
642 * CallerInfo object in the "userData" field of the Connection.
643 *
644 * NOTE: This API should be avoided, with preference given to the
645 * asynchronous startGetCallerInfo API.
646 */
647 static CallerInfo getCallerInfo(Context context, Connection c) {
648 CallerInfo info = null;
649
650 if (c != null) {
651 //See if there is a URI attached. If there is, this means
652 //that there is no CallerInfo queried yet, so we'll need to
653 //replace the URI with a full CallerInfo object.
654 Object userDataObject = c.getUserData();
655 if (userDataObject instanceof Uri) {
656 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
657 if (info != null) {
658 c.setUserData(info);
659 }
660 } else {
661 if (userDataObject instanceof CallerInfoToken) {
662 //temporary result, while query is running
663 info = ((CallerInfoToken) userDataObject).currentInfo;
664 } else {
665 //final query result
666 info = (CallerInfo) userDataObject;
667 }
668 if (info == null) {
669 // No URI, or Existing CallerInfo, so we'll have to make do with
670 // querying a new CallerInfo using the connection's phone number.
671 String number = c.getAddress();
672
673 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
674
675 if (!TextUtils.isEmpty(number)) {
676 info = CallerInfo.getCallerInfo(context, number);
677 if (info != null) {
678 c.setUserData(info);
679 }
680 }
681 }
682 }
683 }
684 return info;
685 }
686
687 /**
688 * Class returned by the startGetCallerInfo call to package a temporary
689 * CallerInfo Object, to be superceded by the CallerInfo Object passed
690 * into the listener when the query with token mAsyncQueryToken is complete.
691 */
692 public static class CallerInfoToken {
693 /**indicates that there will no longer be updates to this request.*/
694 public boolean isFinal;
695
696 public CallerInfo currentInfo;
697 public CallerInfoAsyncQuery asyncQuery;
698 }
699
700 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700701 * place a temporary callerinfo object in the hands of the caller and notify
702 * caller when the actual query is done.
703 */
704 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -0700705 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
706 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700707 CallerInfoToken cit;
708
709 if (c == null) {
710 //TODO: perhaps throw an exception here.
711 cit = new CallerInfoToken();
712 cit.asyncQuery = null;
713 return cit;
714 }
715
716 Object userDataObject = c.getUserData();
717
718 // There are now 3 states for the Connection's userData object:
719 //
720 // (1) Uri - query has not been executed yet
721 //
722 // (2) CallerInfoToken - query is executing, but has not completed.
723 //
724 // (3) CallerInfo - query has executed.
725 //
726 // In each case we have slightly different behaviour:
727 // 1. If the query has not been executed yet (Uri or null), we start
728 // query execution asynchronously, and note it by attaching a
729 // CallerInfoToken as the userData.
730 // 2. If the query is executing (CallerInfoToken), we've essentially
731 // reached a state where we've received multiple requests for the
732 // same callerInfo. That means that once the query is complete,
733 // we'll need to execute the additional listener requested.
734 // 3. If the query has already been executed (CallerInfo), we just
735 // return the CallerInfo object as expected.
736 // 4. Regarding isFinal - there are cases where the CallerInfo object
737 // will not be attached, like when the number is empty (caller id
738 // blocking). This flag is used to indicate that the
739 // CallerInfoToken object is going to be permanent since no
740 // query results will be returned. In the case where a query
741 // has been completed, this flag is used to indicate to the caller
742 // that the data will not be updated since it is valid.
743 //
744 // Note: For the case where a number is NOT retrievable, we leave
745 // the CallerInfo as null in the CallerInfoToken. This is
746 // something of a departure from the original code, since the old
747 // code manufactured a CallerInfo object regardless of the query
748 // outcome. From now on, we will append an empty CallerInfo
749 // object, to mirror previous behaviour, and to avoid Null Pointer
750 // Exceptions.
751
752 if (userDataObject instanceof Uri) {
753 // State (1): query has not been executed yet
754
755 //create a dummy callerinfo, populate with what we know from URI.
756 cit = new CallerInfoToken();
757 cit.currentInfo = new CallerInfo();
758 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
759 (Uri) userDataObject, sCallerInfoQueryListener, c);
760 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
761 cit.isFinal = false;
762
763 c.setUserData(cit);
764
765 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
766
767 } else if (userDataObject == null) {
768 // No URI, or Existing CallerInfo, so we'll have to make do with
769 // querying a new CallerInfo using the connection's phone number.
770 String number = c.getAddress();
771
Chiao Cheng685dcb62013-10-02 11:51:06 -0700772 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -0700773 // Gateway number, the connection number is actually the gateway number.
774 // need to lookup via dialed number.
775 number = info.trueNumber;
776 }
777
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700778 if (DBG) {
779 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
780 log("- number (address): " + toLogSafePhoneNumber(number));
781 log("- c: " + c);
782 log("- phone: " + c.getCall().getPhone());
783 int phoneType = c.getCall().getPhone().getPhoneType();
784 log("- phoneType: " + phoneType);
785 switch (phoneType) {
786 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
787 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -0700788 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700789 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
790 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700791 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
792 log(" ==> PHONE_TYPE_THIRD_PARTY");
793 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700794 default: log(" ==> Unknown phone type"); break;
795 }
796 }
797
798 cit = new CallerInfoToken();
799 cit.currentInfo = new CallerInfo();
800
801 // Store CNAP information retrieved from the Connection (we want to do this
802 // here regardless of whether the number is empty or not).
803 cit.currentInfo.cnapName = c.getCnapName();
804 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
805 // by ContactInfo later
806 cit.currentInfo.numberPresentation = c.getNumberPresentation();
807 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
808
809 if (VDBG) {
810 log("startGetCallerInfo: number = " + number);
811 log("startGetCallerInfo: CNAP Info from FW(1): name="
812 + cit.currentInfo.cnapName
813 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
814 }
815
816 // handling case where number is null (caller id hidden) as well.
817 if (!TextUtils.isEmpty(number)) {
818 // Check for special CNAP cases and modify the CallerInfo accordingly
819 // to be sure we keep the right information to display/log later
820 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
821 cit.currentInfo.numberPresentation);
822
823 cit.currentInfo.phoneNumber = number;
824 // For scenarios where we may receive a valid number from the network but a
825 // restricted/unavailable presentation, we do not want to perform a contact query
826 // (see note on isFinal above). So we set isFinal to true here as well.
827 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
828 cit.isFinal = true;
829 } else {
830 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
831 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
832 number, sCallerInfoQueryListener, c);
833 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
834 cit.isFinal = false;
835 }
836 } else {
837 // This is the case where we are querying on a number that
838 // is null or empty, like a caller whose caller id is
839 // blocked or empty (CLIR). The previous behaviour was to
840 // throw a null CallerInfo object back to the user, but
841 // this departure is somewhat cleaner.
842 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
843 cit.isFinal = true; // please see note on isFinal, above.
844 }
845
846 c.setUserData(cit);
847
848 if (DBG) {
849 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
850 }
851
852 } else if (userDataObject instanceof CallerInfoToken) {
853 // State (2): query is executing, but has not completed.
854
855 // just tack on this listener to the queue.
856 cit = (CallerInfoToken) userDataObject;
857
858 // handling case where number is null (caller id hidden) as well.
859 if (cit.asyncQuery != null) {
860 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
861
862 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
863 listener.getClass().toString());
864 } else {
865 // handling case where number/name gets updated later on by the network
866 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -0700867
868 if (info != null) {
869 // Gateway number, the connection number is actually the gateway number.
870 // need to lookup via dialed number.
871 updatedNumber = info.trueNumber;
872 }
873
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700874 if (DBG) {
875 log("startGetCallerInfo: updatedNumber initially = "
876 + toLogSafePhoneNumber(updatedNumber));
877 }
878 if (!TextUtils.isEmpty(updatedNumber)) {
879 // Store CNAP information retrieved from the Connection
880 cit.currentInfo.cnapName = c.getCnapName();
881 // This can still get overwritten by ContactInfo
882 cit.currentInfo.name = cit.currentInfo.cnapName;
883 cit.currentInfo.numberPresentation = c.getNumberPresentation();
884 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
885
886 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
887 updatedNumber, cit.currentInfo.numberPresentation);
888
889 cit.currentInfo.phoneNumber = updatedNumber;
890 if (DBG) {
891 log("startGetCallerInfo: updatedNumber="
892 + toLogSafePhoneNumber(updatedNumber));
893 }
894 if (VDBG) {
895 log("startGetCallerInfo: CNAP Info from FW(2): name="
896 + cit.currentInfo.cnapName
897 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
898 } else if (DBG) {
899 log("startGetCallerInfo: CNAP Info from FW(2)");
900 }
901 // For scenarios where we may receive a valid number from the network but a
902 // restricted/unavailable presentation, we do not want to perform a contact query
903 // (see note on isFinal above). So we set isFinal to true here as well.
904 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
905 cit.isFinal = true;
906 } else {
907 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
908 updatedNumber, sCallerInfoQueryListener, c);
909 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
910 cit.isFinal = false;
911 }
912 } else {
913 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
914 if (cit.currentInfo == null) {
915 cit.currentInfo = new CallerInfo();
916 }
917 // Store CNAP information retrieved from the Connection
918 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
919 // overwritten by ContactInfo
920 cit.currentInfo.name = cit.currentInfo.cnapName;
921 cit.currentInfo.numberPresentation = c.getNumberPresentation();
922 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
923
924 if (VDBG) {
925 log("startGetCallerInfo: CNAP Info from FW(3): name="
926 + cit.currentInfo.cnapName
927 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
928 } else if (DBG) {
929 log("startGetCallerInfo: CNAP Info from FW(3)");
930 }
931 cit.isFinal = true; // please see note on isFinal, above.
932 }
933 }
934 } else {
935 // State (3): query is complete.
936
937 // The connection's userDataObject is a full-fledged
938 // CallerInfo instance. Wrap it in a CallerInfoToken and
939 // return it to the user.
940
941 cit = new CallerInfoToken();
942 cit.currentInfo = (CallerInfo) userDataObject;
943 cit.asyncQuery = null;
944 cit.isFinal = true;
945 // since the query is already done, call the listener.
946 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
947 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
948 }
949 return cit;
950 }
951
952 /**
953 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
954 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
955 */
956 private static final int QUERY_TOKEN = -1;
957 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
958 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
959 /**
960 * When the query completes, we stash the resulting CallerInfo
961 * object away in the Connection's "userData" (where it will
962 * later be retrieved by the in-call UI.)
963 */
964 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
965 if (DBG) log("query complete, updating connection.userdata");
966 Connection conn = (Connection) cookie;
967
968 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
969 // If no ContactInfo, then we want to use CNAP information coming from network
970 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
971 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
972 // If the number presentation has not been set by
973 // the ContactInfo, use the one from the
974 // connection.
975
976 // TODO: Need a new util method to merge the info
977 // from the Connection in a CallerInfo object.
978 // Here 'ci' is a new CallerInfo instance read
979 // from the DB. It has lost all the connection
980 // info preset before the query (see PhoneUtils
981 // line 1334). We should have a method to merge
982 // back into this new instance the info from the
983 // connection object not set by the DB. If the
984 // Connection already has a CallerInfo instance in
985 // userData, then we could use this instance to
986 // fill 'ci' in. The same routine could be used in
987 // PhoneUtils.
988 if (0 == ci.numberPresentation) {
989 ci.numberPresentation = conn.getNumberPresentation();
990 }
991 } else {
992 // No matching contact was found for this number.
993 // Return a new CallerInfo based solely on the CNAP
994 // information from the network.
995
996 CallerInfo newCi = getCallerInfo(null, conn);
997
998 // ...but copy over the (few) things we care about
999 // from the original CallerInfo object:
1000 if (newCi != null) {
1001 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1002 newCi.geoDescription = ci.geoDescription; // To get geo description string
1003 ci = newCi;
1004 }
1005 }
1006
1007 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1008 conn.setUserData(ci);
1009 }
1010 };
1011
1012
1013 /**
1014 * Returns a single "name" for the specified given a CallerInfo object.
1015 * If the name is null, return defaultString as the default value, usually
1016 * context.getString(R.string.unknown).
1017 */
1018 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1019 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1020
1021 String compactName = null;
1022 if (ci != null) {
1023 if (TextUtils.isEmpty(ci.name)) {
1024 // Perform any modifications for special CNAP cases to
1025 // the phone number being displayed, if applicable.
1026 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1027 ci.numberPresentation);
1028 } else {
1029 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1030 compactName = ci.name;
1031 }
1032 }
1033
1034 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1035 // If we're still null/empty here, then check if we have a presentation
1036 // string that takes precedence that we could return, otherwise display
1037 // "unknown" string.
1038 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1039 compactName = context.getString(R.string.private_num);
1040 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1041 compactName = context.getString(R.string.payphone);
1042 } else {
1043 compactName = context.getString(R.string.unknown);
1044 }
1045 }
1046 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1047 return compactName;
1048 }
1049
Tyler Gunna1abb582018-09-14 16:12:01 -07001050 static boolean isInEmergencyCall(CallManager cm) {
1051 Call fgCall = cm.getActiveFgCall();
1052 // isIdle includes checks for the DISCONNECTING/DISCONNECTED state.
1053 if(!fgCall.isIdle()) {
1054 for (Connection cn : fgCall.getConnections()) {
1055 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
1056 cn.getAddress())) {
1057 return true;
1058 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001059 }
1060 }
1061 return false;
1062 }
1063
1064 //
1065 // Misc UI policy helper functions
1066 //
1067
1068 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001069 * Based on the input CNAP number string,
1070 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1071 * Otherwise, return CNAP_SPECIAL_CASE_NO.
1072 */
1073 private static int checkCnapSpecialCases(String n) {
1074 if (n.equals("PRIVATE") ||
1075 n.equals("P") ||
1076 n.equals("RES")) {
1077 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1078 return PhoneConstants.PRESENTATION_RESTRICTED;
1079 } else if (n.equals("UNAVAILABLE") ||
1080 n.equals("UNKNOWN") ||
1081 n.equals("UNA") ||
1082 n.equals("U")) {
1083 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1084 return PhoneConstants.PRESENTATION_UNKNOWN;
1085 } else {
1086 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1087 return CNAP_SPECIAL_CASE_NO;
1088 }
1089 }
1090
1091 /**
1092 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
1093 * from the network to indicate different number presentations, convert them to
1094 * expected number and presentation values within the CallerInfo object.
1095 * @param number number we use to verify if we are in a corner case
1096 * @param presentation presentation value used to verify if we are in a corner case
1097 * @return the new String that should be used for the phone number
1098 */
1099 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
1100 String number, int presentation) {
1101 // Obviously we return number if ci == null, but still return number if
1102 // number == null, because in these cases the correct string will still be
1103 // displayed/logged after this function returns based on the presentation value.
1104 if (ci == null || number == null) return number;
1105
1106 if (DBG) {
1107 log("modifyForSpecialCnapCases: initially, number="
1108 + toLogSafePhoneNumber(number)
1109 + ", presentation=" + presentation + " ci " + ci);
1110 }
1111
1112 // "ABSENT NUMBER" is a possible value we could get from the network as the
1113 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
1114 // and fix the presentation to be the same.
1115 final String[] absentNumberValues =
1116 context.getResources().getStringArray(R.array.absent_num);
1117 if (Arrays.asList(absentNumberValues).contains(number)
1118 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
1119 number = context.getString(R.string.unknown);
1120 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
1121 }
1122
1123 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
1124 // cases only apply if we received an allowed presentation from the network, so check
1125 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
1126 // match the presentation passed in for verification (meaning we changed it previously
1127 // because it's a corner case and we're being called from a different entry point).
1128 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
1129 || (ci.numberPresentation != presentation
1130 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
1131 int cnapSpecialCase = checkCnapSpecialCases(number);
1132 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
1133 // For all special strings, change number & numberPresentation.
1134 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
1135 number = context.getString(R.string.private_num);
1136 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
1137 number = context.getString(R.string.unknown);
1138 }
1139 if (DBG) {
1140 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
1141 + "; presentation now=" + cnapSpecialCase);
1142 }
1143 ci.numberPresentation = cnapSpecialCase;
1144 }
1145 }
1146 if (DBG) {
1147 log("modifyForSpecialCnapCases: returning number string="
1148 + toLogSafePhoneNumber(number));
1149 }
1150 return number;
1151 }
1152
1153 //
1154 // Support for 3rd party phone service providers.
1155 //
1156
1157 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001158 * Check if a phone number can be route through a 3rd party
1159 * gateway. The number must be a global phone number in numerical
1160 * form (1-800-666-SEXY won't work).
1161 *
1162 * MMI codes and the like cannot be used as a dial number for the
1163 * gateway either.
1164 *
1165 * @param number To be dialed via a 3rd party gateway.
1166 * @return true If the number can be routed through the 3rd party network.
1167 */
Santos Cordon69a69192013-08-22 14:25:42 -07001168 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001169 if (TextUtils.isEmpty(number)) {
1170 return false;
1171 }
1172 number = PhoneNumberUtils.stripSeparators(number);
1173 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
1174 return false;
1175 }
1176 number = PhoneNumberUtils.extractNetworkPortion(number);
1177 return PhoneNumberUtils.isGlobalPhoneNumber(number);
1178 }
1179
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001180 /**
1181 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
1182 */
1183 /* package */ static boolean isPhoneInEcm(Phone phone) {
1184 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
Shuo Qiandd210312017-04-12 22:11:33 +00001185 return phone.isInEcm();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001186 }
1187 return false;
1188 }
1189
1190 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001191 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
1192 * meaning the call is the first real incoming call the phone is having.
1193 */
1194 public static boolean isRealIncomingCall(Call.State state) {
1195 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
1196 }
1197
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001198 //
1199 // General phone and call state debugging/testing code
1200 //
1201
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001202 private static void log(String msg) {
1203 Log.d(LOG_TAG, msg);
1204 }
1205
Nancy Chene53a0642015-03-12 11:20:12 -07001206 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
1207 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
1208 }
1209
Nancy Chen32031f42015-03-04 21:00:07 -08001210 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
1211 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
1212 }
1213
Andrew Leed5165b02014-12-05 15:53:58 -08001214 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
1215 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
1216 }
1217
1218 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1219 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08001220 // TODO: Should use some sort of special hidden flag to decorate this account as
1221 // an emergency-only account
Brad Ebingerd3edc222016-03-23 19:44:38 -07001222 String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
Brad Ebinger4fe48112016-04-13 11:21:53 -07001223 String.valueOf(phone.getFullIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07001224 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
1225 }
1226
1227 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1228 String id, String prefix, boolean isEmergency) {
1229 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08001230 return new PhoneAccountHandle(pstnConnectionServiceName, id);
1231 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08001232
Santos Cordonf69df962015-02-03 11:15:19 -08001233 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08001234 if (phoneAccount != null
1235 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
1236 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
1237 }
1238 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1239 }
1240
1241 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001242 Phone phone = getPhoneForPhoneAccountHandle(handle);
1243 if (phone != null) {
1244 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08001245 }
1246 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1247 }
1248
Ta-wei Yen845f6992016-06-16 12:53:46 -07001249 public static Phone getPhoneForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001250 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
1251 return getPhoneFromIccId(handle.getId());
1252 }
1253 return null;
1254 }
1255
Nancy Chene53a0642015-03-12 11:20:12 -07001256 /**
1257 * Determine if a given phone account corresponds to an active SIM
1258 *
1259 * @param sm An instance of the subscription manager so it is not recreated for each calling of
1260 * this method.
1261 * @param handle The handle for the phone account to check
1262 * @return {@code true} If there is an active SIM for this phone account,
1263 * {@code false} otherwise.
1264 */
1265 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
1266 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
1267 }
1268
Santos Cordonf69df962015-02-03 11:15:19 -08001269 private static ComponentName getPstnConnectionServiceName() {
Tony Mak4c8f3c62015-12-07 02:30:37 +00001270 return PSTN_CONNECTION_SERVICE_COMPONENT;
Santos Cordonf69df962015-02-03 11:15:19 -08001271 }
1272
Santos Cordon80855d52015-02-10 04:33:36 -08001273 private static Phone getPhoneFromIccId(String iccId) {
1274 if (!TextUtils.isEmpty(iccId)) {
1275 for (Phone phone : PhoneFactory.getPhones()) {
Brad Ebinger4fe48112016-04-13 11:21:53 -07001276 String phoneIccId = phone.getFullIccSerialNumber();
Santos Cordon80855d52015-02-10 04:33:36 -08001277 if (iccId.equals(phoneIccId)) {
1278 return phone;
1279 }
1280 }
1281 }
Santos Cordon80855d52015-02-10 04:33:36 -08001282 return null;
1283 }
1284
Stuart Scottdcf40a92014-12-09 10:45:01 -08001285 /**
1286 * Register ICC status for all phones.
1287 */
1288 static final void registerIccStatus(Handler handler, int event) {
1289 for (Phone phone : PhoneFactory.getPhones()) {
1290 IccCard sim = phone.getIccCard();
1291 if (sim != null) {
1292 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
1293 sim.registerForNetworkLocked(handler, event, phone);
1294 }
1295 }
1296 }
1297
1298 /**
1299 * Set the radio power on/off state for all phones.
1300 *
1301 * @param enabled true means on, false means off.
1302 */
1303 static final void setRadioPower(boolean enabled) {
1304 for (Phone phone : PhoneFactory.getPhones()) {
1305 phone.setRadioPower(enabled);
1306 }
1307 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001308}