blob: d3f780f7ec858012d06762773dd937bd875c64e0 [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)) {
432 createUssdDialog(app, context, text,
433 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) {
SongFerngWangdfa107a2018-10-29 20:31:58 +0800447 createUssdDialog(app, context, text,
448 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
SongFerngWangdfa107a2018-10-29 20:31:58 +0800562 private static void createUssdDialog(PhoneGlobals app, Context context, CharSequence text,
563 int windowType) {
564 log("displayMMIComplete: MMI code has finished running.");
565
566 log("displayMMIComplete: Extended NW displayMMIInitiate (" + text + ")");
567 if (text == null || text.length() == 0) {
568 return;
569 }
570
571 // displaying system alert dialog on the screen instead of
572 // using another activity to display the message. This
573 // places the message at the forefront of the UI.
574
575 if (sUssdDialog == null) {
576 sUssdDialog = new AlertDialog.Builder(context, THEME)
577 .setPositiveButton(R.string.ok, null)
578 .setCancelable(true)
579 .setOnDismissListener(new DialogInterface.OnDismissListener() {
580 @Override
581 public void onDismiss(DialogInterface dialog) {
582 sUssdMsg.setLength(0);
583 }
584 })
585 .create();
586
587 sUssdDialog.getWindow().setType(windowType);
588 sUssdDialog.getWindow().addFlags(
589 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
590 }
591 if (sUssdMsg.length() != 0) {
592 sUssdMsg
593 .insert(0, "\n")
594 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
595 .insert(0, "\n");
596 }
597 sUssdMsg.insert(0, text);
598 sUssdDialog.setMessage(sUssdMsg.toString());
599 sUssdDialog.show();
600 }
601
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700602 /**
603 * Cancels the current pending MMI operation, if applicable.
604 * @return true if we canceled an MMI operation, or false
605 * if the current pending MMI wasn't cancelable
606 * or if there was no current pending MMI at all.
607 *
608 * @see displayMMIInitiate
609 */
610 static boolean cancelMmiCode(Phone phone) {
611 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
612 int count = pendingMmis.size();
613 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
614
615 boolean canceled = false;
616 if (count > 0) {
617 // assume that we only have one pending MMI operation active at a time.
618 // I don't think it's possible to enter multiple MMI codes concurrently
619 // in the phone UI, because during the MMI operation, an Alert panel
620 // is displayed, which prevents more MMI code from being entered.
621 MmiCode mmiCode = pendingMmis.get(0);
622 if (mmiCode.isCancelable()) {
623 mmiCode.cancel();
624 canceled = true;
625 }
626 }
627 return canceled;
628 }
629
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700630 /**
631 * Returns the caller-id info corresponding to the specified Connection.
632 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
633 * extract a phone number from the specified Connection, and feed that
634 * number into CallerInfo.getCallerInfo().)
635 *
636 * The returned CallerInfo may be null in certain error cases, like if the
637 * specified Connection was null, or if we weren't able to get a valid
638 * phone number from the Connection.
639 *
640 * Finally, if the getCallerInfo() call did succeed, we save the resulting
641 * CallerInfo object in the "userData" field of the Connection.
642 *
643 * NOTE: This API should be avoided, with preference given to the
644 * asynchronous startGetCallerInfo API.
645 */
646 static CallerInfo getCallerInfo(Context context, Connection c) {
647 CallerInfo info = null;
648
649 if (c != null) {
650 //See if there is a URI attached. If there is, this means
651 //that there is no CallerInfo queried yet, so we'll need to
652 //replace the URI with a full CallerInfo object.
653 Object userDataObject = c.getUserData();
654 if (userDataObject instanceof Uri) {
655 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
656 if (info != null) {
657 c.setUserData(info);
658 }
659 } else {
660 if (userDataObject instanceof CallerInfoToken) {
661 //temporary result, while query is running
662 info = ((CallerInfoToken) userDataObject).currentInfo;
663 } else {
664 //final query result
665 info = (CallerInfo) userDataObject;
666 }
667 if (info == null) {
668 // No URI, or Existing CallerInfo, so we'll have to make do with
669 // querying a new CallerInfo using the connection's phone number.
670 String number = c.getAddress();
671
672 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
673
674 if (!TextUtils.isEmpty(number)) {
675 info = CallerInfo.getCallerInfo(context, number);
676 if (info != null) {
677 c.setUserData(info);
678 }
679 }
680 }
681 }
682 }
683 return info;
684 }
685
686 /**
687 * Class returned by the startGetCallerInfo call to package a temporary
688 * CallerInfo Object, to be superceded by the CallerInfo Object passed
689 * into the listener when the query with token mAsyncQueryToken is complete.
690 */
691 public static class CallerInfoToken {
692 /**indicates that there will no longer be updates to this request.*/
693 public boolean isFinal;
694
695 public CallerInfo currentInfo;
696 public CallerInfoAsyncQuery asyncQuery;
697 }
698
699 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700700 * place a temporary callerinfo object in the hands of the caller and notify
701 * caller when the actual query is done.
702 */
703 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -0700704 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
705 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700706 CallerInfoToken cit;
707
708 if (c == null) {
709 //TODO: perhaps throw an exception here.
710 cit = new CallerInfoToken();
711 cit.asyncQuery = null;
712 return cit;
713 }
714
715 Object userDataObject = c.getUserData();
716
717 // There are now 3 states for the Connection's userData object:
718 //
719 // (1) Uri - query has not been executed yet
720 //
721 // (2) CallerInfoToken - query is executing, but has not completed.
722 //
723 // (3) CallerInfo - query has executed.
724 //
725 // In each case we have slightly different behaviour:
726 // 1. If the query has not been executed yet (Uri or null), we start
727 // query execution asynchronously, and note it by attaching a
728 // CallerInfoToken as the userData.
729 // 2. If the query is executing (CallerInfoToken), we've essentially
730 // reached a state where we've received multiple requests for the
731 // same callerInfo. That means that once the query is complete,
732 // we'll need to execute the additional listener requested.
733 // 3. If the query has already been executed (CallerInfo), we just
734 // return the CallerInfo object as expected.
735 // 4. Regarding isFinal - there are cases where the CallerInfo object
736 // will not be attached, like when the number is empty (caller id
737 // blocking). This flag is used to indicate that the
738 // CallerInfoToken object is going to be permanent since no
739 // query results will be returned. In the case where a query
740 // has been completed, this flag is used to indicate to the caller
741 // that the data will not be updated since it is valid.
742 //
743 // Note: For the case where a number is NOT retrievable, we leave
744 // the CallerInfo as null in the CallerInfoToken. This is
745 // something of a departure from the original code, since the old
746 // code manufactured a CallerInfo object regardless of the query
747 // outcome. From now on, we will append an empty CallerInfo
748 // object, to mirror previous behaviour, and to avoid Null Pointer
749 // Exceptions.
750
751 if (userDataObject instanceof Uri) {
752 // State (1): query has not been executed yet
753
754 //create a dummy callerinfo, populate with what we know from URI.
755 cit = new CallerInfoToken();
756 cit.currentInfo = new CallerInfo();
757 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
758 (Uri) userDataObject, sCallerInfoQueryListener, c);
759 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
760 cit.isFinal = false;
761
762 c.setUserData(cit);
763
764 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
765
766 } else if (userDataObject == null) {
767 // No URI, or Existing CallerInfo, so we'll have to make do with
768 // querying a new CallerInfo using the connection's phone number.
769 String number = c.getAddress();
770
Chiao Cheng685dcb62013-10-02 11:51:06 -0700771 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -0700772 // Gateway number, the connection number is actually the gateway number.
773 // need to lookup via dialed number.
774 number = info.trueNumber;
775 }
776
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700777 if (DBG) {
778 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
779 log("- number (address): " + toLogSafePhoneNumber(number));
780 log("- c: " + c);
781 log("- phone: " + c.getCall().getPhone());
782 int phoneType = c.getCall().getPhone().getPhoneType();
783 log("- phoneType: " + phoneType);
784 switch (phoneType) {
785 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
786 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -0700787 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700788 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
789 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700790 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
791 log(" ==> PHONE_TYPE_THIRD_PARTY");
792 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700793 default: log(" ==> Unknown phone type"); break;
794 }
795 }
796
797 cit = new CallerInfoToken();
798 cit.currentInfo = new CallerInfo();
799
800 // Store CNAP information retrieved from the Connection (we want to do this
801 // here regardless of whether the number is empty or not).
802 cit.currentInfo.cnapName = c.getCnapName();
803 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
804 // by ContactInfo later
805 cit.currentInfo.numberPresentation = c.getNumberPresentation();
806 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
807
808 if (VDBG) {
809 log("startGetCallerInfo: number = " + number);
810 log("startGetCallerInfo: CNAP Info from FW(1): name="
811 + cit.currentInfo.cnapName
812 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
813 }
814
815 // handling case where number is null (caller id hidden) as well.
816 if (!TextUtils.isEmpty(number)) {
817 // Check for special CNAP cases and modify the CallerInfo accordingly
818 // to be sure we keep the right information to display/log later
819 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
820 cit.currentInfo.numberPresentation);
821
822 cit.currentInfo.phoneNumber = number;
823 // For scenarios where we may receive a valid number from the network but a
824 // restricted/unavailable presentation, we do not want to perform a contact query
825 // (see note on isFinal above). So we set isFinal to true here as well.
826 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
827 cit.isFinal = true;
828 } else {
829 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
830 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
831 number, sCallerInfoQueryListener, c);
832 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
833 cit.isFinal = false;
834 }
835 } else {
836 // This is the case where we are querying on a number that
837 // is null or empty, like a caller whose caller id is
838 // blocked or empty (CLIR). The previous behaviour was to
839 // throw a null CallerInfo object back to the user, but
840 // this departure is somewhat cleaner.
841 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
842 cit.isFinal = true; // please see note on isFinal, above.
843 }
844
845 c.setUserData(cit);
846
847 if (DBG) {
848 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
849 }
850
851 } else if (userDataObject instanceof CallerInfoToken) {
852 // State (2): query is executing, but has not completed.
853
854 // just tack on this listener to the queue.
855 cit = (CallerInfoToken) userDataObject;
856
857 // handling case where number is null (caller id hidden) as well.
858 if (cit.asyncQuery != null) {
859 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
860
861 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
862 listener.getClass().toString());
863 } else {
864 // handling case where number/name gets updated later on by the network
865 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -0700866
867 if (info != null) {
868 // Gateway number, the connection number is actually the gateway number.
869 // need to lookup via dialed number.
870 updatedNumber = info.trueNumber;
871 }
872
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700873 if (DBG) {
874 log("startGetCallerInfo: updatedNumber initially = "
875 + toLogSafePhoneNumber(updatedNumber));
876 }
877 if (!TextUtils.isEmpty(updatedNumber)) {
878 // Store CNAP information retrieved from the Connection
879 cit.currentInfo.cnapName = c.getCnapName();
880 // This can still get overwritten by ContactInfo
881 cit.currentInfo.name = cit.currentInfo.cnapName;
882 cit.currentInfo.numberPresentation = c.getNumberPresentation();
883 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
884
885 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
886 updatedNumber, cit.currentInfo.numberPresentation);
887
888 cit.currentInfo.phoneNumber = updatedNumber;
889 if (DBG) {
890 log("startGetCallerInfo: updatedNumber="
891 + toLogSafePhoneNumber(updatedNumber));
892 }
893 if (VDBG) {
894 log("startGetCallerInfo: CNAP Info from FW(2): name="
895 + cit.currentInfo.cnapName
896 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
897 } else if (DBG) {
898 log("startGetCallerInfo: CNAP Info from FW(2)");
899 }
900 // For scenarios where we may receive a valid number from the network but a
901 // restricted/unavailable presentation, we do not want to perform a contact query
902 // (see note on isFinal above). So we set isFinal to true here as well.
903 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
904 cit.isFinal = true;
905 } else {
906 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
907 updatedNumber, sCallerInfoQueryListener, c);
908 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
909 cit.isFinal = false;
910 }
911 } else {
912 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
913 if (cit.currentInfo == null) {
914 cit.currentInfo = new CallerInfo();
915 }
916 // Store CNAP information retrieved from the Connection
917 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
918 // overwritten by ContactInfo
919 cit.currentInfo.name = cit.currentInfo.cnapName;
920 cit.currentInfo.numberPresentation = c.getNumberPresentation();
921 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
922
923 if (VDBG) {
924 log("startGetCallerInfo: CNAP Info from FW(3): name="
925 + cit.currentInfo.cnapName
926 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
927 } else if (DBG) {
928 log("startGetCallerInfo: CNAP Info from FW(3)");
929 }
930 cit.isFinal = true; // please see note on isFinal, above.
931 }
932 }
933 } else {
934 // State (3): query is complete.
935
936 // The connection's userDataObject is a full-fledged
937 // CallerInfo instance. Wrap it in a CallerInfoToken and
938 // return it to the user.
939
940 cit = new CallerInfoToken();
941 cit.currentInfo = (CallerInfo) userDataObject;
942 cit.asyncQuery = null;
943 cit.isFinal = true;
944 // since the query is already done, call the listener.
945 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
946 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
947 }
948 return cit;
949 }
950
951 /**
952 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
953 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
954 */
955 private static final int QUERY_TOKEN = -1;
956 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
957 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
958 /**
959 * When the query completes, we stash the resulting CallerInfo
960 * object away in the Connection's "userData" (where it will
961 * later be retrieved by the in-call UI.)
962 */
963 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
964 if (DBG) log("query complete, updating connection.userdata");
965 Connection conn = (Connection) cookie;
966
967 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
968 // If no ContactInfo, then we want to use CNAP information coming from network
969 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
970 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
971 // If the number presentation has not been set by
972 // the ContactInfo, use the one from the
973 // connection.
974
975 // TODO: Need a new util method to merge the info
976 // from the Connection in a CallerInfo object.
977 // Here 'ci' is a new CallerInfo instance read
978 // from the DB. It has lost all the connection
979 // info preset before the query (see PhoneUtils
980 // line 1334). We should have a method to merge
981 // back into this new instance the info from the
982 // connection object not set by the DB. If the
983 // Connection already has a CallerInfo instance in
984 // userData, then we could use this instance to
985 // fill 'ci' in. The same routine could be used in
986 // PhoneUtils.
987 if (0 == ci.numberPresentation) {
988 ci.numberPresentation = conn.getNumberPresentation();
989 }
990 } else {
991 // No matching contact was found for this number.
992 // Return a new CallerInfo based solely on the CNAP
993 // information from the network.
994
995 CallerInfo newCi = getCallerInfo(null, conn);
996
997 // ...but copy over the (few) things we care about
998 // from the original CallerInfo object:
999 if (newCi != null) {
1000 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1001 newCi.geoDescription = ci.geoDescription; // To get geo description string
1002 ci = newCi;
1003 }
1004 }
1005
1006 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1007 conn.setUserData(ci);
1008 }
1009 };
1010
1011
1012 /**
1013 * Returns a single "name" for the specified given a CallerInfo object.
1014 * If the name is null, return defaultString as the default value, usually
1015 * context.getString(R.string.unknown).
1016 */
1017 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1018 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1019
1020 String compactName = null;
1021 if (ci != null) {
1022 if (TextUtils.isEmpty(ci.name)) {
1023 // Perform any modifications for special CNAP cases to
1024 // the phone number being displayed, if applicable.
1025 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1026 ci.numberPresentation);
1027 } else {
1028 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1029 compactName = ci.name;
1030 }
1031 }
1032
1033 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1034 // If we're still null/empty here, then check if we have a presentation
1035 // string that takes precedence that we could return, otherwise display
1036 // "unknown" string.
1037 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1038 compactName = context.getString(R.string.private_num);
1039 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1040 compactName = context.getString(R.string.payphone);
1041 } else {
1042 compactName = context.getString(R.string.unknown);
1043 }
1044 }
1045 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1046 return compactName;
1047 }
1048
Tyler Gunna1abb582018-09-14 16:12:01 -07001049 static boolean isInEmergencyCall(CallManager cm) {
1050 Call fgCall = cm.getActiveFgCall();
1051 // isIdle includes checks for the DISCONNECTING/DISCONNECTED state.
1052 if(!fgCall.isIdle()) {
1053 for (Connection cn : fgCall.getConnections()) {
1054 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
1055 cn.getAddress())) {
1056 return true;
1057 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001058 }
1059 }
1060 return false;
1061 }
1062
1063 //
1064 // Misc UI policy helper functions
1065 //
1066
1067 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001068 * Based on the input CNAP number string,
1069 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1070 * Otherwise, return CNAP_SPECIAL_CASE_NO.
1071 */
1072 private static int checkCnapSpecialCases(String n) {
1073 if (n.equals("PRIVATE") ||
1074 n.equals("P") ||
1075 n.equals("RES")) {
1076 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1077 return PhoneConstants.PRESENTATION_RESTRICTED;
1078 } else if (n.equals("UNAVAILABLE") ||
1079 n.equals("UNKNOWN") ||
1080 n.equals("UNA") ||
1081 n.equals("U")) {
1082 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1083 return PhoneConstants.PRESENTATION_UNKNOWN;
1084 } else {
1085 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1086 return CNAP_SPECIAL_CASE_NO;
1087 }
1088 }
1089
1090 /**
1091 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
1092 * from the network to indicate different number presentations, convert them to
1093 * expected number and presentation values within the CallerInfo object.
1094 * @param number number we use to verify if we are in a corner case
1095 * @param presentation presentation value used to verify if we are in a corner case
1096 * @return the new String that should be used for the phone number
1097 */
1098 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
1099 String number, int presentation) {
1100 // Obviously we return number if ci == null, but still return number if
1101 // number == null, because in these cases the correct string will still be
1102 // displayed/logged after this function returns based on the presentation value.
1103 if (ci == null || number == null) return number;
1104
1105 if (DBG) {
1106 log("modifyForSpecialCnapCases: initially, number="
1107 + toLogSafePhoneNumber(number)
1108 + ", presentation=" + presentation + " ci " + ci);
1109 }
1110
1111 // "ABSENT NUMBER" is a possible value we could get from the network as the
1112 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
1113 // and fix the presentation to be the same.
1114 final String[] absentNumberValues =
1115 context.getResources().getStringArray(R.array.absent_num);
1116 if (Arrays.asList(absentNumberValues).contains(number)
1117 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
1118 number = context.getString(R.string.unknown);
1119 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
1120 }
1121
1122 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
1123 // cases only apply if we received an allowed presentation from the network, so check
1124 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
1125 // match the presentation passed in for verification (meaning we changed it previously
1126 // because it's a corner case and we're being called from a different entry point).
1127 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
1128 || (ci.numberPresentation != presentation
1129 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
1130 int cnapSpecialCase = checkCnapSpecialCases(number);
1131 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
1132 // For all special strings, change number & numberPresentation.
1133 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
1134 number = context.getString(R.string.private_num);
1135 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
1136 number = context.getString(R.string.unknown);
1137 }
1138 if (DBG) {
1139 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
1140 + "; presentation now=" + cnapSpecialCase);
1141 }
1142 ci.numberPresentation = cnapSpecialCase;
1143 }
1144 }
1145 if (DBG) {
1146 log("modifyForSpecialCnapCases: returning number string="
1147 + toLogSafePhoneNumber(number));
1148 }
1149 return number;
1150 }
1151
1152 //
1153 // Support for 3rd party phone service providers.
1154 //
1155
1156 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001157 * Check if a phone number can be route through a 3rd party
1158 * gateway. The number must be a global phone number in numerical
1159 * form (1-800-666-SEXY won't work).
1160 *
1161 * MMI codes and the like cannot be used as a dial number for the
1162 * gateway either.
1163 *
1164 * @param number To be dialed via a 3rd party gateway.
1165 * @return true If the number can be routed through the 3rd party network.
1166 */
Santos Cordon69a69192013-08-22 14:25:42 -07001167 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001168 if (TextUtils.isEmpty(number)) {
1169 return false;
1170 }
1171 number = PhoneNumberUtils.stripSeparators(number);
1172 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
1173 return false;
1174 }
1175 number = PhoneNumberUtils.extractNetworkPortion(number);
1176 return PhoneNumberUtils.isGlobalPhoneNumber(number);
1177 }
1178
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001179 /**
1180 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
1181 */
1182 /* package */ static boolean isPhoneInEcm(Phone phone) {
1183 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
Shuo Qiandd210312017-04-12 22:11:33 +00001184 return phone.isInEcm();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001185 }
1186 return false;
1187 }
1188
1189 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001190 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
1191 * meaning the call is the first real incoming call the phone is having.
1192 */
1193 public static boolean isRealIncomingCall(Call.State state) {
1194 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
1195 }
1196
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001197 //
1198 // General phone and call state debugging/testing code
1199 //
1200
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001201 private static void log(String msg) {
1202 Log.d(LOG_TAG, msg);
1203 }
1204
Nancy Chene53a0642015-03-12 11:20:12 -07001205 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
1206 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
1207 }
1208
Nancy Chen32031f42015-03-04 21:00:07 -08001209 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
1210 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
1211 }
1212
Andrew Leed5165b02014-12-05 15:53:58 -08001213 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
1214 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
1215 }
1216
1217 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1218 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08001219 // TODO: Should use some sort of special hidden flag to decorate this account as
1220 // an emergency-only account
Brad Ebingerd3edc222016-03-23 19:44:38 -07001221 String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
Brad Ebinger4fe48112016-04-13 11:21:53 -07001222 String.valueOf(phone.getFullIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07001223 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
1224 }
1225
1226 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1227 String id, String prefix, boolean isEmergency) {
1228 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08001229 return new PhoneAccountHandle(pstnConnectionServiceName, id);
1230 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08001231
Santos Cordonf69df962015-02-03 11:15:19 -08001232 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08001233 if (phoneAccount != null
1234 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
1235 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
1236 }
1237 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1238 }
1239
1240 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001241 Phone phone = getPhoneForPhoneAccountHandle(handle);
1242 if (phone != null) {
1243 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08001244 }
1245 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1246 }
1247
Ta-wei Yen845f6992016-06-16 12:53:46 -07001248 public static Phone getPhoneForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001249 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
1250 return getPhoneFromIccId(handle.getId());
1251 }
1252 return null;
1253 }
1254
Nancy Chene53a0642015-03-12 11:20:12 -07001255 /**
1256 * Determine if a given phone account corresponds to an active SIM
1257 *
1258 * @param sm An instance of the subscription manager so it is not recreated for each calling of
1259 * this method.
1260 * @param handle The handle for the phone account to check
1261 * @return {@code true} If there is an active SIM for this phone account,
1262 * {@code false} otherwise.
1263 */
1264 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
1265 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
1266 }
1267
Santos Cordonf69df962015-02-03 11:15:19 -08001268 private static ComponentName getPstnConnectionServiceName() {
Tony Mak4c8f3c62015-12-07 02:30:37 +00001269 return PSTN_CONNECTION_SERVICE_COMPONENT;
Santos Cordonf69df962015-02-03 11:15:19 -08001270 }
1271
Santos Cordon80855d52015-02-10 04:33:36 -08001272 private static Phone getPhoneFromIccId(String iccId) {
1273 if (!TextUtils.isEmpty(iccId)) {
1274 for (Phone phone : PhoneFactory.getPhones()) {
Brad Ebinger4fe48112016-04-13 11:21:53 -07001275 String phoneIccId = phone.getFullIccSerialNumber();
Santos Cordon80855d52015-02-10 04:33:36 -08001276 if (iccId.equals(phoneIccId)) {
1277 return phone;
1278 }
1279 }
1280 }
Santos Cordon80855d52015-02-10 04:33:36 -08001281 return null;
1282 }
1283
Stuart Scottdcf40a92014-12-09 10:45:01 -08001284 /**
1285 * Register ICC status for all phones.
1286 */
1287 static final void registerIccStatus(Handler handler, int event) {
1288 for (Phone phone : PhoneFactory.getPhones()) {
1289 IccCard sim = phone.getIccCard();
1290 if (sim != null) {
1291 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
1292 sim.registerForNetworkLocked(handler, event, phone);
1293 }
1294 }
1295 }
1296
1297 /**
Amit Mahajanf5d92c82018-11-02 17:44:40 -07001298 * Register ICC status for all phones.
1299 */
1300 static final void registerIccStatus(Handler handler, int event, int phoneId) {
1301 Phone[] phones = PhoneFactory.getPhones();
1302 IccCard sim = phones[phoneId].getIccCard();
1303 if (sim != null) {
1304 if (VDBG) {
1305 Log.v(LOG_TAG, "register for ICC status, phone " + phones[phoneId].getPhoneId());
1306 }
1307 sim.registerForNetworkLocked(handler, event, phones[phoneId]);
1308 }
1309 }
1310
1311 /**
1312 * Unregister ICC status for a specific phone.
1313 */
1314 static final void unregisterIccStatus(Handler handler, int phoneId) {
1315 Phone[] phones = PhoneFactory.getPhones();
1316 IccCard sim = phones[phoneId].getIccCard();
1317 if (sim != null) {
1318 if (VDBG) {
1319 Log.v(LOG_TAG, "unregister for ICC status, phone " + phones[phoneId].getPhoneId());
1320 }
1321 sim.unregisterForNetworkLocked(handler);
1322 }
1323 }
1324
1325 /**
Stuart Scottdcf40a92014-12-09 10:45:01 -08001326 * Set the radio power on/off state for all phones.
1327 *
1328 * @param enabled true means on, false means off.
1329 */
1330 static final void setRadioPower(boolean enabled) {
1331 for (Phone phone : PhoneFactory.getPhones()) {
1332 phone.setRadioPower(enabled);
1333 }
1334 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001335}