blob: 9ede914fb1d03e188d702c78c5a518f41bf00568 [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;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070022import android.content.ActivityNotFoundException;
Sailesh Nepalbfb68322013-11-07 14:07:41 -080023import android.content.ComponentName;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070024import android.content.Context;
25import android.content.DialogInterface;
26import android.content.Intent;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070027import android.content.res.Configuration;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070028import android.media.AudioManager;
29import android.net.Uri;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070030import android.os.Handler;
31import android.os.Message;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070032import android.telecom.PhoneAccount;
Andrew Leed5165b02014-12-05 15:53:58 -080033import android.telecom.PhoneAccountHandle;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070034import android.telecom.VideoProfile;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070035import android.telephony.PhoneNumberUtils;
Santos Cordonf69df962015-02-03 11:15:19 -080036import android.telephony.SubscriptionManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070037import android.text.TextUtils;
38import android.util.Log;
Andrew Leeb3ee4dc2015-01-23 17:35:00 -080039import android.view.ContextThemeWrapper;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070040import android.view.KeyEvent;
41import android.view.LayoutInflater;
42import android.view.View;
43import android.view.WindowManager;
44import android.widget.EditText;
45import android.widget.Toast;
46
47import com.android.internal.telephony.Call;
48import com.android.internal.telephony.CallManager;
49import com.android.internal.telephony.CallStateException;
50import com.android.internal.telephony.CallerInfo;
51import com.android.internal.telephony.CallerInfoAsyncQuery;
52import com.android.internal.telephony.Connection;
Stuart Scottdcf40a92014-12-09 10:45:01 -080053import com.android.internal.telephony.IccCard;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070054import com.android.internal.telephony.MmiCode;
55import com.android.internal.telephony.Phone;
56import com.android.internal.telephony.PhoneConstants;
Stuart Scottdcf40a92014-12-09 10:45:01 -080057import com.android.internal.telephony.PhoneFactory;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070058import com.android.internal.telephony.TelephonyCapabilities;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070059import com.android.internal.telephony.sip.SipPhone;
Santos Cordon69a69192013-08-22 14:25:42 -070060import com.android.phone.CallGatewayManager.RawGatewayInfo;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070061
Santos Cordon7d4ddf62013-07-10 11:58:08 -070062import java.util.Arrays;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070063import java.util.List;
64
65/**
66 * Misc utilities for the Phone app.
67 */
68public class PhoneUtils {
Brad Ebingerd3edc222016-03-23 19:44:38 -070069 public static final String EMERGENCY_ACCOUNT_HANDLE_ID = "E";
Santos Cordon7d4ddf62013-07-10 11:58:08 -070070 private static final String LOG_TAG = "PhoneUtils";
71 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
72
73 // Do not check in with VDBG = true, since that may write PII to the system log.
74 private static final boolean VDBG = false;
75
76 /** Control stack trace for Audio Mode settings */
77 private static final boolean DBG_SETAUDIOMODE_STACK = false;
78
79 /** Identifier for the "Add Call" intent extra. */
80 static final String ADD_CALL_MODE_KEY = "add_call_mode";
81
82 // Return codes from placeCall()
fionaxuf7885142016-11-27 16:08:39 -080083 public static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed
84 public static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code
85 public static final int CALL_STATUS_FAILED = 2; // The call failed
Santos Cordon7d4ddf62013-07-10 11:58:08 -070086
87 // State of the Phone's audio modes
88 // Each state can move to the other states, but within the state only certain
89 // transitions for AudioManager.setMode() are allowed.
90 static final int AUDIO_IDLE = 0; /** audio behaviour at phone idle */
91 static final int AUDIO_RINGING = 1; /** audio behaviour while ringing */
92 static final int AUDIO_OFFHOOK = 2; /** audio behaviour while in call. */
93
94 // USSD string length for MMI operations
95 static final int MIN_USSD_LEN = 1;
96 static final int MAX_USSD_LEN = 160;
97
98 /** Speaker state, persisting between wired headset connection events */
99 private static boolean sIsSpeakerEnabled = false;
100
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700101 /** Static handler for the connection/mute tracking */
102 private static ConnectionHandler mConnectionHandler;
103
104 /** Phone state changed event*/
105 private static final int PHONE_STATE_CHANGED = -1;
106
Zhihai Xua4915c72013-10-18 17:01:16 -0700107 /** poll phone DISCONNECTING status interval */
108 private static final int DISCONNECTING_POLLING_INTERVAL_MS = 200;
109
110 /** poll phone DISCONNECTING status times limit */
111 private static final int DISCONNECTING_POLLING_TIMES_LIMIT = 8;
112
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700113 /** Define for not a special CNAP string */
114 private static final int CNAP_SPECIAL_CASE_NO = -1;
115
Yorke Leee0f2b792014-10-15 12:30:44 -0700116 /**
117 * Theme to use for dialogs displayed by utility methods in this class. This is needed
118 * because these dialogs are displayed using the application context, which does not resolve
119 * the dialog theme correctly.
120 */
Zheng Zhangd889c772017-11-02 15:49:37 -0700121 private static final int THEME = com.android.internal.R.style.Theme_DeviceDefault_Dialog_Alert;
Yorke Leee0f2b792014-10-15 12:30:44 -0700122
Etan Cohen37abbab2014-03-07 16:57:03 -0800123 /** USSD information used to aggregate all USSD messages */
124 private static AlertDialog sUssdDialog = null;
125 private static StringBuilder sUssdMsg = new StringBuilder();
126
Tony Mak4c8f3c62015-12-07 02:30:37 +0000127 private static final ComponentName PSTN_CONNECTION_SERVICE_COMPONENT =
128 new ComponentName("com.android.phone",
129 "com.android.services.telephony.TelephonyConnectionService");
130
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700131 /**
132 * Handler that tracks the connections and updates the value of the
133 * Mute settings for each connection as needed.
134 */
135 private static class ConnectionHandler extends Handler {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700136 }
137
138 /**
139 * Register the ConnectionHandler with the phone, to receive connection events
140 */
141 public static void initializeConnectionHandler(CallManager cm) {
142 if (mConnectionHandler == null) {
143 mConnectionHandler = new ConnectionHandler();
144 }
145
146 // pass over cm as user.obj
147 cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm);
148
149 }
150
151 /** This class is never instantiated. */
152 private PhoneUtils() {
153 }
154
155 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700156 * For a CDMA phone, advance the call state upon making a new
157 * outgoing call.
158 *
159 * <pre>
160 * IDLE -> SINGLE_ACTIVE
161 * or
162 * SINGLE_ACTIVE -> THRWAY_ACTIVE
163 * </pre>
164 * @param app The phone instance.
165 */
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700166 private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app,
167 Connection connection) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700168 if (app.cdmaPhoneCallState.getCurrentCallState() ==
169 CdmaPhoneCallState.PhoneCallState.IDLE) {
170 // This is the first outgoing call. Set the Phone Call State to ACTIVE
171 app.cdmaPhoneCallState.setCurrentCallState(
172 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
173 } else {
174 // This is the second outgoing call. Set the Phone Call State to 3WAY
175 app.cdmaPhoneCallState.setCurrentCallState(
176 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700177
Santos Cordonda120f42014-08-06 04:44:34 -0700178 // TODO: Remove this code.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700179 //app.getCallModeler().setCdmaOutgoing3WayCall(connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700180 }
181 }
182
183 /**
Santos Cordon69a69192013-08-22 14:25:42 -0700184 * @see placeCall below
185 */
186 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
187 boolean isEmergencyCall) {
188 return placeCall(context, phone, number, contactRef, isEmergencyCall,
189 CallGatewayManager.EMPTY_INFO, null);
190 }
191
192 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700193 * Dial the number using the phone passed in.
194 *
195 * If the connection is establised, this method issues a sync call
196 * that may block to query the caller info.
197 * TODO: Change the logic to use the async query.
198 *
199 * @param context To perform the CallerInfo query.
200 * @param phone the Phone object.
201 * @param number to be dialed as requested by the user. This is
202 * NOT the phone number to connect to. It is used only to build the
203 * call card and to update the call log. See above for restrictions.
204 * @param contactRef that triggered the call. Typically a 'tel:'
205 * uri but can also be a 'content://contacts' one.
206 * @param isEmergencyCall indicates that whether or not this is an
207 * emergency call
208 * @param gatewayUri Is the address used to setup the connection, null
209 * if not using a gateway
Santos Cordon69a69192013-08-22 14:25:42 -0700210 * @param callGateway Class for setting gateway data on a successful call.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700211 *
212 * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
213 */
Santos Cordon69a69192013-08-22 14:25:42 -0700214 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
215 boolean isEmergencyCall, RawGatewayInfo gatewayInfo, CallGatewayManager callGateway) {
216 final Uri gatewayUri = gatewayInfo.gatewayUri;
217
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700218 if (VDBG) {
219 log("placeCall()... number: '" + number + "'"
220 + ", GW:'" + gatewayUri + "'"
221 + ", contactRef:" + contactRef
222 + ", isEmergencyCall: " + isEmergencyCall);
223 } else {
224 log("placeCall()... number: " + toLogSafePhoneNumber(number)
225 + ", GW: " + (gatewayUri != null ? "non-null" : "null")
226 + ", emergency? " + isEmergencyCall);
227 }
228 final PhoneGlobals app = PhoneGlobals.getInstance();
229
230 boolean useGateway = false;
231 if (null != gatewayUri &&
232 !isEmergencyCall &&
233 PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes.
234 useGateway = true;
235 }
236
237 int status = CALL_STATUS_DIALED;
238 Connection connection;
239 String numberToDial;
240 if (useGateway) {
241 // TODO: 'tel' should be a constant defined in framework base
242 // somewhere (it is in webkit.)
Jay Shrauner137458b2014-09-05 14:27:25 -0700243 if (null == gatewayUri || !PhoneAccount.SCHEME_TEL.equals(gatewayUri.getScheme())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700244 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
245 return CALL_STATUS_FAILED;
246 }
247
248 // We can use getSchemeSpecificPart because we don't allow #
249 // in the gateway numbers (treated a fragment delim.) However
250 // if we allow more complex gateway numbers sequence (with
251 // passwords or whatnot) that use #, this may break.
252 // TODO: Need to support MMI codes.
253 numberToDial = gatewayUri.getSchemeSpecificPart();
254 } else {
255 numberToDial = number;
256 }
257
258 // Remember if the phone state was in IDLE state before this call.
259 // After calling CallManager#dial(), getState() will return different state.
260 final boolean initiallyIdle = app.mCM.getState() == PhoneConstants.State.IDLE;
261
262 try {
Tyler Gunnc6514352015-06-02 21:46:34 -0700263 connection = app.mCM.dial(phone, numberToDial, VideoProfile.STATE_AUDIO_ONLY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700264 } catch (CallStateException ex) {
265 // CallStateException means a new outgoing call is not currently
266 // possible: either no more call slots exist, or there's another
267 // call already in the process of dialing or ringing.
268 Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
269 return CALL_STATUS_FAILED;
270
271 // Note that it's possible for CallManager.dial() to return
272 // null *without* throwing an exception; that indicates that
273 // we dialed an MMI (see below).
274 }
275
276 int phoneType = phone.getPhoneType();
277
278 // On GSM phones, null is returned for MMI codes
279 if (null == connection) {
Santos Cordonf77a3392014-07-21 19:48:10 -0700280 status = CALL_STATUS_FAILED;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700281 } else {
Tyler Gunn10f1c6a2014-01-17 12:01:11 -0800282 // Now that the call is successful, we can save the gateway info for the call
283 if (callGateway != null) {
284 callGateway.setGatewayInfoForConnection(connection, gatewayInfo);
285 }
286
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700287 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700288 updateCdmaCallStateOnNewOutgoingCall(app, connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700289 }
290
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700291 if (gatewayUri == null) {
292 // phone.dial() succeeded: we're now in a normal phone call.
293 // attach the URI to the CallerInfo Object if it is there,
294 // otherwise just attach the Uri Reference.
295 // if the uri does not have a "content" scheme, then we treat
296 // it as if it does NOT have a unique reference.
297 String content = context.getContentResolver().SCHEME_CONTENT;
298 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
299 Object userDataObject = connection.getUserData();
300 if (userDataObject == null) {
301 connection.setUserData(contactRef);
302 } else {
303 // TODO: This branch is dead code, we have
304 // just created the connection which has
305 // no user data (null) by default.
306 if (userDataObject instanceof CallerInfo) {
307 ((CallerInfo) userDataObject).contactRefUri = contactRef;
308 } else {
309 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
310 contactRef;
311 }
312 }
313 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700314 }
Santos Cordonc264cba2013-09-19 04:55:40 -0700315
Chiao Chenge365ba72013-09-26 14:18:12 -0700316 startGetCallerInfo(context, connection, null, null, gatewayInfo);
317
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700318 setAudioMode();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700319 }
320
321 return status;
322 }
323
324 /* package */ static String toLogSafePhoneNumber(String number) {
325 // For unknown number, log empty string.
326 if (number == null) {
327 return "";
328 }
329
330 if (VDBG) {
331 // When VDBG is true we emit PII.
332 return number;
333 }
334
335 // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
336 // sanitized phone numbers.
337 StringBuilder builder = new StringBuilder();
338 for (int i = 0; i < number.length(); i++) {
339 char c = number.charAt(i);
340 if (c == '-' || c == '@' || c == '.') {
341 builder.append(c);
342 } else {
343 builder.append('x');
344 }
345 }
346 return builder.toString();
347 }
348
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700349 static void separateCall(Connection c) {
350 try {
351 if (DBG) log("separateCall: " + toLogSafePhoneNumber(c.getAddress()));
352 c.separate();
353 } catch (CallStateException ex) {
354 Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
355 }
356 }
357
358 /**
359 * Handle the MMIInitiate message and put up an alert that lets
360 * the user cancel the operation, if applicable.
361 *
362 * @param context context to get strings.
363 * @param mmiCode the MmiCode object being started.
364 * @param buttonCallbackMessage message to post when button is clicked.
365 * @param previousAlert a previous alert used in this activity.
366 * @return the dialog handle
367 */
368 static Dialog displayMMIInitiate(Context context,
369 MmiCode mmiCode,
370 Message buttonCallbackMessage,
371 Dialog previousAlert) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700372 log("displayMMIInitiate: " + android.telecom.Log.pii(mmiCode.toString()));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700373 if (previousAlert != null) {
374 previousAlert.dismiss();
375 }
376
377 // The UI paradigm we are using now requests that all dialogs have
378 // user interaction, and that any other messages to the user should
379 // be by way of Toasts.
380 //
381 // In adhering to this request, all MMI initiating "OK" dialogs
382 // (non-cancelable MMIs) that end up being closed when the MMI
383 // completes (thereby showing a completion dialog) are being
384 // replaced with Toasts.
385 //
386 // As a side effect, moving to Toasts for the non-cancelable MMIs
387 // also means that buttonCallbackMessage (which was tied into "OK")
388 // is no longer invokable for these dialogs. This is not a problem
389 // since the only callback messages we supported were for cancelable
390 // MMIs anyway.
391 //
392 // A cancelable MMI is really just a USSD request. The term
393 // "cancelable" here means that we can cancel the request when the
394 // system prompts us for a response, NOT while the network is
395 // processing the MMI request. Any request to cancel a USSD while
396 // the network is NOT ready for a response may be ignored.
397 //
398 // With this in mind, we replace the cancelable alert dialog with
399 // a progress dialog, displayed until we receive a request from
400 // the the network. For more information, please see the comments
401 // in the displayMMIComplete() method below.
402 //
403 // Anything that is NOT a USSD request is a normal MMI request,
404 // which will bring up a toast (desribed above).
405
406 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
407
408 if (!isCancelable) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700409 log("displayMMIInitiate: not a USSD code, displaying status toast.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700410 CharSequence text = context.getText(R.string.mmiStarted);
411 Toast.makeText(context, text, Toast.LENGTH_SHORT)
412 .show();
413 return null;
414 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700415 log("displayMMIInitiate: running USSD code, displaying intermediate progress.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700416
417 // create the indeterminate progress dialog and display it.
Alex Hills779841a2015-10-22 13:23:28 -0400418 ProgressDialog pd = new ProgressDialog(context, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700419 pd.setMessage(context.getText(R.string.ussdRunning));
420 pd.setCancelable(false);
421 pd.setIndeterminate(true);
422 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
423
424 pd.show();
425
426 return pd;
427 }
428
429 }
430
431 /**
432 * Handle the MMIComplete message and fire off an intent to display
433 * the message.
434 *
435 * @param context context to get strings.
436 * @param mmiCode MMI result.
437 * @param previousAlert a previous alert used in this activity.
438 */
439 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
440 Message dismissCallbackMessage,
441 AlertDialog previousAlert) {
442 final PhoneGlobals app = PhoneGlobals.getInstance();
443 CharSequence text;
444 int title = 0; // title for the progress dialog, if needed.
445 MmiCode.State state = mmiCode.getState();
446
Tyler Gunn13fe2492017-05-22 14:14:20 -0700447 log("displayMMIComplete: state=" + state);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700448
449 switch (state) {
450 case PENDING:
451 // USSD code asking for feedback from user.
452 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700453 log("displayMMIComplete: using text from PENDING MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700454 break;
455 case CANCELLED:
456 text = null;
457 break;
458 case COMPLETE:
459 if (app.getPUKEntryActivity() != null) {
460 // if an attempt to unPUK the device was made, we specify
461 // the title and the message here.
462 title = com.android.internal.R.string.PinMmi;
463 text = context.getText(R.string.puk_unlocked);
464 break;
465 }
466 // All other conditions for the COMPLETE mmi state will cause
467 // the case to fall through to message logic in common with
468 // the FAILED case.
469
470 case FAILED:
471 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700472 log("displayMMIComplete (failed): using text from MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700473 break;
474 default:
475 throw new IllegalStateException("Unexpected MmiCode state: " + state);
476 }
477
478 if (previousAlert != null) {
479 previousAlert.dismiss();
480 }
481
482 // Check to see if a UI exists for the PUK activation. If it does
483 // exist, then it indicates that we're trying to unblock the PUK.
484 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
485 if (DBG) log("displaying PUK unblocking progress dialog.");
486
487 // create the progress dialog, make sure the flags and type are
488 // set correctly.
Alex Hills779841a2015-10-22 13:23:28 -0400489 ProgressDialog pd = new ProgressDialog(app, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700490 pd.setTitle(title);
491 pd.setMessage(text);
492 pd.setCancelable(false);
493 pd.setIndeterminate(true);
494 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
495 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
496
497 // display the dialog
498 pd.show();
499
500 // indicate to the Phone app that the progress dialog has
501 // been assigned for the PUK unlock / SIM READY process.
502 app.setPukEntryProgressDialog(pd);
503
504 } else {
505 // In case of failure to unlock, we'll need to reset the
506 // PUK unlock activity, so that the user may try again.
507 if (app.getPUKEntryActivity() != null) {
508 app.setPukEntryActivity(null);
509 }
510
511 // A USSD in a pending state means that it is still
512 // interacting with the user.
513 if (state != MmiCode.State.PENDING) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700514 log("displayMMIComplete: MMI code has finished running.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700515
Tyler Gunn13fe2492017-05-22 14:14:20 -0700516 log("displayMMIComplete: Extended NW displayMMIInitiate (" + text + ")");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700517 if (text == null || text.length() == 0)
518 return;
519
520 // displaying system alert dialog on the screen instead of
521 // using another activity to display the message. This
522 // places the message at the forefront of the UI.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700523
Etan Cohen37abbab2014-03-07 16:57:03 -0800524 if (sUssdDialog == null) {
Yorke Leee0f2b792014-10-15 12:30:44 -0700525 sUssdDialog = new AlertDialog.Builder(context, THEME)
Etan Cohen37abbab2014-03-07 16:57:03 -0800526 .setPositiveButton(R.string.ok, null)
527 .setCancelable(true)
528 .setOnDismissListener(new DialogInterface.OnDismissListener() {
529 @Override
530 public void onDismiss(DialogInterface dialog) {
531 sUssdMsg.setLength(0);
532 }
533 })
534 .create();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700535
Etan Cohen37abbab2014-03-07 16:57:03 -0800536 sUssdDialog.getWindow().setType(
Brad Ebinger2eefb2b2017-08-03 11:09:30 -0700537 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
Etan Cohen37abbab2014-03-07 16:57:03 -0800538 sUssdDialog.getWindow().addFlags(
539 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
540 }
541 if (sUssdMsg.length() != 0) {
542 sUssdMsg
543 .insert(0, "\n")
544 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
545 .insert(0, "\n");
546 }
547 sUssdMsg.insert(0, text);
548 sUssdDialog.setMessage(sUssdMsg.toString());
549 sUssdDialog.show();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700550 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700551 log("displayMMIComplete: USSD code has requested user input. Constructing input "
552 + "dialog.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700553
554 // USSD MMI code that is interacting with the user. The
555 // basic set of steps is this:
556 // 1. User enters a USSD request
557 // 2. We recognize the request and displayMMIInitiate
558 // (above) creates a progress dialog.
559 // 3. Request returns and we get a PENDING or COMPLETE
560 // message.
561 // 4. These MMI messages are caught in the PhoneApp
562 // (onMMIComplete) and the InCallScreen
563 // (mHandler.handleMessage) which bring up this dialog
564 // and closes the original progress dialog,
565 // respectively.
566 // 5. If the message is anything other than PENDING,
567 // we are done, and the alert dialog (directly above)
568 // displays the outcome.
569 // 6. If the network is requesting more information from
570 // the user, the MMI will be in a PENDING state, and
571 // we display this dialog with the message.
572 // 7. User input, or cancel requests result in a return
573 // to step 1. Keep in mind that this is the only
574 // time that a USSD should be canceled.
575
576 // inflate the layout with the scrolling text area for the dialog.
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800577 ContextThemeWrapper contextThemeWrapper =
578 new ContextThemeWrapper(context, R.style.DialerAlertDialogTheme);
579 LayoutInflater inflater = (LayoutInflater) contextThemeWrapper.getSystemService(
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700580 Context.LAYOUT_INFLATER_SERVICE);
581 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
582
583 // get the input field.
584 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
585
586 // specify the dialog's click listener, with SEND and CANCEL logic.
587 final DialogInterface.OnClickListener mUSSDDialogListener =
588 new DialogInterface.OnClickListener() {
589 public void onClick(DialogInterface dialog, int whichButton) {
590 switch (whichButton) {
591 case DialogInterface.BUTTON_POSITIVE:
592 // As per spec 24.080, valid length of ussd string
593 // is 1 - 160. If length is out of the range then
594 // display toast message & Cancel MMI operation.
595 if (inputText.length() < MIN_USSD_LEN
596 || inputText.length() > MAX_USSD_LEN) {
597 Toast.makeText(app,
598 app.getResources().getString(R.string.enter_input,
599 MIN_USSD_LEN, MAX_USSD_LEN),
600 Toast.LENGTH_LONG).show();
601 if (mmiCode.isCancelable()) {
602 mmiCode.cancel();
603 }
604 } else {
605 phone.sendUssdResponse(inputText.getText().toString());
606 }
607 break;
608 case DialogInterface.BUTTON_NEGATIVE:
609 if (mmiCode.isCancelable()) {
610 mmiCode.cancel();
611 }
612 break;
613 }
614 }
615 };
616
617 // build the dialog
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800618 final AlertDialog newDialog = new AlertDialog.Builder(contextThemeWrapper)
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700619 .setMessage(text)
620 .setView(dialogView)
621 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
622 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
623 .setCancelable(false)
624 .create();
625
626 // attach the key listener to the dialog's input field and make
627 // sure focus is set.
628 final View.OnKeyListener mUSSDDialogInputListener =
629 new View.OnKeyListener() {
630 public boolean onKey(View v, int keyCode, KeyEvent event) {
631 switch (keyCode) {
632 case KeyEvent.KEYCODE_CALL:
633 case KeyEvent.KEYCODE_ENTER:
634 if(event.getAction() == KeyEvent.ACTION_DOWN) {
635 phone.sendUssdResponse(inputText.getText().toString());
636 newDialog.dismiss();
637 }
638 return true;
639 }
640 return false;
641 }
642 };
643 inputText.setOnKeyListener(mUSSDDialogInputListener);
644 inputText.requestFocus();
645
646 // set the window properties of the dialog
647 newDialog.getWindow().setType(
648 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
649 newDialog.getWindow().addFlags(
650 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
651
652 // now show the dialog!
653 newDialog.show();
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800654
655 newDialog.getButton(DialogInterface.BUTTON_POSITIVE)
656 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
657 newDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
658 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700659 }
660 }
661 }
662
663 /**
664 * Cancels the current pending MMI operation, if applicable.
665 * @return true if we canceled an MMI operation, or false
666 * if the current pending MMI wasn't cancelable
667 * or if there was no current pending MMI at all.
668 *
669 * @see displayMMIInitiate
670 */
671 static boolean cancelMmiCode(Phone phone) {
672 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
673 int count = pendingMmis.size();
674 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
675
676 boolean canceled = false;
677 if (count > 0) {
678 // assume that we only have one pending MMI operation active at a time.
679 // I don't think it's possible to enter multiple MMI codes concurrently
680 // in the phone UI, because during the MMI operation, an Alert panel
681 // is displayed, which prevents more MMI code from being entered.
682 MmiCode mmiCode = pendingMmis.get(0);
683 if (mmiCode.isCancelable()) {
684 mmiCode.cancel();
685 canceled = true;
686 }
687 }
688 return canceled;
689 }
690
691 public static class VoiceMailNumberMissingException extends Exception {
692 VoiceMailNumberMissingException() {
693 super();
694 }
695
696 VoiceMailNumberMissingException(String msg) {
697 super(msg);
698 }
699 }
700
701 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700702 * Gets the phone number to be called from an intent. Requires a Context
703 * to access the contacts database, and a Phone to access the voicemail
704 * number.
705 *
706 * <p>If <code>phone</code> is <code>null</code>, the function will return
707 * <code>null</code> for <code>voicemail:</code> URIs;
708 * if <code>context</code> is <code>null</code>, the function will return
709 * <code>null</code> for person/phone URIs.</p>
710 *
711 * <p>If the intent contains a <code>sip:</code> URI, the returned
712 * "number" is actually the SIP address.
713 *
714 * @param context a context to use (or
715 * @param intent the intent
716 *
717 * @throws VoiceMailNumberMissingException if <code>intent</code> contains
718 * a <code>voicemail:</code> URI, but <code>phone</code> does not
719 * have a voicemail number set.
720 *
721 * @return the phone number (or SIP address) that would be called by the intent,
722 * or <code>null</code> if the number cannot be found.
723 */
724 private static String getNumberFromIntent(Context context, Intent intent)
725 throws VoiceMailNumberMissingException {
726 Uri uri = intent.getData();
727 String scheme = uri.getScheme();
728
729 // The sip: scheme is simple: just treat the rest of the URI as a
730 // SIP address.
Jay Shrauner137458b2014-09-05 14:27:25 -0700731 if (PhoneAccount.SCHEME_SIP.equals(scheme)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700732 return uri.getSchemeSpecificPart();
733 }
734
735 // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
736 // the other cases (i.e. tel: and voicemail: and contact: URIs.)
737
738 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
739
740 // Check for a voicemail-dialing request. If the voicemail number is
741 // empty, throw a VoiceMailNumberMissingException.
Jay Shrauner137458b2014-09-05 14:27:25 -0700742 if (PhoneAccount.SCHEME_VOICEMAIL.equals(scheme) &&
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700743 (number == null || TextUtils.isEmpty(number)))
744 throw new VoiceMailNumberMissingException();
745
746 return number;
747 }
748
749 /**
750 * Returns the caller-id info corresponding to the specified Connection.
751 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
752 * extract a phone number from the specified Connection, and feed that
753 * number into CallerInfo.getCallerInfo().)
754 *
755 * The returned CallerInfo may be null in certain error cases, like if the
756 * specified Connection was null, or if we weren't able to get a valid
757 * phone number from the Connection.
758 *
759 * Finally, if the getCallerInfo() call did succeed, we save the resulting
760 * CallerInfo object in the "userData" field of the Connection.
761 *
762 * NOTE: This API should be avoided, with preference given to the
763 * asynchronous startGetCallerInfo API.
764 */
765 static CallerInfo getCallerInfo(Context context, Connection c) {
766 CallerInfo info = null;
767
768 if (c != null) {
769 //See if there is a URI attached. If there is, this means
770 //that there is no CallerInfo queried yet, so we'll need to
771 //replace the URI with a full CallerInfo object.
772 Object userDataObject = c.getUserData();
773 if (userDataObject instanceof Uri) {
774 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
775 if (info != null) {
776 c.setUserData(info);
777 }
778 } else {
779 if (userDataObject instanceof CallerInfoToken) {
780 //temporary result, while query is running
781 info = ((CallerInfoToken) userDataObject).currentInfo;
782 } else {
783 //final query result
784 info = (CallerInfo) userDataObject;
785 }
786 if (info == null) {
787 // No URI, or Existing CallerInfo, so we'll have to make do with
788 // querying a new CallerInfo using the connection's phone number.
789 String number = c.getAddress();
790
791 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
792
793 if (!TextUtils.isEmpty(number)) {
794 info = CallerInfo.getCallerInfo(context, number);
795 if (info != null) {
796 c.setUserData(info);
797 }
798 }
799 }
800 }
801 }
802 return info;
803 }
804
805 /**
806 * Class returned by the startGetCallerInfo call to package a temporary
807 * CallerInfo Object, to be superceded by the CallerInfo Object passed
808 * into the listener when the query with token mAsyncQueryToken is complete.
809 */
810 public static class CallerInfoToken {
811 /**indicates that there will no longer be updates to this request.*/
812 public boolean isFinal;
813
814 public CallerInfo currentInfo;
815 public CallerInfoAsyncQuery asyncQuery;
816 }
817
818 /**
819 * Start a CallerInfo Query based on the earliest connection in the call.
820 */
821 static CallerInfoToken startGetCallerInfo(Context context, Call call,
822 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
823 Connection conn = null;
824 int phoneType = call.getPhone().getPhoneType();
825 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
826 conn = call.getLatestConnection();
827 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700828 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -0700829 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700830 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700831 conn = call.getEarliestConnection();
832 } else {
833 throw new IllegalStateException("Unexpected phone type: " + phoneType);
834 }
835
836 return startGetCallerInfo(context, conn, listener, cookie);
837 }
838
Chiao Chenge365ba72013-09-26 14:18:12 -0700839 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
840 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
841 return startGetCallerInfo(context, c, listener, cookie, null);
842 }
843
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700844 /**
845 * place a temporary callerinfo object in the hands of the caller and notify
846 * caller when the actual query is done.
847 */
848 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -0700849 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
850 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700851 CallerInfoToken cit;
852
853 if (c == null) {
854 //TODO: perhaps throw an exception here.
855 cit = new CallerInfoToken();
856 cit.asyncQuery = null;
857 return cit;
858 }
859
860 Object userDataObject = c.getUserData();
861
862 // There are now 3 states for the Connection's userData object:
863 //
864 // (1) Uri - query has not been executed yet
865 //
866 // (2) CallerInfoToken - query is executing, but has not completed.
867 //
868 // (3) CallerInfo - query has executed.
869 //
870 // In each case we have slightly different behaviour:
871 // 1. If the query has not been executed yet (Uri or null), we start
872 // query execution asynchronously, and note it by attaching a
873 // CallerInfoToken as the userData.
874 // 2. If the query is executing (CallerInfoToken), we've essentially
875 // reached a state where we've received multiple requests for the
876 // same callerInfo. That means that once the query is complete,
877 // we'll need to execute the additional listener requested.
878 // 3. If the query has already been executed (CallerInfo), we just
879 // return the CallerInfo object as expected.
880 // 4. Regarding isFinal - there are cases where the CallerInfo object
881 // will not be attached, like when the number is empty (caller id
882 // blocking). This flag is used to indicate that the
883 // CallerInfoToken object is going to be permanent since no
884 // query results will be returned. In the case where a query
885 // has been completed, this flag is used to indicate to the caller
886 // that the data will not be updated since it is valid.
887 //
888 // Note: For the case where a number is NOT retrievable, we leave
889 // the CallerInfo as null in the CallerInfoToken. This is
890 // something of a departure from the original code, since the old
891 // code manufactured a CallerInfo object regardless of the query
892 // outcome. From now on, we will append an empty CallerInfo
893 // object, to mirror previous behaviour, and to avoid Null Pointer
894 // Exceptions.
895
896 if (userDataObject instanceof Uri) {
897 // State (1): query has not been executed yet
898
899 //create a dummy callerinfo, populate with what we know from URI.
900 cit = new CallerInfoToken();
901 cit.currentInfo = new CallerInfo();
902 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
903 (Uri) userDataObject, sCallerInfoQueryListener, c);
904 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
905 cit.isFinal = false;
906
907 c.setUserData(cit);
908
909 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
910
911 } else if (userDataObject == null) {
912 // No URI, or Existing CallerInfo, so we'll have to make do with
913 // querying a new CallerInfo using the connection's phone number.
914 String number = c.getAddress();
915
Chiao Cheng685dcb62013-10-02 11:51:06 -0700916 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -0700917 // Gateway number, the connection number is actually the gateway number.
918 // need to lookup via dialed number.
919 number = info.trueNumber;
920 }
921
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700922 if (DBG) {
923 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
924 log("- number (address): " + toLogSafePhoneNumber(number));
925 log("- c: " + c);
926 log("- phone: " + c.getCall().getPhone());
927 int phoneType = c.getCall().getPhone().getPhoneType();
928 log("- phoneType: " + phoneType);
929 switch (phoneType) {
930 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
931 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -0700932 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700933 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
934 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700935 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
936 log(" ==> PHONE_TYPE_THIRD_PARTY");
937 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700938 default: log(" ==> Unknown phone type"); break;
939 }
940 }
941
942 cit = new CallerInfoToken();
943 cit.currentInfo = new CallerInfo();
944
945 // Store CNAP information retrieved from the Connection (we want to do this
946 // here regardless of whether the number is empty or not).
947 cit.currentInfo.cnapName = c.getCnapName();
948 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
949 // by ContactInfo later
950 cit.currentInfo.numberPresentation = c.getNumberPresentation();
951 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
952
953 if (VDBG) {
954 log("startGetCallerInfo: number = " + number);
955 log("startGetCallerInfo: CNAP Info from FW(1): name="
956 + cit.currentInfo.cnapName
957 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
958 }
959
960 // handling case where number is null (caller id hidden) as well.
961 if (!TextUtils.isEmpty(number)) {
962 // Check for special CNAP cases and modify the CallerInfo accordingly
963 // to be sure we keep the right information to display/log later
964 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
965 cit.currentInfo.numberPresentation);
966
967 cit.currentInfo.phoneNumber = number;
968 // For scenarios where we may receive a valid number from the network but a
969 // restricted/unavailable presentation, we do not want to perform a contact query
970 // (see note on isFinal above). So we set isFinal to true here as well.
971 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
972 cit.isFinal = true;
973 } else {
974 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
975 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
976 number, sCallerInfoQueryListener, c);
977 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
978 cit.isFinal = false;
979 }
980 } else {
981 // This is the case where we are querying on a number that
982 // is null or empty, like a caller whose caller id is
983 // blocked or empty (CLIR). The previous behaviour was to
984 // throw a null CallerInfo object back to the user, but
985 // this departure is somewhat cleaner.
986 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
987 cit.isFinal = true; // please see note on isFinal, above.
988 }
989
990 c.setUserData(cit);
991
992 if (DBG) {
993 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
994 }
995
996 } else if (userDataObject instanceof CallerInfoToken) {
997 // State (2): query is executing, but has not completed.
998
999 // just tack on this listener to the queue.
1000 cit = (CallerInfoToken) userDataObject;
1001
1002 // handling case where number is null (caller id hidden) as well.
1003 if (cit.asyncQuery != null) {
1004 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1005
1006 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1007 listener.getClass().toString());
1008 } else {
1009 // handling case where number/name gets updated later on by the network
1010 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -07001011
1012 if (info != null) {
1013 // Gateway number, the connection number is actually the gateway number.
1014 // need to lookup via dialed number.
1015 updatedNumber = info.trueNumber;
1016 }
1017
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001018 if (DBG) {
1019 log("startGetCallerInfo: updatedNumber initially = "
1020 + toLogSafePhoneNumber(updatedNumber));
1021 }
1022 if (!TextUtils.isEmpty(updatedNumber)) {
1023 // Store CNAP information retrieved from the Connection
1024 cit.currentInfo.cnapName = c.getCnapName();
1025 // This can still get overwritten by ContactInfo
1026 cit.currentInfo.name = cit.currentInfo.cnapName;
1027 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1028 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1029
1030 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1031 updatedNumber, cit.currentInfo.numberPresentation);
1032
1033 cit.currentInfo.phoneNumber = updatedNumber;
1034 if (DBG) {
1035 log("startGetCallerInfo: updatedNumber="
1036 + toLogSafePhoneNumber(updatedNumber));
1037 }
1038 if (VDBG) {
1039 log("startGetCallerInfo: CNAP Info from FW(2): name="
1040 + cit.currentInfo.cnapName
1041 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1042 } else if (DBG) {
1043 log("startGetCallerInfo: CNAP Info from FW(2)");
1044 }
1045 // For scenarios where we may receive a valid number from the network but a
1046 // restricted/unavailable presentation, we do not want to perform a contact query
1047 // (see note on isFinal above). So we set isFinal to true here as well.
1048 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1049 cit.isFinal = true;
1050 } else {
1051 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1052 updatedNumber, sCallerInfoQueryListener, c);
1053 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1054 cit.isFinal = false;
1055 }
1056 } else {
1057 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1058 if (cit.currentInfo == null) {
1059 cit.currentInfo = new CallerInfo();
1060 }
1061 // Store CNAP information retrieved from the Connection
1062 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
1063 // overwritten by ContactInfo
1064 cit.currentInfo.name = cit.currentInfo.cnapName;
1065 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1066 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1067
1068 if (VDBG) {
1069 log("startGetCallerInfo: CNAP Info from FW(3): name="
1070 + cit.currentInfo.cnapName
1071 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1072 } else if (DBG) {
1073 log("startGetCallerInfo: CNAP Info from FW(3)");
1074 }
1075 cit.isFinal = true; // please see note on isFinal, above.
1076 }
1077 }
1078 } else {
1079 // State (3): query is complete.
1080
1081 // The connection's userDataObject is a full-fledged
1082 // CallerInfo instance. Wrap it in a CallerInfoToken and
1083 // return it to the user.
1084
1085 cit = new CallerInfoToken();
1086 cit.currentInfo = (CallerInfo) userDataObject;
1087 cit.asyncQuery = null;
1088 cit.isFinal = true;
1089 // since the query is already done, call the listener.
1090 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1091 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
1092 }
1093 return cit;
1094 }
1095
1096 /**
1097 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
1098 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
1099 */
1100 private static final int QUERY_TOKEN = -1;
1101 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1102 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1103 /**
1104 * When the query completes, we stash the resulting CallerInfo
1105 * object away in the Connection's "userData" (where it will
1106 * later be retrieved by the in-call UI.)
1107 */
1108 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1109 if (DBG) log("query complete, updating connection.userdata");
1110 Connection conn = (Connection) cookie;
1111
1112 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1113 // If no ContactInfo, then we want to use CNAP information coming from network
1114 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1115 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1116 // If the number presentation has not been set by
1117 // the ContactInfo, use the one from the
1118 // connection.
1119
1120 // TODO: Need a new util method to merge the info
1121 // from the Connection in a CallerInfo object.
1122 // Here 'ci' is a new CallerInfo instance read
1123 // from the DB. It has lost all the connection
1124 // info preset before the query (see PhoneUtils
1125 // line 1334). We should have a method to merge
1126 // back into this new instance the info from the
1127 // connection object not set by the DB. If the
1128 // Connection already has a CallerInfo instance in
1129 // userData, then we could use this instance to
1130 // fill 'ci' in. The same routine could be used in
1131 // PhoneUtils.
1132 if (0 == ci.numberPresentation) {
1133 ci.numberPresentation = conn.getNumberPresentation();
1134 }
1135 } else {
1136 // No matching contact was found for this number.
1137 // Return a new CallerInfo based solely on the CNAP
1138 // information from the network.
1139
1140 CallerInfo newCi = getCallerInfo(null, conn);
1141
1142 // ...but copy over the (few) things we care about
1143 // from the original CallerInfo object:
1144 if (newCi != null) {
1145 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1146 newCi.geoDescription = ci.geoDescription; // To get geo description string
1147 ci = newCi;
1148 }
1149 }
1150
1151 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1152 conn.setUserData(ci);
1153 }
1154 };
1155
1156
1157 /**
1158 * Returns a single "name" for the specified given a CallerInfo object.
1159 * If the name is null, return defaultString as the default value, usually
1160 * context.getString(R.string.unknown).
1161 */
1162 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1163 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1164
1165 String compactName = null;
1166 if (ci != null) {
1167 if (TextUtils.isEmpty(ci.name)) {
1168 // Perform any modifications for special CNAP cases to
1169 // the phone number being displayed, if applicable.
1170 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1171 ci.numberPresentation);
1172 } else {
1173 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1174 compactName = ci.name;
1175 }
1176 }
1177
1178 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1179 // If we're still null/empty here, then check if we have a presentation
1180 // string that takes precedence that we could return, otherwise display
1181 // "unknown" string.
1182 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1183 compactName = context.getString(R.string.private_num);
1184 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1185 compactName = context.getString(R.string.payphone);
1186 } else {
1187 compactName = context.getString(R.string.unknown);
1188 }
1189 }
1190 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1191 return compactName;
1192 }
1193
1194 /**
1195 * Returns true if the specified Call is a "conference call", meaning
1196 * that it owns more than one Connection object. This information is
1197 * used to trigger certain UI changes that appear when a conference
1198 * call is active (like displaying the label "Conference call", and
1199 * enabling the "Manage conference" UI.)
1200 *
1201 * Watch out: This method simply checks the number of Connections,
1202 * *not* their states. So if a Call has (for example) one ACTIVE
1203 * connection and one DISCONNECTED connection, this method will return
1204 * true (which is unintuitive, since the Call isn't *really* a
1205 * conference call any more.)
1206 *
1207 * @return true if the specified call has more than one connection (in any state.)
1208 */
1209 static boolean isConferenceCall(Call call) {
1210 // CDMA phones don't have the same concept of "conference call" as
1211 // GSM phones do; there's no special "conference call" state of
1212 // the UI or a "manage conference" function. (Instead, when
1213 // you're in a 3-way call, all we can do is display the "generic"
1214 // state of the UI.) So as far as the in-call UI is concerned,
1215 // Conference corresponds to generic display.
1216 final PhoneGlobals app = PhoneGlobals.getInstance();
1217 int phoneType = call.getPhone().getPhoneType();
1218 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1219 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
1220 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
1221 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1222 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
1223 return true;
1224 }
1225 } else {
1226 List<Connection> connections = call.getConnections();
1227 if (connections != null && connections.size() > 1) {
1228 return true;
1229 }
1230 }
1231 return false;
1232
1233 // TODO: We may still want to change the semantics of this method
1234 // to say that a given call is only really a conference call if
1235 // the number of ACTIVE connections, not the total number of
1236 // connections, is greater than one. (See warning comment in the
1237 // javadoc above.)
1238 // Here's an implementation of that:
1239 // if (connections == null) {
1240 // return false;
1241 // }
1242 // int numActiveConnections = 0;
1243 // for (Connection conn : connections) {
1244 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
1245 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1246 // if (numActiveConnections > 1) {
1247 // return true;
1248 // }
1249 // }
1250 // return false;
1251 }
1252
1253 /**
1254 * Launch the Dialer to start a new call.
1255 * This is just a wrapper around the ACTION_DIAL intent.
1256 */
1257 /* package */ static boolean startNewCall(final CallManager cm) {
1258 final PhoneGlobals app = PhoneGlobals.getInstance();
1259
1260 // Sanity-check that this is OK given the current state of the phone.
1261 if (!okToAddCall(cm)) {
1262 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1263 dumpCallManager();
1264 return false;
1265 }
1266
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001267 Intent intent = new Intent(Intent.ACTION_DIAL);
1268 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1269
1270 // when we request the dialer come up, we also want to inform
1271 // it that we're going through the "add call" option from the
1272 // InCallScreen / PhoneUtils.
1273 intent.putExtra(ADD_CALL_MODE_KEY, true);
1274 try {
1275 app.startActivity(intent);
1276 } catch (ActivityNotFoundException e) {
1277 // This is rather rare but possible.
1278 // Note: this method is used even when the phone is encrypted. At that moment
1279 // the system may not find any Activity which can accept this Intent.
1280 Log.e(LOG_TAG, "Activity for adding calls isn't found.");
1281 return false;
1282 }
1283
1284 return true;
1285 }
1286
1287 /**
1288 * Turns on/off speaker.
1289 *
1290 * @param context Context
1291 * @param flag True when speaker should be on. False otherwise.
1292 * @param store True when the settings should be stored in the device.
1293 */
1294 /* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1295 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
1296 final PhoneGlobals app = PhoneGlobals.getInstance();
1297
1298 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1299 audioManager.setSpeakerphoneOn(flag);
1300
1301 // record the speaker-enable value
1302 if (store) {
1303 sIsSpeakerEnabled = flag;
1304 }
1305
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001306 // We also need to make a fresh call to PhoneApp.updateWakeState()
1307 // any time the speaker state changes, since the screen timeout is
1308 // sometimes different depending on whether or not the speaker is
1309 // in use.
1310 app.updateWakeState();
1311
Hariprasad Jayakumareee6a9e2014-04-25 15:33:13 -07001312 app.mCM.setEchoSuppressionEnabled();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001313 }
1314
1315 /**
1316 * Restore the speaker mode, called after a wired headset disconnect
1317 * event.
1318 */
1319 static void restoreSpeakerMode(Context context) {
1320 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1321
1322 // change the mode if needed.
1323 if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1324 turnOnSpeaker(context, sIsSpeakerEnabled, false);
1325 }
1326 }
1327
1328 static boolean isSpeakerOn(Context context) {
1329 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1330 return audioManager.isSpeakerphoneOn();
1331 }
1332
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001333 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001334 * Get the mute state of foreground phone, which has the current
1335 * foreground call
1336 */
1337 static boolean getMute() {
Santos Cordonbb2bcef2014-08-05 19:08:10 -07001338 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001339 }
1340
1341 /* package */ static void setAudioMode() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001342 }
1343
1344 /**
1345 * Sets the audio mode per current phone state.
1346 */
1347 /* package */ static void setAudioMode(CallManager cm) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001348 }
1349
1350 /**
1351 * Look for ANY connections on the phone that qualify as being
1352 * disconnected.
1353 *
1354 * @return true if we find a connection that is disconnected over
1355 * all the phone's call objects.
1356 */
1357 /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1358 return hasDisconnectedConnections(phone.getForegroundCall()) ||
1359 hasDisconnectedConnections(phone.getBackgroundCall()) ||
1360 hasDisconnectedConnections(phone.getRingingCall());
1361 }
1362
1363 /**
1364 * Iterate over all connections in a call to see if there are any
1365 * that are not alive (disconnected or idle).
1366 *
1367 * @return true if we find a connection that is disconnected, and
1368 * pending removal via
Amit Mahajan6d83e5e2015-12-14 13:24:48 -08001369 * {@link com.android.internal.telephony.Call#clearDisconnected()}.
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001370 */
1371 private static final boolean hasDisconnectedConnections(Call call) {
1372 // look through all connections for non-active ones.
1373 for (Connection c : call.getConnections()) {
1374 if (!c.isAlive()) {
1375 return true;
1376 }
1377 }
1378 return false;
1379 }
1380
1381 //
1382 // Misc UI policy helper functions
1383 //
1384
1385 /**
Christine Chenaf2fd0a2013-09-13 16:27:40 -07001386 * @return true if we're allowed to hold calls, given the current
1387 * state of the Phone.
1388 */
1389 /* package */ static boolean okToHoldCall(CallManager cm) {
1390 final Call fgCall = cm.getActiveFgCall();
1391 final boolean hasHoldingCall = cm.hasActiveBgCall();
1392 final Call.State fgCallState = fgCall.getState();
1393
1394 // The "Hold" control is disabled entirely if there's
1395 // no way to either hold or unhold in the current state.
1396 final boolean okToHold = (fgCallState == Call.State.ACTIVE) && !hasHoldingCall;
1397 final boolean okToUnhold = cm.hasActiveBgCall() && (fgCallState == Call.State.IDLE);
1398 final boolean canHold = okToHold || okToUnhold;
1399
1400 return canHold;
1401 }
1402
1403 /**
1404 * @return true if we support holding calls, given the current
1405 * state of the Phone.
1406 */
1407 /* package */ static boolean okToSupportHold(CallManager cm) {
1408 boolean supportsHold = false;
1409
1410 final Call fgCall = cm.getActiveFgCall();
1411 final boolean hasHoldingCall = cm.hasActiveBgCall();
1412 final Call.State fgCallState = fgCall.getState();
1413
1414 if (TelephonyCapabilities.supportsHoldAndUnhold(fgCall.getPhone())) {
1415 // This phone has the concept of explicit "Hold" and "Unhold" actions.
1416 supportsHold = true;
1417 } else if (hasHoldingCall && (fgCallState == Call.State.IDLE)) {
1418 // Even when foreground phone device doesn't support hold/unhold, phone devices
1419 // for background holding calls may do.
1420 final Call bgCall = cm.getFirstActiveBgCall();
1421 if (bgCall != null &&
1422 TelephonyCapabilities.supportsHoldAndUnhold(bgCall.getPhone())) {
1423 supportsHold = true;
1424 }
1425 }
1426 return supportsHold;
1427 }
1428
1429 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001430 * @return true if we're allowed to swap calls, given the current
1431 * state of the Phone.
1432 */
1433 /* package */ static boolean okToSwapCalls(CallManager cm) {
1434 int phoneType = cm.getDefaultPhone().getPhoneType();
1435 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1436 // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
1437 // state by either accepting a Call Waiting or by merging two calls
1438 PhoneGlobals app = PhoneGlobals.getInstance();
1439 return (app.cdmaPhoneCallState.getCurrentCallState()
1440 == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
1441 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001442 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07001443 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001444 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001445 // GSM: "Swap" is available if both lines are in use and there's no
1446 // incoming call. (Actually we need to verify that the active
1447 // call really is in the ACTIVE state and the holding call really
1448 // is in the HOLDING state, since you *can't* actually swap calls
1449 // when the foreground call is DIALING or ALERTING.)
1450 return !cm.hasActiveRingingCall()
1451 && (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
1452 && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
1453 } else {
1454 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1455 }
1456 }
1457
1458 /**
1459 * @return true if we're allowed to merge calls, given the current
1460 * state of the Phone.
1461 */
1462 /* package */ static boolean okToMergeCalls(CallManager cm) {
1463 int phoneType = cm.getFgPhone().getPhoneType();
1464 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1465 // CDMA: "Merge" is enabled only when the user is in a 3Way call.
1466 PhoneGlobals app = PhoneGlobals.getInstance();
1467 return ((app.cdmaPhoneCallState.getCurrentCallState()
1468 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1469 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
1470 } else {
1471 // GSM: "Merge" is available if both lines are in use and there's no
1472 // incoming call, *and* the current conference isn't already
1473 // "full".
1474 // TODO: shall move all okToMerge logic to CallManager
1475 return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
1476 && cm.hasActiveBgCall()
1477 && cm.canConference(cm.getFirstActiveBgCall());
1478 }
1479 }
1480
1481 /**
1482 * @return true if the UI should let you add a new call, given the current
1483 * state of the Phone.
1484 */
1485 /* package */ static boolean okToAddCall(CallManager cm) {
1486 Phone phone = cm.getActiveFgCall().getPhone();
1487
1488 // "Add call" is never allowed in emergency callback mode (ECM).
1489 if (isPhoneInEcm(phone)) {
1490 return false;
1491 }
1492
1493 int phoneType = phone.getPhoneType();
1494 final Call.State fgCallState = cm.getActiveFgCall().getState();
1495 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1496 // CDMA: "Add call" button is only enabled when:
1497 // - ForegroundCall is in ACTIVE state
1498 // - After 30 seconds of user Ignoring/Missing a Call Waiting call.
1499 PhoneGlobals app = PhoneGlobals.getInstance();
1500 return ((fgCallState == Call.State.ACTIVE)
1501 && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
1502 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001503 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07001504 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001505 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001506 // GSM: "Add call" is available only if ALL of the following are true:
1507 // - There's no incoming ringing call
1508 // - There's < 2 lines in use
1509 // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
1510 // (We mainly need to make sure it *isn't* DIALING or ALERTING.)
1511 final boolean hasRingingCall = cm.hasActiveRingingCall();
1512 final boolean hasActiveCall = cm.hasActiveFgCall();
1513 final boolean hasHoldingCall = cm.hasActiveBgCall();
1514 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1515
1516 return !hasRingingCall
1517 && !allLinesTaken
1518 && ((fgCallState == Call.State.ACTIVE)
1519 || (fgCallState == Call.State.IDLE)
1520 || (fgCallState == Call.State.DISCONNECTED));
1521 } else {
1522 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1523 }
1524 }
1525
1526 /**
1527 * Based on the input CNAP number string,
1528 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1529 * Otherwise, return CNAP_SPECIAL_CASE_NO.
1530 */
1531 private static int checkCnapSpecialCases(String n) {
1532 if (n.equals("PRIVATE") ||
1533 n.equals("P") ||
1534 n.equals("RES")) {
1535 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1536 return PhoneConstants.PRESENTATION_RESTRICTED;
1537 } else if (n.equals("UNAVAILABLE") ||
1538 n.equals("UNKNOWN") ||
1539 n.equals("UNA") ||
1540 n.equals("U")) {
1541 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1542 return PhoneConstants.PRESENTATION_UNKNOWN;
1543 } else {
1544 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1545 return CNAP_SPECIAL_CASE_NO;
1546 }
1547 }
1548
1549 /**
1550 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
1551 * from the network to indicate different number presentations, convert them to
1552 * expected number and presentation values within the CallerInfo object.
1553 * @param number number we use to verify if we are in a corner case
1554 * @param presentation presentation value used to verify if we are in a corner case
1555 * @return the new String that should be used for the phone number
1556 */
1557 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
1558 String number, int presentation) {
1559 // Obviously we return number if ci == null, but still return number if
1560 // number == null, because in these cases the correct string will still be
1561 // displayed/logged after this function returns based on the presentation value.
1562 if (ci == null || number == null) return number;
1563
1564 if (DBG) {
1565 log("modifyForSpecialCnapCases: initially, number="
1566 + toLogSafePhoneNumber(number)
1567 + ", presentation=" + presentation + " ci " + ci);
1568 }
1569
1570 // "ABSENT NUMBER" is a possible value we could get from the network as the
1571 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
1572 // and fix the presentation to be the same.
1573 final String[] absentNumberValues =
1574 context.getResources().getStringArray(R.array.absent_num);
1575 if (Arrays.asList(absentNumberValues).contains(number)
1576 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
1577 number = context.getString(R.string.unknown);
1578 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
1579 }
1580
1581 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
1582 // cases only apply if we received an allowed presentation from the network, so check
1583 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
1584 // match the presentation passed in for verification (meaning we changed it previously
1585 // because it's a corner case and we're being called from a different entry point).
1586 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
1587 || (ci.numberPresentation != presentation
1588 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
1589 int cnapSpecialCase = checkCnapSpecialCases(number);
1590 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
1591 // For all special strings, change number & numberPresentation.
1592 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
1593 number = context.getString(R.string.private_num);
1594 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
1595 number = context.getString(R.string.unknown);
1596 }
1597 if (DBG) {
1598 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
1599 + "; presentation now=" + cnapSpecialCase);
1600 }
1601 ci.numberPresentation = cnapSpecialCase;
1602 }
1603 }
1604 if (DBG) {
1605 log("modifyForSpecialCnapCases: returning number string="
1606 + toLogSafePhoneNumber(number));
1607 }
1608 return number;
1609 }
1610
1611 //
1612 // Support for 3rd party phone service providers.
1613 //
1614
1615 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001616 * Check if a phone number can be route through a 3rd party
1617 * gateway. The number must be a global phone number in numerical
1618 * form (1-800-666-SEXY won't work).
1619 *
1620 * MMI codes and the like cannot be used as a dial number for the
1621 * gateway either.
1622 *
1623 * @param number To be dialed via a 3rd party gateway.
1624 * @return true If the number can be routed through the 3rd party network.
1625 */
Santos Cordon69a69192013-08-22 14:25:42 -07001626 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001627 if (TextUtils.isEmpty(number)) {
1628 return false;
1629 }
1630 number = PhoneNumberUtils.stripSeparators(number);
1631 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
1632 return false;
1633 }
1634 number = PhoneNumberUtils.extractNetworkPortion(number);
1635 return PhoneNumberUtils.isGlobalPhoneNumber(number);
1636 }
1637
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001638 /**
1639 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
1640 */
1641 /* package */ static boolean isPhoneInEcm(Phone phone) {
1642 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
Shuo Qiandd210312017-04-12 22:11:33 +00001643 return phone.isInEcm();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001644 }
1645 return false;
1646 }
1647
1648 /**
1649 * Returns the most appropriate Phone object to handle a call
1650 * to the specified number.
1651 *
1652 * @param cm the CallManager.
1653 * @param scheme the scheme from the data URI that the number originally came from.
1654 * @param number the phone number, or SIP address.
1655 */
Sailesh Nepalbfb68322013-11-07 14:07:41 -08001656 public static Phone pickPhoneBasedOnNumber(CallManager cm, String scheme, String number,
1657 String primarySipUri, ComponentName thirdPartyCallComponent) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001658 if (DBG) {
1659 log("pickPhoneBasedOnNumber: scheme " + scheme
1660 + ", number " + toLogSafePhoneNumber(number)
1661 + ", sipUri "
Sailesh Nepalbfb68322013-11-07 14:07:41 -08001662 + (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null")
1663 + ", thirdPartyCallComponent: " + thirdPartyCallComponent);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001664 }
1665
1666 if (primarySipUri != null) {
1667 Phone phone = getSipPhoneFromUri(cm, primarySipUri);
1668 if (phone != null) return phone;
1669 }
Sailesh Nepalbfb68322013-11-07 14:07:41 -08001670
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001671 return cm.getDefaultPhone();
1672 }
1673
1674 public static Phone getSipPhoneFromUri(CallManager cm, String target) {
1675 for (Phone phone : cm.getAllPhones()) {
1676 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
1677 String sipUri = ((SipPhone) phone).getSipUri();
1678 if (target.equals(sipUri)) {
1679 if (DBG) log("- pickPhoneBasedOnNumber:" +
1680 "found SipPhone! obj = " + phone + ", "
1681 + phone.getClass());
1682 return phone;
1683 }
1684 }
1685 }
1686 return null;
1687 }
1688
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001689 /**
1690 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
1691 * meaning the call is the first real incoming call the phone is having.
1692 */
1693 public static boolean isRealIncomingCall(Call.State state) {
1694 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
1695 }
1696
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001697 public static String getPresentationString(Context context, int presentation) {
1698 String name = context.getString(R.string.unknown);
1699 if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1700 name = context.getString(R.string.private_num);
1701 } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1702 name = context.getString(R.string.payphone);
1703 }
1704 return name;
1705 }
1706
1707 public static void sendViewNotificationAsync(Context context, Uri contactUri) {
1708 if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")");
1709 Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri);
1710 intent.setClassName("com.android.contacts",
1711 "com.android.contacts.ViewNotificationService");
1712 context.startService(intent);
1713 }
1714
1715 //
1716 // General phone and call state debugging/testing code
1717 //
1718
1719 /* package */ static void dumpCallState(Phone phone) {
1720 PhoneGlobals app = PhoneGlobals.getInstance();
1721 Log.d(LOG_TAG, "dumpCallState():");
1722 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
1723 + ", state = " + phone.getState());
1724
1725 StringBuilder b = new StringBuilder(128);
1726
1727 Call call = phone.getForegroundCall();
1728 b.setLength(0);
1729 b.append(" - FG call: ").append(call.getState());
1730 b.append(" isAlive ").append(call.getState().isAlive());
1731 b.append(" isRinging ").append(call.getState().isRinging());
1732 b.append(" isDialing ").append(call.getState().isDialing());
1733 b.append(" isIdle ").append(call.isIdle());
1734 b.append(" hasConnections ").append(call.hasConnections());
1735 Log.d(LOG_TAG, b.toString());
1736
1737 call = phone.getBackgroundCall();
1738 b.setLength(0);
1739 b.append(" - BG call: ").append(call.getState());
1740 b.append(" isAlive ").append(call.getState().isAlive());
1741 b.append(" isRinging ").append(call.getState().isRinging());
1742 b.append(" isDialing ").append(call.getState().isDialing());
1743 b.append(" isIdle ").append(call.isIdle());
1744 b.append(" hasConnections ").append(call.hasConnections());
1745 Log.d(LOG_TAG, b.toString());
1746
1747 call = phone.getRingingCall();
1748 b.setLength(0);
1749 b.append(" - RINGING call: ").append(call.getState());
1750 b.append(" isAlive ").append(call.getState().isAlive());
1751 b.append(" isRinging ").append(call.getState().isRinging());
1752 b.append(" isDialing ").append(call.getState().isDialing());
1753 b.append(" isIdle ").append(call.isIdle());
1754 b.append(" hasConnections ").append(call.hasConnections());
1755 Log.d(LOG_TAG, b.toString());
1756
1757
1758 final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1759 final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1760 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1761 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1762 b.setLength(0);
1763 b.append(" - hasRingingCall ").append(hasRingingCall);
1764 b.append(" hasActiveCall ").append(hasActiveCall);
1765 b.append(" hasHoldingCall ").append(hasHoldingCall);
1766 b.append(" allLinesTaken ").append(allLinesTaken);
1767 Log.d(LOG_TAG, b.toString());
1768
1769 // On CDMA phones, dump out the CdmaPhoneCallState too:
1770 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1771 if (app.cdmaPhoneCallState != null) {
1772 Log.d(LOG_TAG, " - CDMA call state: "
1773 + app.cdmaPhoneCallState.getCurrentCallState());
1774 } else {
1775 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!");
1776 }
1777 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001778 }
1779
1780 private static void log(String msg) {
1781 Log.d(LOG_TAG, msg);
1782 }
1783
1784 static void dumpCallManager() {
1785 Call call;
1786 CallManager cm = PhoneGlobals.getInstance().mCM;
1787 StringBuilder b = new StringBuilder(128);
1788
1789
1790
1791 Log.d(LOG_TAG, "############### dumpCallManager() ##############");
1792 // TODO: Don't log "cm" itself, since CallManager.toString()
1793 // already spews out almost all this same information.
1794 // We should fix CallManager.toString() to be more minimal, and
1795 // use an explicit dumpState() method for the verbose dump.
1796 // Log.d(LOG_TAG, "CallManager: " + cm
1797 // + ", state = " + cm.getState());
1798 Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
1799 b.setLength(0);
1800 call = cm.getActiveFgCall();
1801 b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
1802 b.append(call);
1803 b.append( " State: ").append(cm.getActiveFgCallState());
1804 b.append( " Conn: ").append(cm.getFgCallConnections());
1805 Log.d(LOG_TAG, b.toString());
1806 b.setLength(0);
1807 call = cm.getFirstActiveBgCall();
1808 b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
1809 b.append(call);
1810 b.append( " State: ").append(cm.getFirstActiveBgCall().getState());
1811 b.append( " Conn: ").append(cm.getBgCallConnections());
1812 Log.d(LOG_TAG, b.toString());
1813 b.setLength(0);
1814 call = cm.getFirstActiveRingingCall();
1815 b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
1816 b.append(call);
1817 b.append( " State: ").append(cm.getFirstActiveRingingCall().getState());
1818 Log.d(LOG_TAG, b.toString());
1819
1820
1821
1822 for (Phone phone : CallManager.getInstance().getAllPhones()) {
1823 if (phone != null) {
1824 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
1825 + ", state = " + phone.getState());
1826 b.setLength(0);
1827 call = phone.getForegroundCall();
1828 b.append(" - FG call: ").append(call);
1829 b.append( " State: ").append(call.getState());
1830 b.append( " Conn: ").append(call.hasConnections());
1831 Log.d(LOG_TAG, b.toString());
1832 b.setLength(0);
1833 call = phone.getBackgroundCall();
1834 b.append(" - BG call: ").append(call);
1835 b.append( " State: ").append(call.getState());
1836 b.append( " Conn: ").append(call.hasConnections());
1837 Log.d(LOG_TAG, b.toString());b.setLength(0);
1838 call = phone.getRingingCall();
1839 b.append(" - RINGING call: ").append(call);
1840 b.append( " State: ").append(call.getState());
1841 b.append( " Conn: ").append(call.hasConnections());
1842 Log.d(LOG_TAG, b.toString());
1843 }
1844 }
1845
1846 Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
1847 }
1848
1849 /**
1850 * @return if the context is in landscape orientation.
1851 */
1852 public static boolean isLandscape(Context context) {
1853 return context.getResources().getConfiguration().orientation
1854 == Configuration.ORIENTATION_LANDSCAPE;
1855 }
Andrew Leed5165b02014-12-05 15:53:58 -08001856
Nancy Chene53a0642015-03-12 11:20:12 -07001857 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
1858 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
1859 }
1860
Nancy Chen32031f42015-03-04 21:00:07 -08001861 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
1862 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
1863 }
1864
Andrew Leed5165b02014-12-05 15:53:58 -08001865 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
1866 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
1867 }
1868
1869 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1870 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08001871 // TODO: Should use some sort of special hidden flag to decorate this account as
1872 // an emergency-only account
Brad Ebingerd3edc222016-03-23 19:44:38 -07001873 String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
Brad Ebinger4fe48112016-04-13 11:21:53 -07001874 String.valueOf(phone.getFullIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07001875 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
1876 }
1877
1878 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
1879 String id, String prefix, boolean isEmergency) {
1880 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08001881 return new PhoneAccountHandle(pstnConnectionServiceName, id);
1882 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08001883
Santos Cordonf69df962015-02-03 11:15:19 -08001884 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08001885 if (phoneAccount != null
1886 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
1887 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
1888 }
1889 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1890 }
1891
1892 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001893 Phone phone = getPhoneForPhoneAccountHandle(handle);
1894 if (phone != null) {
1895 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08001896 }
1897 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
1898 }
1899
Ta-wei Yen845f6992016-06-16 12:53:46 -07001900 public static Phone getPhoneForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08001901 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
1902 return getPhoneFromIccId(handle.getId());
1903 }
1904 return null;
1905 }
1906
1907
Nancy Chene53a0642015-03-12 11:20:12 -07001908 /**
1909 * Determine if a given phone account corresponds to an active SIM
1910 *
1911 * @param sm An instance of the subscription manager so it is not recreated for each calling of
1912 * this method.
1913 * @param handle The handle for the phone account to check
1914 * @return {@code true} If there is an active SIM for this phone account,
1915 * {@code false} otherwise.
1916 */
1917 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
1918 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
1919 }
1920
Santos Cordonf69df962015-02-03 11:15:19 -08001921 private static ComponentName getPstnConnectionServiceName() {
Tony Mak4c8f3c62015-12-07 02:30:37 +00001922 return PSTN_CONNECTION_SERVICE_COMPONENT;
Santos Cordonf69df962015-02-03 11:15:19 -08001923 }
1924
Santos Cordon80855d52015-02-10 04:33:36 -08001925 private static Phone getPhoneFromIccId(String iccId) {
1926 if (!TextUtils.isEmpty(iccId)) {
1927 for (Phone phone : PhoneFactory.getPhones()) {
Brad Ebinger4fe48112016-04-13 11:21:53 -07001928 String phoneIccId = phone.getFullIccSerialNumber();
Santos Cordon80855d52015-02-10 04:33:36 -08001929 if (iccId.equals(phoneIccId)) {
1930 return phone;
1931 }
1932 }
1933 }
Santos Cordon80855d52015-02-10 04:33:36 -08001934 return null;
1935 }
1936
Stuart Scottdcf40a92014-12-09 10:45:01 -08001937 /**
1938 * Register ICC status for all phones.
1939 */
1940 static final void registerIccStatus(Handler handler, int event) {
1941 for (Phone phone : PhoneFactory.getPhones()) {
1942 IccCard sim = phone.getIccCard();
1943 if (sim != null) {
1944 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
1945 sim.registerForNetworkLocked(handler, event, phone);
1946 }
1947 }
1948 }
1949
1950 /**
1951 * Set the radio power on/off state for all phones.
1952 *
1953 * @param enabled true means on, false means off.
1954 */
1955 static final void setRadioPower(boolean enabled) {
1956 for (Phone phone : PhoneFactory.getPhones()) {
1957 phone.setRadioPower(enabled);
1958 }
1959 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001960}