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