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