blob: 6c3f0bfddb9fd553b2b249d5cdbcf177e809cc39 [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;
Sailesh Nepalbfb68322013-11-07 14:07:41 -080022import android.content.ComponentName;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070023import android.content.Context;
24import android.content.DialogInterface;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070025import android.net.Uri;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070026import android.os.Handler;
27import android.os.Message;
SongFerngWang5ae4f6d2018-10-31 22:11:32 +080028import android.os.PersistableBundle;
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;
SongFerngWang5ae4f6d2018-10-31 22:11:32 +080032import android.telephony.CarrierConfigManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070033import android.telephony.PhoneNumberUtils;
Santos Cordonf69df962015-02-03 11:15:19 -080034import android.telephony.SubscriptionManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070035import android.text.TextUtils;
36import android.util.Log;
Andrew Leeb3ee4dc2015-01-23 17:35:00 -080037import android.view.ContextThemeWrapper;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070038import android.view.KeyEvent;
39import android.view.LayoutInflater;
40import android.view.View;
41import android.view.WindowManager;
42import android.widget.EditText;
43import android.widget.Toast;
44
45import com.android.internal.telephony.Call;
46import com.android.internal.telephony.CallManager;
47import com.android.internal.telephony.CallStateException;
Chen Xu0437d992019-09-07 19:04:31 -070048import android.telephony.CallerInfo;
49import android.telephony.CallerInfoAsyncQuery;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070050import com.android.internal.telephony.Connection;
Stuart Scottdcf40a92014-12-09 10:45:01 -080051import com.android.internal.telephony.IccCard;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070052import com.android.internal.telephony.MmiCode;
53import com.android.internal.telephony.Phone;
54import com.android.internal.telephony.PhoneConstants;
Stuart Scottdcf40a92014-12-09 10:45:01 -080055import com.android.internal.telephony.PhoneFactory;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070056import com.android.internal.telephony.TelephonyCapabilities;
Santos Cordon69a69192013-08-22 14:25:42 -070057import com.android.phone.CallGatewayManager.RawGatewayInfo;
SongFerngWang5ae4f6d2018-10-31 22:11:32 +080058import com.android.phone.settings.SuppServicesUiUtil;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070059
Santos Cordon7d4ddf62013-07-10 11:58:08 -070060import java.util.Arrays;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070061import java.util.List;
62
63/**
64 * Misc utilities for the Phone app.
65 */
66public class PhoneUtils {
Brad Ebingerd3edc222016-03-23 19:44:38 -070067 public static final String EMERGENCY_ACCOUNT_HANDLE_ID = "E";
Santos Cordon7d4ddf62013-07-10 11:58:08 -070068 private static final String LOG_TAG = "PhoneUtils";
69 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
70
71 // Do not check in with VDBG = true, since that may write PII to the system log.
72 private static final boolean VDBG = false;
73
Santos Cordon7d4ddf62013-07-10 11:58:08 -070074 // Return codes from placeCall()
fionaxuf7885142016-11-27 16:08:39 -080075 public static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed
76 public static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code
77 public static final int CALL_STATUS_FAILED = 2; // The call failed
Santos Cordon7d4ddf62013-07-10 11:58:08 -070078
Santos Cordon7d4ddf62013-07-10 11:58:08 -070079 // USSD string length for MMI operations
80 static final int MIN_USSD_LEN = 1;
81 static final int MAX_USSD_LEN = 160;
82
Santos Cordon7d4ddf62013-07-10 11:58:08 -070083 /** Define for not a special CNAP string */
84 private static final int CNAP_SPECIAL_CASE_NO = -1;
85
Yorke Leee0f2b792014-10-15 12:30:44 -070086 /**
87 * Theme to use for dialogs displayed by utility methods in this class. This is needed
88 * because these dialogs are displayed using the application context, which does not resolve
89 * the dialog theme correctly.
90 */
Zheng Zhangd889c772017-11-02 15:49:37 -070091 private static final int THEME = com.android.internal.R.style.Theme_DeviceDefault_Dialog_Alert;
Yorke Leee0f2b792014-10-15 12:30:44 -070092
Etan Cohen37abbab2014-03-07 16:57:03 -080093 /** USSD information used to aggregate all USSD messages */
94 private static AlertDialog sUssdDialog = null;
95 private static StringBuilder sUssdMsg = new StringBuilder();
96
Tony Mak4c8f3c62015-12-07 02:30:37 +000097 private static final ComponentName PSTN_CONNECTION_SERVICE_COMPONENT =
98 new ComponentName("com.android.phone",
99 "com.android.services.telephony.TelephonyConnectionService");
100
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700101 /** This class is never instantiated. */
102 private PhoneUtils() {
103 }
104
105 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700106 * For a CDMA phone, advance the call state upon making a new
107 * outgoing call.
108 *
109 * <pre>
110 * IDLE -> SINGLE_ACTIVE
111 * or
112 * SINGLE_ACTIVE -> THRWAY_ACTIVE
113 * </pre>
114 * @param app The phone instance.
115 */
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700116 private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app,
117 Connection connection) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700118 if (app.cdmaPhoneCallState.getCurrentCallState() ==
119 CdmaPhoneCallState.PhoneCallState.IDLE) {
120 // This is the first outgoing call. Set the Phone Call State to ACTIVE
121 app.cdmaPhoneCallState.setCurrentCallState(
122 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
123 } else {
124 // This is the second outgoing call. Set the Phone Call State to 3WAY
125 app.cdmaPhoneCallState.setCurrentCallState(
126 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700127
Santos Cordonda120f42014-08-06 04:44:34 -0700128 // TODO: Remove this code.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700129 //app.getCallModeler().setCdmaOutgoing3WayCall(connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700130 }
131 }
132
133 /**
Santos Cordon69a69192013-08-22 14:25:42 -0700134 * @see placeCall below
135 */
136 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
137 boolean isEmergencyCall) {
138 return placeCall(context, phone, number, contactRef, isEmergencyCall,
139 CallGatewayManager.EMPTY_INFO, null);
140 }
141
142 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700143 * Dial the number using the phone passed in.
144 *
145 * If the connection is establised, this method issues a sync call
146 * that may block to query the caller info.
147 * TODO: Change the logic to use the async query.
148 *
149 * @param context To perform the CallerInfo query.
150 * @param phone the Phone object.
151 * @param number to be dialed as requested by the user. This is
152 * NOT the phone number to connect to. It is used only to build the
153 * call card and to update the call log. See above for restrictions.
154 * @param contactRef that triggered the call. Typically a 'tel:'
155 * uri but can also be a 'content://contacts' one.
156 * @param isEmergencyCall indicates that whether or not this is an
157 * emergency call
158 * @param gatewayUri Is the address used to setup the connection, null
159 * if not using a gateway
Santos Cordon69a69192013-08-22 14:25:42 -0700160 * @param callGateway Class for setting gateway data on a successful call.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700161 *
162 * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
163 */
Santos Cordon69a69192013-08-22 14:25:42 -0700164 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
165 boolean isEmergencyCall, RawGatewayInfo gatewayInfo, CallGatewayManager callGateway) {
166 final Uri gatewayUri = gatewayInfo.gatewayUri;
167
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700168 if (VDBG) {
169 log("placeCall()... number: '" + number + "'"
170 + ", GW:'" + gatewayUri + "'"
171 + ", contactRef:" + contactRef
172 + ", isEmergencyCall: " + isEmergencyCall);
173 } else {
174 log("placeCall()... number: " + toLogSafePhoneNumber(number)
175 + ", GW: " + (gatewayUri != null ? "non-null" : "null")
176 + ", emergency? " + isEmergencyCall);
177 }
178 final PhoneGlobals app = PhoneGlobals.getInstance();
179
180 boolean useGateway = false;
181 if (null != gatewayUri &&
182 !isEmergencyCall &&
183 PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes.
184 useGateway = true;
185 }
186
187 int status = CALL_STATUS_DIALED;
188 Connection connection;
189 String numberToDial;
190 if (useGateway) {
191 // TODO: 'tel' should be a constant defined in framework base
192 // somewhere (it is in webkit.)
Jay Shrauner137458b2014-09-05 14:27:25 -0700193 if (null == gatewayUri || !PhoneAccount.SCHEME_TEL.equals(gatewayUri.getScheme())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700194 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
195 return CALL_STATUS_FAILED;
196 }
197
198 // We can use getSchemeSpecificPart because we don't allow #
199 // in the gateway numbers (treated a fragment delim.) However
200 // if we allow more complex gateway numbers sequence (with
201 // passwords or whatnot) that use #, this may break.
202 // TODO: Need to support MMI codes.
203 numberToDial = gatewayUri.getSchemeSpecificPart();
204 } else {
205 numberToDial = number;
206 }
207
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700208 try {
Tyler Gunnc6514352015-06-02 21:46:34 -0700209 connection = app.mCM.dial(phone, numberToDial, VideoProfile.STATE_AUDIO_ONLY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700210 } catch (CallStateException ex) {
211 // CallStateException means a new outgoing call is not currently
212 // possible: either no more call slots exist, or there's another
213 // call already in the process of dialing or ringing.
214 Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
215 return CALL_STATUS_FAILED;
216
217 // Note that it's possible for CallManager.dial() to return
218 // null *without* throwing an exception; that indicates that
219 // we dialed an MMI (see below).
220 }
221
222 int phoneType = phone.getPhoneType();
223
224 // On GSM phones, null is returned for MMI codes
225 if (null == connection) {
Santos Cordonf77a3392014-07-21 19:48:10 -0700226 status = CALL_STATUS_FAILED;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700227 } else {
228 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700229 updateCdmaCallStateOnNewOutgoingCall(app, connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700230 }
231
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700232 if (gatewayUri == null) {
233 // phone.dial() succeeded: we're now in a normal phone call.
234 // attach the URI to the CallerInfo Object if it is there,
235 // otherwise just attach the Uri Reference.
236 // if the uri does not have a "content" scheme, then we treat
237 // it as if it does NOT have a unique reference.
238 String content = context.getContentResolver().SCHEME_CONTENT;
239 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
240 Object userDataObject = connection.getUserData();
241 if (userDataObject == null) {
242 connection.setUserData(contactRef);
243 } else {
244 // TODO: This branch is dead code, we have
245 // just created the connection which has
246 // no user data (null) by default.
247 if (userDataObject instanceof CallerInfo) {
248 ((CallerInfo) userDataObject).contactRefUri = contactRef;
249 } else {
250 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
251 contactRef;
252 }
253 }
254 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700255 }
Santos Cordonc264cba2013-09-19 04:55:40 -0700256
Chiao Chenge365ba72013-09-26 14:18:12 -0700257 startGetCallerInfo(context, connection, null, null, gatewayInfo);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700258 }
259
260 return status;
261 }
262
263 /* package */ static String toLogSafePhoneNumber(String number) {
264 // For unknown number, log empty string.
265 if (number == null) {
266 return "";
267 }
268
269 if (VDBG) {
270 // When VDBG is true we emit PII.
271 return number;
272 }
273
274 // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
275 // sanitized phone numbers.
276 StringBuilder builder = new StringBuilder();
277 for (int i = 0; i < number.length(); i++) {
278 char c = number.charAt(i);
279 if (c == '-' || c == '@' || c == '.') {
280 builder.append(c);
281 } else {
282 builder.append('x');
283 }
284 }
285 return builder.toString();
286 }
287
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700288 /**
289 * Handle the MMIInitiate message and put up an alert that lets
290 * the user cancel the operation, if applicable.
291 *
292 * @param context context to get strings.
293 * @param mmiCode the MmiCode object being started.
294 * @param buttonCallbackMessage message to post when button is clicked.
295 * @param previousAlert a previous alert used in this activity.
296 * @return the dialog handle
297 */
298 static Dialog displayMMIInitiate(Context context,
299 MmiCode mmiCode,
300 Message buttonCallbackMessage,
301 Dialog previousAlert) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700302 log("displayMMIInitiate: " + android.telecom.Log.pii(mmiCode.toString()));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700303 if (previousAlert != null) {
304 previousAlert.dismiss();
305 }
306
307 // The UI paradigm we are using now requests that all dialogs have
308 // user interaction, and that any other messages to the user should
309 // be by way of Toasts.
310 //
311 // In adhering to this request, all MMI initiating "OK" dialogs
312 // (non-cancelable MMIs) that end up being closed when the MMI
313 // completes (thereby showing a completion dialog) are being
314 // replaced with Toasts.
315 //
316 // As a side effect, moving to Toasts for the non-cancelable MMIs
317 // also means that buttonCallbackMessage (which was tied into "OK")
318 // is no longer invokable for these dialogs. This is not a problem
319 // since the only callback messages we supported were for cancelable
320 // MMIs anyway.
321 //
322 // A cancelable MMI is really just a USSD request. The term
323 // "cancelable" here means that we can cancel the request when the
324 // system prompts us for a response, NOT while the network is
325 // processing the MMI request. Any request to cancel a USSD while
326 // the network is NOT ready for a response may be ignored.
327 //
328 // With this in mind, we replace the cancelable alert dialog with
329 // a progress dialog, displayed until we receive a request from
330 // the the network. For more information, please see the comments
331 // in the displayMMIComplete() method below.
332 //
333 // Anything that is NOT a USSD request is a normal MMI request,
334 // which will bring up a toast (desribed above).
335
336 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
337
338 if (!isCancelable) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700339 log("displayMMIInitiate: not a USSD code, displaying status toast.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700340 CharSequence text = context.getText(R.string.mmiStarted);
341 Toast.makeText(context, text, Toast.LENGTH_SHORT)
342 .show();
343 return null;
344 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700345 log("displayMMIInitiate: running USSD code, displaying intermediate progress.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700346
347 // create the indeterminate progress dialog and display it.
Alex Hills779841a2015-10-22 13:23:28 -0400348 ProgressDialog pd = new ProgressDialog(context, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700349 pd.setMessage(context.getText(R.string.ussdRunning));
350 pd.setCancelable(false);
351 pd.setIndeterminate(true);
352 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
353
354 pd.show();
355
356 return pd;
357 }
358
359 }
360
361 /**
362 * Handle the MMIComplete message and fire off an intent to display
363 * the message.
364 *
365 * @param context context to get strings.
366 * @param mmiCode MMI result.
367 * @param previousAlert a previous alert used in this activity.
368 */
369 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
370 Message dismissCallbackMessage,
371 AlertDialog previousAlert) {
372 final PhoneGlobals app = PhoneGlobals.getInstance();
373 CharSequence text;
374 int title = 0; // title for the progress dialog, if needed.
375 MmiCode.State state = mmiCode.getState();
376
Tyler Gunn13fe2492017-05-22 14:14:20 -0700377 log("displayMMIComplete: state=" + state);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700378
379 switch (state) {
380 case PENDING:
381 // USSD code asking for feedback from user.
382 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700383 log("displayMMIComplete: using text from PENDING MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700384 break;
385 case CANCELLED:
386 text = null;
387 break;
388 case COMPLETE:
SongFerngWang5ae4f6d2018-10-31 22:11:32 +0800389 PersistableBundle b = null;
390 if (SubscriptionManager.isValidSubscriptionId(phone.getSubId())) {
391 b = app.getCarrierConfigForSubId(
392 phone.getSubId());
393 } else {
394 b = app.getCarrierConfig();
395 }
396
397 if (b.getBoolean(CarrierConfigManager.KEY_USE_CALLER_ID_USSD_BOOL)) {
398 text = SuppServicesUiUtil.handleCallerIdUssdResponse(app, context, phone,
399 mmiCode);
400 if (mmiCode.getMessage() != null && !text.equals(mmiCode.getMessage())) {
401 break;
402 }
403 }
404
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700405 if (app.getPUKEntryActivity() != null) {
406 // if an attempt to unPUK the device was made, we specify
407 // the title and the message here.
408 title = com.android.internal.R.string.PinMmi;
409 text = context.getText(R.string.puk_unlocked);
410 break;
411 }
412 // All other conditions for the COMPLETE mmi state will cause
413 // the case to fall through to message logic in common with
414 // the FAILED case.
415
416 case FAILED:
417 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700418 log("displayMMIComplete (failed): using text from MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700419 break;
420 default:
421 throw new IllegalStateException("Unexpected MmiCode state: " + state);
422 }
423
424 if (previousAlert != null) {
425 previousAlert.dismiss();
426 }
427
428 // Check to see if a UI exists for the PUK activation. If it does
429 // exist, then it indicates that we're trying to unblock the PUK.
430 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
431 if (DBG) log("displaying PUK unblocking progress dialog.");
432
433 // create the progress dialog, make sure the flags and type are
434 // set correctly.
Alex Hills779841a2015-10-22 13:23:28 -0400435 ProgressDialog pd = new ProgressDialog(app, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700436 pd.setTitle(title);
437 pd.setMessage(text);
438 pd.setCancelable(false);
439 pd.setIndeterminate(true);
440 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
441 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
442
443 // display the dialog
444 pd.show();
445
446 // indicate to the Phone app that the progress dialog has
447 // been assigned for the PUK unlock / SIM READY process.
448 app.setPukEntryProgressDialog(pd);
449
SongFerngWangdfa107a2018-10-29 20:31:58 +0800450 } else if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.FAILED)) {
Youming Yeef84f3e2019-04-15 14:05:02 -0700451 createUssdDialog(app, context, text, phone,
SongFerngWangdfa107a2018-10-29 20:31:58 +0800452 WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
453 // In case of failure to unlock, we'll need to reset the
454 // PUK unlock activity, so that the user may try again.
455 app.setPukEntryActivity(null);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700456 } else {
457 // In case of failure to unlock, we'll need to reset the
458 // PUK unlock activity, so that the user may try again.
459 if (app.getPUKEntryActivity() != null) {
460 app.setPukEntryActivity(null);
461 }
462
463 // A USSD in a pending state means that it is still
464 // interacting with the user.
465 if (state != MmiCode.State.PENDING) {
Youming Yeef84f3e2019-04-15 14:05:02 -0700466 createUssdDialog(app, context, text, phone,
SongFerngWangdfa107a2018-10-29 20:31:58 +0800467 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700468 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700469 log("displayMMIComplete: USSD code has requested user input. Constructing input "
470 + "dialog.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700471
472 // USSD MMI code that is interacting with the user. The
473 // basic set of steps is this:
474 // 1. User enters a USSD request
475 // 2. We recognize the request and displayMMIInitiate
476 // (above) creates a progress dialog.
477 // 3. Request returns and we get a PENDING or COMPLETE
478 // message.
479 // 4. These MMI messages are caught in the PhoneApp
480 // (onMMIComplete) and the InCallScreen
481 // (mHandler.handleMessage) which bring up this dialog
482 // and closes the original progress dialog,
483 // respectively.
484 // 5. If the message is anything other than PENDING,
485 // we are done, and the alert dialog (directly above)
486 // displays the outcome.
487 // 6. If the network is requesting more information from
488 // the user, the MMI will be in a PENDING state, and
489 // we display this dialog with the message.
490 // 7. User input, or cancel requests result in a return
491 // to step 1. Keep in mind that this is the only
492 // time that a USSD should be canceled.
493
494 // inflate the layout with the scrolling text area for the dialog.
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800495 ContextThemeWrapper contextThemeWrapper =
496 new ContextThemeWrapper(context, R.style.DialerAlertDialogTheme);
497 LayoutInflater inflater = (LayoutInflater) contextThemeWrapper.getSystemService(
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700498 Context.LAYOUT_INFLATER_SERVICE);
499 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
500
501 // get the input field.
502 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
503
504 // specify the dialog's click listener, with SEND and CANCEL logic.
505 final DialogInterface.OnClickListener mUSSDDialogListener =
506 new DialogInterface.OnClickListener() {
507 public void onClick(DialogInterface dialog, int whichButton) {
508 switch (whichButton) {
509 case DialogInterface.BUTTON_POSITIVE:
510 // As per spec 24.080, valid length of ussd string
511 // is 1 - 160. If length is out of the range then
512 // display toast message & Cancel MMI operation.
513 if (inputText.length() < MIN_USSD_LEN
514 || inputText.length() > MAX_USSD_LEN) {
515 Toast.makeText(app,
516 app.getResources().getString(R.string.enter_input,
517 MIN_USSD_LEN, MAX_USSD_LEN),
518 Toast.LENGTH_LONG).show();
519 if (mmiCode.isCancelable()) {
520 mmiCode.cancel();
521 }
522 } else {
523 phone.sendUssdResponse(inputText.getText().toString());
524 }
525 break;
526 case DialogInterface.BUTTON_NEGATIVE:
527 if (mmiCode.isCancelable()) {
528 mmiCode.cancel();
529 }
530 break;
531 }
532 }
533 };
534
535 // build the dialog
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800536 final AlertDialog newDialog = new AlertDialog.Builder(contextThemeWrapper)
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700537 .setMessage(text)
538 .setView(dialogView)
539 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
540 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
541 .setCancelable(false)
542 .create();
543
544 // attach the key listener to the dialog's input field and make
545 // sure focus is set.
546 final View.OnKeyListener mUSSDDialogInputListener =
547 new View.OnKeyListener() {
548 public boolean onKey(View v, int keyCode, KeyEvent event) {
549 switch (keyCode) {
550 case KeyEvent.KEYCODE_CALL:
551 case KeyEvent.KEYCODE_ENTER:
552 if(event.getAction() == KeyEvent.ACTION_DOWN) {
553 phone.sendUssdResponse(inputText.getText().toString());
554 newDialog.dismiss();
555 }
556 return true;
557 }
558 return false;
559 }
560 };
561 inputText.setOnKeyListener(mUSSDDialogInputListener);
562 inputText.requestFocus();
563
564 // set the window properties of the dialog
565 newDialog.getWindow().setType(
566 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
567 newDialog.getWindow().addFlags(
568 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
569
570 // now show the dialog!
571 newDialog.show();
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800572
573 newDialog.getButton(DialogInterface.BUTTON_POSITIVE)
574 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
575 newDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
576 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700577 }
578 }
579 }
580
SongFerngWang5ae4f6d2018-10-31 22:11:32 +0800581 /**
582 * It displays the message dialog for user about the mmi code result message.
583 *
584 * @param app This is {@link PhoneGlobals}
585 * @param context Context to get strings.
586 * @param text This is message's result.
Youming Yeef84f3e2019-04-15 14:05:02 -0700587 * @param phone This is phone to create sssd dialog.
SongFerngWang5ae4f6d2018-10-31 22:11:32 +0800588 * @param windowType The new window type. {@link WindowManager.LayoutParams}.
589 */
590 public static void createUssdDialog(PhoneGlobals app, Context context, CharSequence text,
Youming Yeef84f3e2019-04-15 14:05:02 -0700591 Phone phone, int windowType) {
SongFerngWangdfa107a2018-10-29 20:31:58 +0800592 log("displayMMIComplete: MMI code has finished running.");
593
594 log("displayMMIComplete: Extended NW displayMMIInitiate (" + text + ")");
595 if (text == null || text.length() == 0) {
596 return;
597 }
598
599 // displaying system alert dialog on the screen instead of
600 // using another activity to display the message. This
601 // places the message at the forefront of the UI.
602
603 if (sUssdDialog == null) {
604 sUssdDialog = new AlertDialog.Builder(context, THEME)
605 .setPositiveButton(R.string.ok, null)
606 .setCancelable(true)
607 .setOnDismissListener(new DialogInterface.OnDismissListener() {
608 @Override
609 public void onDismiss(DialogInterface dialog) {
610 sUssdMsg.setLength(0);
611 }
612 })
613 .create();
614
615 sUssdDialog.getWindow().setType(windowType);
616 sUssdDialog.getWindow().addFlags(
617 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
618 }
619 if (sUssdMsg.length() != 0) {
620 sUssdMsg
621 .insert(0, "\n")
622 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
623 .insert(0, "\n");
624 }
Youming Yeef84f3e2019-04-15 14:05:02 -0700625 if (phone != null && phone.getCarrierName() != null) {
626 sUssdDialog.setTitle(app.getResources().getString(R.string.carrier_mmi_msg_title,
627 phone.getCarrierName()));
628 } else {
629 sUssdDialog
630 .setTitle(app.getResources().getString(R.string.default_carrier_mmi_msg_title));
631 }
SongFerngWangdfa107a2018-10-29 20:31:58 +0800632 sUssdMsg.insert(0, text);
633 sUssdDialog.setMessage(sUssdMsg.toString());
634 sUssdDialog.show();
635 }
636
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700637 /**
638 * Cancels the current pending MMI operation, if applicable.
639 * @return true if we canceled an MMI operation, or false
640 * if the current pending MMI wasn't cancelable
641 * or if there was no current pending MMI at all.
642 *
643 * @see displayMMIInitiate
644 */
645 static boolean cancelMmiCode(Phone phone) {
646 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
647 int count = pendingMmis.size();
648 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
649
650 boolean canceled = false;
651 if (count > 0) {
652 // assume that we only have one pending MMI operation active at a time.
653 // I don't think it's possible to enter multiple MMI codes concurrently
654 // in the phone UI, because during the MMI operation, an Alert panel
655 // is displayed, which prevents more MMI code from being entered.
656 MmiCode mmiCode = pendingMmis.get(0);
657 if (mmiCode.isCancelable()) {
658 mmiCode.cancel();
659 canceled = true;
660 }
661 }
662 return canceled;
663 }
664
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700665 /**
666 * Returns the caller-id info corresponding to the specified Connection.
667 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
668 * extract a phone number from the specified Connection, and feed that
669 * number into CallerInfo.getCallerInfo().)
670 *
671 * The returned CallerInfo may be null in certain error cases, like if the
672 * specified Connection was null, or if we weren't able to get a valid
673 * phone number from the Connection.
674 *
675 * Finally, if the getCallerInfo() call did succeed, we save the resulting
676 * CallerInfo object in the "userData" field of the Connection.
677 *
678 * NOTE: This API should be avoided, with preference given to the
679 * asynchronous startGetCallerInfo API.
680 */
681 static CallerInfo getCallerInfo(Context context, Connection c) {
682 CallerInfo info = null;
683
684 if (c != null) {
685 //See if there is a URI attached. If there is, this means
686 //that there is no CallerInfo queried yet, so we'll need to
687 //replace the URI with a full CallerInfo object.
688 Object userDataObject = c.getUserData();
689 if (userDataObject instanceof Uri) {
690 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
691 if (info != null) {
692 c.setUserData(info);
693 }
694 } else {
695 if (userDataObject instanceof CallerInfoToken) {
696 //temporary result, while query is running
697 info = ((CallerInfoToken) userDataObject).currentInfo;
698 } else {
699 //final query result
700 info = (CallerInfo) userDataObject;
701 }
702 if (info == null) {
703 // No URI, or Existing CallerInfo, so we'll have to make do with
704 // querying a new CallerInfo using the connection's phone number.
705 String number = c.getAddress();
706
707 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
708
709 if (!TextUtils.isEmpty(number)) {
710 info = CallerInfo.getCallerInfo(context, number);
711 if (info != null) {
712 c.setUserData(info);
713 }
714 }
715 }
716 }
717 }
718 return info;
719 }
720
721 /**
722 * Class returned by the startGetCallerInfo call to package a temporary
723 * CallerInfo Object, to be superceded by the CallerInfo Object passed
724 * into the listener when the query with token mAsyncQueryToken is complete.
725 */
726 public static class CallerInfoToken {
727 /**indicates that there will no longer be updates to this request.*/
728 public boolean isFinal;
729
730 public CallerInfo currentInfo;
731 public CallerInfoAsyncQuery asyncQuery;
732 }
733
734 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700735 * place a temporary callerinfo object in the hands of the caller and notify
736 * caller when the actual query is done.
737 */
738 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -0700739 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
740 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700741 CallerInfoToken cit;
742
743 if (c == null) {
744 //TODO: perhaps throw an exception here.
745 cit = new CallerInfoToken();
746 cit.asyncQuery = null;
747 return cit;
748 }
749
750 Object userDataObject = c.getUserData();
751
752 // There are now 3 states for the Connection's userData object:
753 //
754 // (1) Uri - query has not been executed yet
755 //
756 // (2) CallerInfoToken - query is executing, but has not completed.
757 //
758 // (3) CallerInfo - query has executed.
759 //
760 // In each case we have slightly different behaviour:
761 // 1. If the query has not been executed yet (Uri or null), we start
762 // query execution asynchronously, and note it by attaching a
763 // CallerInfoToken as the userData.
764 // 2. If the query is executing (CallerInfoToken), we've essentially
765 // reached a state where we've received multiple requests for the
766 // same callerInfo. That means that once the query is complete,
767 // we'll need to execute the additional listener requested.
768 // 3. If the query has already been executed (CallerInfo), we just
769 // return the CallerInfo object as expected.
770 // 4. Regarding isFinal - there are cases where the CallerInfo object
771 // will not be attached, like when the number is empty (caller id
772 // blocking). This flag is used to indicate that the
773 // CallerInfoToken object is going to be permanent since no
774 // query results will be returned. In the case where a query
775 // has been completed, this flag is used to indicate to the caller
776 // that the data will not be updated since it is valid.
777 //
778 // Note: For the case where a number is NOT retrievable, we leave
779 // the CallerInfo as null in the CallerInfoToken. This is
780 // something of a departure from the original code, since the old
781 // code manufactured a CallerInfo object regardless of the query
782 // outcome. From now on, we will append an empty CallerInfo
783 // object, to mirror previous behaviour, and to avoid Null Pointer
784 // Exceptions.
785
786 if (userDataObject instanceof Uri) {
787 // State (1): query has not been executed yet
788
789 //create a dummy callerinfo, populate with what we know from URI.
790 cit = new CallerInfoToken();
791 cit.currentInfo = new CallerInfo();
792 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
793 (Uri) userDataObject, sCallerInfoQueryListener, c);
794 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
795 cit.isFinal = false;
796
797 c.setUserData(cit);
798
799 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
800
801 } else if (userDataObject == null) {
802 // No URI, or Existing CallerInfo, so we'll have to make do with
803 // querying a new CallerInfo using the connection's phone number.
804 String number = c.getAddress();
805
Chiao Cheng685dcb62013-10-02 11:51:06 -0700806 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -0700807 // Gateway number, the connection number is actually the gateway number.
808 // need to lookup via dialed number.
809 number = info.trueNumber;
810 }
811
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700812 if (DBG) {
813 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
814 log("- number (address): " + toLogSafePhoneNumber(number));
815 log("- c: " + c);
816 log("- phone: " + c.getCall().getPhone());
817 int phoneType = c.getCall().getPhone().getPhoneType();
818 log("- phoneType: " + phoneType);
819 switch (phoneType) {
820 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
821 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -0700822 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700823 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
824 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700825 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
826 log(" ==> PHONE_TYPE_THIRD_PARTY");
827 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700828 default: log(" ==> Unknown phone type"); break;
829 }
830 }
831
832 cit = new CallerInfoToken();
833 cit.currentInfo = new CallerInfo();
834
835 // Store CNAP information retrieved from the Connection (we want to do this
836 // here regardless of whether the number is empty or not).
837 cit.currentInfo.cnapName = c.getCnapName();
Chen Xu0437d992019-09-07 19:04:31 -0700838 cit.currentInfo.setName(cit.currentInfo.cnapName); // This can still get overwritten
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700839 // by ContactInfo later
840 cit.currentInfo.numberPresentation = c.getNumberPresentation();
841 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
842
843 if (VDBG) {
844 log("startGetCallerInfo: number = " + number);
845 log("startGetCallerInfo: CNAP Info from FW(1): name="
846 + cit.currentInfo.cnapName
847 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
848 }
849
850 // handling case where number is null (caller id hidden) as well.
851 if (!TextUtils.isEmpty(number)) {
852 // Check for special CNAP cases and modify the CallerInfo accordingly
853 // to be sure we keep the right information to display/log later
854 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
855 cit.currentInfo.numberPresentation);
856
Chen Xu0437d992019-09-07 19:04:31 -0700857 cit.currentInfo.setPhoneNumber(number);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700858 // For scenarios where we may receive a valid number from the network but a
859 // restricted/unavailable presentation, we do not want to perform a contact query
860 // (see note on isFinal above). So we set isFinal to true here as well.
861 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
862 cit.isFinal = true;
863 } else {
864 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
865 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
866 number, sCallerInfoQueryListener, c);
867 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
868 cit.isFinal = false;
869 }
870 } else {
871 // This is the case where we are querying on a number that
872 // is null or empty, like a caller whose caller id is
873 // blocked or empty (CLIR). The previous behaviour was to
874 // throw a null CallerInfo object back to the user, but
875 // this departure is somewhat cleaner.
876 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
877 cit.isFinal = true; // please see note on isFinal, above.
878 }
879
880 c.setUserData(cit);
881
882 if (DBG) {
883 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
884 }
885
886 } else if (userDataObject instanceof CallerInfoToken) {
887 // State (2): query is executing, but has not completed.
888
889 // just tack on this listener to the queue.
890 cit = (CallerInfoToken) userDataObject;
891
892 // handling case where number is null (caller id hidden) as well.
893 if (cit.asyncQuery != null) {
894 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
895
896 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
897 listener.getClass().toString());
898 } else {
899 // handling case where number/name gets updated later on by the network
900 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -0700901
902 if (info != null) {
903 // Gateway number, the connection number is actually the gateway number.
904 // need to lookup via dialed number.
905 updatedNumber = info.trueNumber;
906 }
907
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700908 if (DBG) {
909 log("startGetCallerInfo: updatedNumber initially = "
910 + toLogSafePhoneNumber(updatedNumber));
911 }
912 if (!TextUtils.isEmpty(updatedNumber)) {
913 // Store CNAP information retrieved from the Connection
914 cit.currentInfo.cnapName = c.getCnapName();
915 // This can still get overwritten by ContactInfo
Chen Xu0437d992019-09-07 19:04:31 -0700916 cit.currentInfo.setName(cit.currentInfo.cnapName);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700917 cit.currentInfo.numberPresentation = c.getNumberPresentation();
918 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
919
920 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
921 updatedNumber, cit.currentInfo.numberPresentation);
922
Chen Xu0437d992019-09-07 19:04:31 -0700923 cit.currentInfo.setPhoneNumber(updatedNumber);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700924 if (DBG) {
925 log("startGetCallerInfo: updatedNumber="
926 + toLogSafePhoneNumber(updatedNumber));
927 }
928 if (VDBG) {
929 log("startGetCallerInfo: CNAP Info from FW(2): name="
930 + cit.currentInfo.cnapName
931 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
932 } else if (DBG) {
933 log("startGetCallerInfo: CNAP Info from FW(2)");
934 }
935 // For scenarios where we may receive a valid number from the network but a
936 // restricted/unavailable presentation, we do not want to perform a contact query
937 // (see note on isFinal above). So we set isFinal to true here as well.
938 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
939 cit.isFinal = true;
940 } else {
941 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
942 updatedNumber, sCallerInfoQueryListener, c);
943 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
944 cit.isFinal = false;
945 }
946 } else {
947 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
948 if (cit.currentInfo == null) {
949 cit.currentInfo = new CallerInfo();
950 }
951 // Store CNAP information retrieved from the Connection
952 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
953 // overwritten by ContactInfo
Chen Xu0437d992019-09-07 19:04:31 -0700954 cit.currentInfo.setName(cit.currentInfo.cnapName);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700955 cit.currentInfo.numberPresentation = c.getNumberPresentation();
956 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
957
958 if (VDBG) {
959 log("startGetCallerInfo: CNAP Info from FW(3): name="
960 + cit.currentInfo.cnapName
961 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
962 } else if (DBG) {
963 log("startGetCallerInfo: CNAP Info from FW(3)");
964 }
965 cit.isFinal = true; // please see note on isFinal, above.
966 }
967 }
968 } else {
969 // State (3): query is complete.
970
971 // The connection's userDataObject is a full-fledged
972 // CallerInfo instance. Wrap it in a CallerInfoToken and
973 // return it to the user.
974
975 cit = new CallerInfoToken();
976 cit.currentInfo = (CallerInfo) userDataObject;
977 cit.asyncQuery = null;
978 cit.isFinal = true;
979 // since the query is already done, call the listener.
980 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
981 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
982 }
983 return cit;
984 }
985
986 /**
987 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
988 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
989 */
990 private static final int QUERY_TOKEN = -1;
991 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
992 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
993 /**
994 * When the query completes, we stash the resulting CallerInfo
995 * object away in the Connection's "userData" (where it will
996 * later be retrieved by the in-call UI.)
997 */
998 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
999 if (DBG) log("query complete, updating connection.userdata");
1000 Connection conn = (Connection) cookie;
1001
1002 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1003 // If no ContactInfo, then we want to use CNAP information coming from network
1004 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1005 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1006 // If the number presentation has not been set by
1007 // the ContactInfo, use the one from the
1008 // connection.
1009
1010 // TODO: Need a new util method to merge the info
1011 // from the Connection in a CallerInfo object.
1012 // Here 'ci' is a new CallerInfo instance read
1013 // from the DB. It has lost all the connection
1014 // info preset before the query (see PhoneUtils
1015 // line 1334). We should have a method to merge
1016 // back into this new instance the info from the
1017 // connection object not set by the DB. If the
1018 // Connection already has a CallerInfo instance in
1019 // userData, then we could use this instance to
1020 // fill 'ci' in. The same routine could be used in
1021 // PhoneUtils.
1022 if (0 == ci.numberPresentation) {
1023 ci.numberPresentation = conn.getNumberPresentation();
1024 }
1025 } else {
1026 // No matching contact was found for this number.
1027 // Return a new CallerInfo based solely on the CNAP
1028 // information from the network.
1029
1030 CallerInfo newCi = getCallerInfo(null, conn);
1031
1032 // ...but copy over the (few) things we care about
1033 // from the original CallerInfo object:
1034 if (newCi != null) {
Chen Xu0437d992019-09-07 19:04:31 -07001035 newCi.setPhoneNumber(ci.getPhoneNumber()); // To get formatted phone number
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001036 newCi.geoDescription = ci.geoDescription; // To get geo description string
1037 ci = newCi;
1038 }
1039 }
1040
1041 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1042 conn.setUserData(ci);
1043 }
1044 };
1045
1046
1047 /**
1048 * Returns a single "name" for the specified given a CallerInfo object.
1049 * If the name is null, return defaultString as the default value, usually
1050 * context.getString(R.string.unknown).
1051 */
1052 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1053 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1054
1055 String compactName = null;
1056 if (ci != null) {
Chen Xu0437d992019-09-07 19:04:31 -07001057 if (TextUtils.isEmpty(ci.getName())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001058 // Perform any modifications for special CNAP cases to
1059 // the phone number being displayed, if applicable.
Chen Xu0437d992019-09-07 19:04:31 -07001060 compactName = modifyForSpecialCnapCases(context, ci, ci.getPhoneNumber(),
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001061 ci.numberPresentation);
1062 } else {
1063 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
Chen Xu0437d992019-09-07 19:04:31 -07001064 compactName = ci.getName();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001065 }
1066 }
1067
1068 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1069 // If we're still null/empty here, then check if we have a presentation
1070 // string that takes precedence that we could return, otherwise display
1071 // "unknown" string.
1072 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1073 compactName = context.getString(R.string.private_num);
1074 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1075 compactName = context.getString(R.string.payphone);
1076 } else {
1077 compactName = context.getString(R.string.unknown);
1078 }
1079 }
1080 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1081 return compactName;
1082 }
1083
Tyler Gunna1abb582018-09-14 16:12:01 -07001084 static boolean isInEmergencyCall(CallManager cm) {
1085 Call fgCall = cm.getActiveFgCall();
1086 // isIdle includes checks for the DISCONNECTING/DISCONNECTED state.
1087 if(!fgCall.isIdle()) {
1088 for (Connection cn : fgCall.getConnections()) {
1089 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
1090 cn.getAddress())) {
1091 return true;
1092 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001093 }
1094 }
1095 return false;
1096 }
1097
1098 //
1099 // Misc UI policy helper functions
1100 //
1101
1102 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001103 * Based on the input CNAP number string,
1104 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1105 * Otherwise, return CNAP_SPECIAL_CASE_NO.
1106 */
1107 private static int checkCnapSpecialCases(String n) {
1108 if (n.equals("PRIVATE") ||
1109 n.equals("P") ||
1110 n.equals("RES")) {
1111 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1112 return PhoneConstants.PRESENTATION_RESTRICTED;
1113 } else if (n.equals("UNAVAILABLE") ||
1114 n.equals("UNKNOWN") ||
1115 n.equals("UNA") ||
1116 n.equals("U")) {
1117 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1118 return PhoneConstants.PRESENTATION_UNKNOWN;
1119 } else {
1120 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1121 return CNAP_SPECIAL_CASE_NO;
1122 }
1123 }
1124
1125 /**
1126 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
1127 * from the network to indicate different number presentations, convert them to
1128 * expected number and presentation values within the CallerInfo object.
1129 * @param number number we use to verify if we are in a corner case
1130 * @param presentation presentation value used to verify if we are in a corner case
1131 * @return the new String that should be used for the phone number
1132 */
1133 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
1134 String number, int presentation) {
1135 // Obviously we return number if ci == null, but still return number if
1136 // number == null, because in these cases the correct string will still be
1137 // displayed/logged after this function returns based on the presentation value.
1138 if (ci == null || number == null) return number;
1139
1140 if (DBG) {
1141 log("modifyForSpecialCnapCases: initially, number="
1142 + toLogSafePhoneNumber(number)
1143 + ", presentation=" + presentation + " ci " + ci);
1144 }
1145
1146 // "ABSENT NUMBER" is a possible value we could get from the network as the
1147 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
1148 // and fix the presentation to be the same.
1149 final String[] absentNumberValues =
1150 context.getResources().getStringArray(R.array.absent_num);
1151 if (Arrays.asList(absentNumberValues).contains(number)
1152 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
1153 number = context.getString(R.string.unknown);
1154 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
1155 }
1156
1157 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
1158 // cases only apply if we received an allowed presentation from the network, so check
1159 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
1160 // match the presentation passed in for verification (meaning we changed it previously
1161 // because it's a corner case and we're being called from a different entry point).
1162 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
1163 || (ci.numberPresentation != presentation
1164 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
1165 int cnapSpecialCase = checkCnapSpecialCases(number);
1166 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
1167 // For all special strings, change number & numberPresentation.
1168 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
1169 number = context.getString(R.string.private_num);
1170 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
1171 number = context.getString(R.string.unknown);
1172 }
1173 if (DBG) {
1174 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
1175 + "; presentation now=" + cnapSpecialCase);
1176 }
1177 ci.numberPresentation = cnapSpecialCase;
1178 }
1179 }
1180 if (DBG) {
1181 log("modifyForSpecialCnapCases: returning number string="
1182 + toLogSafePhoneNumber(number));
1183 }
1184 return number;
1185 }
1186
1187 //
1188 // Support for 3rd party phone service providers.
1189 //
1190
1191 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001192 * Check if a phone number can be route through a 3rd party
1193 * gateway. The number must be a global phone number in numerical
1194 * form (1-800-666-SEXY won't work).
1195 *
1196 * MMI codes and the like cannot be used as a dial number for the
1197 * gateway either.
1198 *
1199 * @param number To be dialed via a 3rd party gateway.
1200 * @return true If the number can be routed through the 3rd party network.
1201 */
Santos Cordon69a69192013-08-22 14:25:42 -07001202 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001203 if (TextUtils.isEmpty(number)) {
1204 return false;
1205 }
1206 number = PhoneNumberUtils.stripSeparators(number);
1207 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
1208 return false;
1209 }
1210 number = PhoneNumberUtils.extractNetworkPortion(number);
1211 return PhoneNumberUtils.isGlobalPhoneNumber(number);
1212 }
1213
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001214 /**
1215 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
1216 */
1217 /* package */ static boolean isPhoneInEcm(Phone phone) {
1218 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
Shuo Qiandd210312017-04-12 22:11:33 +00001219 return phone.isInEcm();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001220 }
1221 return false;
1222 }
1223
1224 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001225 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
1226 * meaning the call is the first real incoming call the phone is having.
1227 */
1228 public static boolean isRealIncomingCall(Call.State state) {
1229 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
1230 }
1231
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001232 //
1233 // General phone and call state debugging/testing code
1234 //
1235
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001236 private static void log(String msg) {
1237 Log.d(LOG_TAG, msg);
1238 }
1239
Nancy Chene53a0642015-03-12 11:20:12 -07001240 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
1241 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
1242 }
1243
Nancy Chen32031f42015-03-04 21:00:07 -08001244 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
1245 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
1246 }
1247
Andrew Leed5165b02014-12-05 15:53:58 -08001248 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
1249 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
1250 }
1251
1252 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1253 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08001254 // TODO: Should use some sort of special hidden flag to decorate this account as
1255 // an emergency-only account
Brad Ebingerd3edc222016-03-23 19:44:38 -07001256 String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
Brad Ebinger4fe48112016-04-13 11:21:53 -07001257 String.valueOf(phone.getFullIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07001258 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
1259 }
1260
1261 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1262 String id, String prefix, boolean isEmergency) {
1263 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08001264 return new PhoneAccountHandle(pstnConnectionServiceName, id);
1265 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08001266
Santos Cordonf69df962015-02-03 11:15:19 -08001267 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08001268 if (phoneAccount != null
1269 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
1270 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
1271 }
1272 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1273 }
1274
1275 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001276 Phone phone = getPhoneForPhoneAccountHandle(handle);
1277 if (phone != null) {
1278 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08001279 }
1280 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1281 }
1282
Ta-wei Yen845f6992016-06-16 12:53:46 -07001283 public static Phone getPhoneForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001284 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
1285 return getPhoneFromIccId(handle.getId());
1286 }
1287 return null;
1288 }
1289
Nancy Chene53a0642015-03-12 11:20:12 -07001290 /**
1291 * Determine if a given phone account corresponds to an active SIM
1292 *
1293 * @param sm An instance of the subscription manager so it is not recreated for each calling of
1294 * this method.
1295 * @param handle The handle for the phone account to check
1296 * @return {@code true} If there is an active SIM for this phone account,
1297 * {@code false} otherwise.
1298 */
1299 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
1300 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
1301 }
1302
Santos Cordonf69df962015-02-03 11:15:19 -08001303 private static ComponentName getPstnConnectionServiceName() {
Tony Mak4c8f3c62015-12-07 02:30:37 +00001304 return PSTN_CONNECTION_SERVICE_COMPONENT;
Santos Cordonf69df962015-02-03 11:15:19 -08001305 }
1306
Santos Cordon80855d52015-02-10 04:33:36 -08001307 private static Phone getPhoneFromIccId(String iccId) {
1308 if (!TextUtils.isEmpty(iccId)) {
1309 for (Phone phone : PhoneFactory.getPhones()) {
Brad Ebinger4fe48112016-04-13 11:21:53 -07001310 String phoneIccId = phone.getFullIccSerialNumber();
Santos Cordon80855d52015-02-10 04:33:36 -08001311 if (iccId.equals(phoneIccId)) {
1312 return phone;
1313 }
1314 }
1315 }
Santos Cordon80855d52015-02-10 04:33:36 -08001316 return null;
1317 }
1318
Stuart Scottdcf40a92014-12-09 10:45:01 -08001319 /**
1320 * Register ICC status for all phones.
1321 */
1322 static final void registerIccStatus(Handler handler, int event) {
1323 for (Phone phone : PhoneFactory.getPhones()) {
1324 IccCard sim = phone.getIccCard();
1325 if (sim != null) {
1326 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
1327 sim.registerForNetworkLocked(handler, event, phone);
1328 }
1329 }
1330 }
1331
1332 /**
Amit Mahajanf5d92c82018-11-02 17:44:40 -07001333 * Register ICC status for all phones.
1334 */
1335 static final void registerIccStatus(Handler handler, int event, int phoneId) {
1336 Phone[] phones = PhoneFactory.getPhones();
1337 IccCard sim = phones[phoneId].getIccCard();
1338 if (sim != null) {
1339 if (VDBG) {
1340 Log.v(LOG_TAG, "register for ICC status, phone " + phones[phoneId].getPhoneId());
1341 }
1342 sim.registerForNetworkLocked(handler, event, phones[phoneId]);
1343 }
1344 }
1345
1346 /**
1347 * Unregister ICC status for a specific phone.
1348 */
1349 static final void unregisterIccStatus(Handler handler, int phoneId) {
1350 Phone[] phones = PhoneFactory.getPhones();
1351 IccCard sim = phones[phoneId].getIccCard();
1352 if (sim != null) {
1353 if (VDBG) {
1354 Log.v(LOG_TAG, "unregister for ICC status, phone " + phones[phoneId].getPhoneId());
1355 }
1356 sim.unregisterForNetworkLocked(handler);
1357 }
1358 }
1359
1360 /**
Stuart Scottdcf40a92014-12-09 10:45:01 -08001361 * Set the radio power on/off state for all phones.
1362 *
1363 * @param enabled true means on, false means off.
1364 */
1365 static final void setRadioPower(boolean enabled) {
1366 for (Phone phone : PhoneFactory.getPhones()) {
1367 phone.setRadioPower(enabled);
1368 }
1369 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001370}