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