blob: 31477e788c0958f2859ff5e10e198fd26befd5ba [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;
22import android.bluetooth.IBluetoothHeadsetPhone;
23import android.content.ActivityNotFoundException;
Sailesh Nepalbfb68322013-11-07 14:07:41 -080024import android.content.ComponentName;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070025import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070028import android.content.res.Configuration;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070029import android.media.AudioManager;
30import android.net.Uri;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070031import android.os.Handler;
32import android.os.Message;
33import android.os.RemoteException;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070034import android.telecom.PhoneAccount;
Andrew Leed5165b02014-12-05 15:53:58 -080035import android.telecom.PhoneAccountHandle;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070036import android.telecom.VideoProfile;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070037import android.telephony.PhoneNumberUtils;
Santos Cordonf69df962015-02-03 11:15:19 -080038import android.telephony.SubscriptionManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070039import android.text.TextUtils;
40import android.util.Log;
Andrew Leeb3ee4dc2015-01-23 17:35:00 -080041import android.view.ContextThemeWrapper;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070042import android.view.KeyEvent;
43import android.view.LayoutInflater;
44import android.view.View;
45import android.view.WindowManager;
46import android.widget.EditText;
47import android.widget.Toast;
48
49import com.android.internal.telephony.Call;
50import com.android.internal.telephony.CallManager;
51import com.android.internal.telephony.CallStateException;
52import com.android.internal.telephony.CallerInfo;
53import com.android.internal.telephony.CallerInfoAsyncQuery;
54import com.android.internal.telephony.Connection;
Stuart Scottdcf40a92014-12-09 10:45:01 -080055import com.android.internal.telephony.IccCard;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070056import com.android.internal.telephony.MmiCode;
57import com.android.internal.telephony.Phone;
58import com.android.internal.telephony.PhoneConstants;
Stuart Scottdcf40a92014-12-09 10:45:01 -080059import com.android.internal.telephony.PhoneFactory;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070060import com.android.internal.telephony.TelephonyCapabilities;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070061import com.android.internal.telephony.sip.SipPhone;
Santos Cordon69a69192013-08-22 14:25:42 -070062import com.android.phone.CallGatewayManager.RawGatewayInfo;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070063
Santos Cordon7d4ddf62013-07-10 11:58:08 -070064import java.util.Arrays;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070065import java.util.List;
66
67/**
68 * Misc utilities for the Phone app.
69 */
70public class PhoneUtils {
Brad Ebingerd3edc222016-03-23 19:44:38 -070071 public static final String EMERGENCY_ACCOUNT_HANDLE_ID = "E";
Santos Cordon7d4ddf62013-07-10 11:58:08 -070072 private static final String LOG_TAG = "PhoneUtils";
73 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
74
75 // Do not check in with VDBG = true, since that may write PII to the system log.
76 private static final boolean VDBG = false;
77
78 /** Control stack trace for Audio Mode settings */
79 private static final boolean DBG_SETAUDIOMODE_STACK = false;
80
81 /** Identifier for the "Add Call" intent extra. */
82 static final String ADD_CALL_MODE_KEY = "add_call_mode";
83
84 // Return codes from placeCall()
fionaxuf7885142016-11-27 16:08:39 -080085 public static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed
86 public static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code
87 public static final int CALL_STATUS_FAILED = 2; // The call failed
Santos Cordon7d4ddf62013-07-10 11:58:08 -070088
89 // State of the Phone's audio modes
90 // Each state can move to the other states, but within the state only certain
91 // transitions for AudioManager.setMode() are allowed.
92 static final int AUDIO_IDLE = 0; /** audio behaviour at phone idle */
93 static final int AUDIO_RINGING = 1; /** audio behaviour while ringing */
94 static final int AUDIO_OFFHOOK = 2; /** audio behaviour while in call. */
95
96 // USSD string length for MMI operations
97 static final int MIN_USSD_LEN = 1;
98 static final int MAX_USSD_LEN = 160;
99
100 /** Speaker state, persisting between wired headset connection events */
101 private static boolean sIsSpeakerEnabled = false;
102
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700103 /** Static handler for the connection/mute tracking */
104 private static ConnectionHandler mConnectionHandler;
105
106 /** Phone state changed event*/
107 private static final int PHONE_STATE_CHANGED = -1;
108
Zhihai Xua4915c72013-10-18 17:01:16 -0700109 /** check status then decide whether answerCall */
110 private static final int MSG_CHECK_STATUS_ANSWERCALL = 100;
111
112 /** poll phone DISCONNECTING status interval */
113 private static final int DISCONNECTING_POLLING_INTERVAL_MS = 200;
114
115 /** poll phone DISCONNECTING status times limit */
116 private static final int DISCONNECTING_POLLING_TIMES_LIMIT = 8;
117
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700118 /** Define for not a special CNAP string */
119 private static final int CNAP_SPECIAL_CASE_NO = -1;
120
Yorke Leee0f2b792014-10-15 12:30:44 -0700121 /**
122 * Theme to use for dialogs displayed by utility methods in this class. This is needed
123 * because these dialogs are displayed using the application context, which does not resolve
124 * the dialog theme correctly.
125 */
Zheng Zhangd889c772017-11-02 15:49:37 -0700126 private static final int THEME = com.android.internal.R.style.Theme_DeviceDefault_Dialog_Alert;
Yorke Leee0f2b792014-10-15 12:30:44 -0700127
Zhihai Xua4915c72013-10-18 17:01:16 -0700128 private static class FgRingCalls {
129 private Call fgCall;
130 private Call ringing;
131 public FgRingCalls(Call fg, Call ring) {
132 fgCall = fg;
133 ringing = ring;
134 }
135 }
136
Etan Cohen37abbab2014-03-07 16:57:03 -0800137 /** USSD information used to aggregate all USSD messages */
138 private static AlertDialog sUssdDialog = null;
139 private static StringBuilder sUssdMsg = new StringBuilder();
140
Tony Mak4c8f3c62015-12-07 02:30:37 +0000141 private static final ComponentName PSTN_CONNECTION_SERVICE_COMPONENT =
142 new ComponentName("com.android.phone",
143 "com.android.services.telephony.TelephonyConnectionService");
144
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700145 /**
146 * Handler that tracks the connections and updates the value of the
147 * Mute settings for each connection as needed.
148 */
149 private static class ConnectionHandler extends Handler {
150 @Override
151 public void handleMessage(Message msg) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700152 switch (msg.what) {
Zhihai Xua4915c72013-10-18 17:01:16 -0700153 case MSG_CHECK_STATUS_ANSWERCALL:
154 FgRingCalls frC = (FgRingCalls) msg.obj;
155 // wait for finishing disconnecting
156 // before check the ringing call state
157 if ((frC.fgCall != null) &&
158 (frC.fgCall.getState() == Call.State.DISCONNECTING) &&
159 (msg.arg1 < DISCONNECTING_POLLING_TIMES_LIMIT)) {
160 Message retryMsg =
161 mConnectionHandler.obtainMessage(MSG_CHECK_STATUS_ANSWERCALL);
162 retryMsg.arg1 = 1 + msg.arg1;
163 retryMsg.obj = msg.obj;
164 mConnectionHandler.sendMessageDelayed(retryMsg,
165 DISCONNECTING_POLLING_INTERVAL_MS);
166 // since hangupActiveCall() also accepts the ringing call
167 // check if the ringing call was already answered or not
168 // only answer it when the call still is ringing
169 } else if (frC.ringing.isRinging()) {
170 if (msg.arg1 == DISCONNECTING_POLLING_TIMES_LIMIT) {
171 Log.e(LOG_TAG, "DISCONNECTING time out");
172 }
173 answerCall(frC.ringing);
174 }
175 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700176 }
177 }
178 }
179
180 /**
181 * Register the ConnectionHandler with the phone, to receive connection events
182 */
183 public static void initializeConnectionHandler(CallManager cm) {
184 if (mConnectionHandler == null) {
185 mConnectionHandler = new ConnectionHandler();
186 }
187
188 // pass over cm as user.obj
189 cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm);
190
191 }
192
193 /** This class is never instantiated. */
194 private PhoneUtils() {
195 }
196
197 /**
198 * Answer the currently-ringing call.
199 *
200 * @return true if we answered the call, or false if there wasn't
201 * actually a ringing incoming call, or some other error occurred.
202 *
203 * @see #answerAndEndHolding(CallManager, Call)
204 * @see #answerAndEndActive(CallManager, Call)
205 */
206 /* package */ static boolean answerCall(Call ringingCall) {
207 log("answerCall(" + ringingCall + ")...");
208 final PhoneGlobals app = PhoneGlobals.getInstance();
209 final CallNotifier notifier = app.notifier;
210
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700211 final Phone phone = ringingCall.getPhone();
212 final boolean phoneIsCdma = (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA);
213 boolean answered = false;
214 IBluetoothHeadsetPhone btPhone = null;
215
216 if (phoneIsCdma) {
217 // Stop any signalInfo tone being played when a Call waiting gets answered
218 if (ringingCall.getState() == Call.State.WAITING) {
219 notifier.stopSignalInfoTone();
220 }
221 }
222
223 if (ringingCall != null && ringingCall.isRinging()) {
224 if (DBG) log("answerCall: call state = " + ringingCall.getState());
225 try {
226 if (phoneIsCdma) {
227 if (app.cdmaPhoneCallState.getCurrentCallState()
228 == CdmaPhoneCallState.PhoneCallState.IDLE) {
229 // This is the FIRST incoming call being answered.
230 // Set the Phone Call State to SINGLE_ACTIVE
231 app.cdmaPhoneCallState.setCurrentCallState(
232 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
233 } else {
234 // This is the CALL WAITING call being answered.
235 // Set the Phone Call State to CONF_CALL
236 app.cdmaPhoneCallState.setCurrentCallState(
237 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
238 // Enable "Add Call" option after answering a Call Waiting as the user
239 // should be allowed to add another call in case one of the parties
240 // drops off
241 app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
Santos Cordon13fed9f2014-09-24 13:10:34 -0700242 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700243 }
244
245 final boolean isRealIncomingCall = isRealIncomingCall(ringingCall.getState());
246
247 //if (DBG) log("sPhone.acceptCall");
248 app.mCM.acceptCall(ringingCall);
249 answered = true;
250
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700251 setAudioMode();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700252 } catch (CallStateException ex) {
253 Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
254
255 if (phoneIsCdma) {
256 // restore the cdmaPhoneCallState and btPhone.cdmaSetSecondCallState:
257 app.cdmaPhoneCallState.setCurrentCallState(
258 app.cdmaPhoneCallState.getPreviousCallState());
259 if (btPhone != null) {
260 try {
261 btPhone.cdmaSetSecondCallState(false);
262 } catch (RemoteException e) {
263 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
264 }
265 }
266 }
267 }
268 }
269 return answered;
270 }
271
272 /**
Santos Cordonde10b752013-09-19 04:11:33 -0700273 * Hangs up all active calls.
274 */
275 static void hangupAllCalls(CallManager cm) {
276 final Call ringing = cm.getFirstActiveRingingCall();
277 final Call fg = cm.getActiveFgCall();
278 final Call bg = cm.getFirstActiveBgCall();
279
280 // We go in reverse order, BG->FG->RINGING because hanging up a ringing call or an active
281 // call can move a bg call to a fg call which would force us to loop over each call
282 // several times. This ordering works best to ensure we dont have any more calls.
283 if (bg != null && !bg.isIdle()) {
284 hangup(bg);
285 }
286 if (fg != null && !fg.isIdle()) {
287 hangup(fg);
288 }
289 if (ringing != null && !ringing.isIdle()) {
290 hangupRingingCall(fg);
291 }
292 }
293
294 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700295 * Smart "hang up" helper method which hangs up exactly one connection,
296 * based on the current Phone state, as follows:
297 * <ul>
298 * <li>If there's a ringing call, hang that up.
299 * <li>Else if there's a foreground call, hang that up.
300 * <li>Else if there's a background call, hang that up.
301 * <li>Otherwise do nothing.
302 * </ul>
303 * @return true if we successfully hung up, or false
304 * if there were no active calls at all.
305 */
306 static boolean hangup(CallManager cm) {
307 boolean hungup = false;
308 Call ringing = cm.getFirstActiveRingingCall();
309 Call fg = cm.getActiveFgCall();
310 Call bg = cm.getFirstActiveBgCall();
311
312 if (!ringing.isIdle()) {
313 log("hangup(): hanging up ringing call");
314 hungup = hangupRingingCall(ringing);
315 } else if (!fg.isIdle()) {
316 log("hangup(): hanging up foreground call");
317 hungup = hangup(fg);
318 } else if (!bg.isIdle()) {
319 log("hangup(): hanging up background call");
320 hungup = hangup(bg);
321 } else {
322 // No call to hang up! This is unlikely in normal usage,
323 // since the UI shouldn't be providing an "End call" button in
324 // the first place. (But it *can* happen, rarely, if an
325 // active call happens to disconnect on its own right when the
326 // user is trying to hang up..)
327 log("hangup(): no active call to hang up");
328 }
329 if (DBG) log("==> hungup = " + hungup);
330
331 return hungup;
332 }
333
334 static boolean hangupRingingCall(Call ringing) {
335 if (DBG) log("hangup ringing call");
336 int phoneType = ringing.getPhone().getPhoneType();
337 Call.State state = ringing.getState();
338
339 if (state == Call.State.INCOMING) {
340 // Regular incoming call (with no other active calls)
341 log("hangupRingingCall(): regular incoming call: hangup()");
342 return hangup(ringing);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700343 } else {
344 // Unexpected state: the ringing call isn't INCOMING or
345 // WAITING, so there's no reason to have called
346 // hangupRingingCall() in the first place.
347 // (Presumably the incoming call went away at the exact moment
348 // we got here, so just do nothing.)
349 Log.w(LOG_TAG, "hangupRingingCall: no INCOMING or WAITING call");
350 return false;
351 }
352 }
353
354 static boolean hangupActiveCall(Call foreground) {
355 if (DBG) log("hangup active call");
356 return hangup(foreground);
357 }
358
359 static boolean hangupHoldingCall(Call background) {
360 if (DBG) log("hangup holding call");
361 return hangup(background);
362 }
363
364 /**
365 * Used in CDMA phones to end the complete Call session
366 * @param phone the Phone object.
367 * @return true if *any* call was successfully hung up
368 */
369 static boolean hangupRingingAndActive(Phone phone) {
370 boolean hungUpRingingCall = false;
371 boolean hungUpFgCall = false;
372 Call ringingCall = phone.getRingingCall();
373 Call fgCall = phone.getForegroundCall();
374
375 // Hang up any Ringing Call
376 if (!ringingCall.isIdle()) {
377 log("hangupRingingAndActive: Hang up Ringing Call");
378 hungUpRingingCall = hangupRingingCall(ringingCall);
379 }
380
381 // Hang up any Active Call
382 if (!fgCall.isIdle()) {
383 log("hangupRingingAndActive: Hang up Foreground Call");
384 hungUpFgCall = hangupActiveCall(fgCall);
385 }
386
387 return hungUpRingingCall || hungUpFgCall;
388 }
389
390 /**
391 * Trivial wrapper around Call.hangup(), except that we return a
392 * boolean success code rather than throwing CallStateException on
393 * failure.
394 *
395 * @return true if the call was successfully hung up, or false
396 * if the call wasn't actually active.
397 */
398 static boolean hangup(Call call) {
399 try {
400 CallManager cm = PhoneGlobals.getInstance().mCM;
401
402 if (call.getState() == Call.State.ACTIVE && cm.hasActiveBgCall()) {
403 // handle foreground call hangup while there is background call
404 log("- hangup(Call): hangupForegroundResumeBackground...");
405 cm.hangupForegroundResumeBackground(cm.getFirstActiveBgCall());
406 } else {
407 log("- hangup(Call): regular hangup()...");
408 call.hangup();
409 }
410 return true;
411 } catch (CallStateException ex) {
412 Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
413 }
414
415 return false;
416 }
417
418 /**
419 * Trivial wrapper around Connection.hangup(), except that we silently
420 * do nothing (rather than throwing CallStateException) if the
421 * connection wasn't actually active.
422 */
423 static void hangup(Connection c) {
424 try {
425 if (c != null) {
426 c.hangup();
427 }
428 } catch (CallStateException ex) {
429 Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
430 }
431 }
432
433 static boolean answerAndEndHolding(CallManager cm, Call ringing) {
434 if (DBG) log("end holding & answer waiting: 1");
435 if (!hangupHoldingCall(cm.getFirstActiveBgCall())) {
436 Log.e(LOG_TAG, "end holding failed!");
437 return false;
438 }
439
440 if (DBG) log("end holding & answer waiting: 2");
441 return answerCall(ringing);
442
443 }
444
445 /**
446 * Answers the incoming call specified by "ringing", and ends the currently active phone call.
447 *
448 * This method is useful when's there's an incoming call which we cannot manage with the
449 * current call. e.g. when you are having a phone call with CDMA network and has received
450 * a SIP call, then we won't expect our telephony can manage those phone calls simultaneously.
451 * Note that some types of network may allow multiple phone calls at once; GSM allows to hold
452 * an ongoing phone call, so we don't need to end the active call. The caller of this method
453 * needs to check if the network allows multiple phone calls or not.
454 *
455 * @see #answerCall(Call)
456 * @see InCallScreen#internalAnswerCall()
457 */
458 /* package */ static boolean answerAndEndActive(CallManager cm, Call ringing) {
459 if (DBG) log("answerAndEndActive()...");
460
461 // Unlike the answerCall() method, we *don't* need to stop the
462 // ringer or change audio modes here since the user is already
463 // in-call, which means that the audio mode is already set
464 // correctly, and that we wouldn't have started the ringer in the
465 // first place.
466
467 // hanging up the active call also accepts the waiting call
468 // while active call and waiting call are from the same phone
469 // i.e. both from GSM phone
Zhihai Xua4915c72013-10-18 17:01:16 -0700470 Call fgCall = cm.getActiveFgCall();
471 if (!hangupActiveCall(fgCall)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700472 Log.w(LOG_TAG, "end active call failed!");
473 return false;
474 }
475
Zhihai Xua4915c72013-10-18 17:01:16 -0700476 mConnectionHandler.removeMessages(MSG_CHECK_STATUS_ANSWERCALL);
477 Message msg = mConnectionHandler.obtainMessage(MSG_CHECK_STATUS_ANSWERCALL);
478 msg.arg1 = 1;
479 msg.obj = new FgRingCalls(fgCall, ringing);
480 mConnectionHandler.sendMessage(msg);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700481
482 return true;
483 }
484
485 /**
486 * For a CDMA phone, advance the call state upon making a new
487 * outgoing call.
488 *
489 * <pre>
490 * IDLE -> SINGLE_ACTIVE
491 * or
492 * SINGLE_ACTIVE -> THRWAY_ACTIVE
493 * </pre>
494 * @param app The phone instance.
495 */
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700496 private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app,
497 Connection connection) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700498 if (app.cdmaPhoneCallState.getCurrentCallState() ==
499 CdmaPhoneCallState.PhoneCallState.IDLE) {
500 // This is the first outgoing call. Set the Phone Call State to ACTIVE
501 app.cdmaPhoneCallState.setCurrentCallState(
502 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
503 } else {
504 // This is the second outgoing call. Set the Phone Call State to 3WAY
505 app.cdmaPhoneCallState.setCurrentCallState(
506 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700507
Santos Cordonda120f42014-08-06 04:44:34 -0700508 // TODO: Remove this code.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700509 //app.getCallModeler().setCdmaOutgoing3WayCall(connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700510 }
511 }
512
513 /**
Santos Cordon69a69192013-08-22 14:25:42 -0700514 * @see placeCall below
515 */
516 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
517 boolean isEmergencyCall) {
518 return placeCall(context, phone, number, contactRef, isEmergencyCall,
519 CallGatewayManager.EMPTY_INFO, null);
520 }
521
522 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700523 * Dial the number using the phone passed in.
524 *
525 * If the connection is establised, this method issues a sync call
526 * that may block to query the caller info.
527 * TODO: Change the logic to use the async query.
528 *
529 * @param context To perform the CallerInfo query.
530 * @param phone the Phone object.
531 * @param number to be dialed as requested by the user. This is
532 * NOT the phone number to connect to. It is used only to build the
533 * call card and to update the call log. See above for restrictions.
534 * @param contactRef that triggered the call. Typically a 'tel:'
535 * uri but can also be a 'content://contacts' one.
536 * @param isEmergencyCall indicates that whether or not this is an
537 * emergency call
538 * @param gatewayUri Is the address used to setup the connection, null
539 * if not using a gateway
Santos Cordon69a69192013-08-22 14:25:42 -0700540 * @param callGateway Class for setting gateway data on a successful call.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700541 *
542 * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
543 */
Santos Cordon69a69192013-08-22 14:25:42 -0700544 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
545 boolean isEmergencyCall, RawGatewayInfo gatewayInfo, CallGatewayManager callGateway) {
546 final Uri gatewayUri = gatewayInfo.gatewayUri;
547
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700548 if (VDBG) {
549 log("placeCall()... number: '" + number + "'"
550 + ", GW:'" + gatewayUri + "'"
551 + ", contactRef:" + contactRef
552 + ", isEmergencyCall: " + isEmergencyCall);
553 } else {
554 log("placeCall()... number: " + toLogSafePhoneNumber(number)
555 + ", GW: " + (gatewayUri != null ? "non-null" : "null")
556 + ", emergency? " + isEmergencyCall);
557 }
558 final PhoneGlobals app = PhoneGlobals.getInstance();
559
560 boolean useGateway = false;
561 if (null != gatewayUri &&
562 !isEmergencyCall &&
563 PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes.
564 useGateway = true;
565 }
566
567 int status = CALL_STATUS_DIALED;
568 Connection connection;
569 String numberToDial;
570 if (useGateway) {
571 // TODO: 'tel' should be a constant defined in framework base
572 // somewhere (it is in webkit.)
Jay Shrauner137458b2014-09-05 14:27:25 -0700573 if (null == gatewayUri || !PhoneAccount.SCHEME_TEL.equals(gatewayUri.getScheme())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700574 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
575 return CALL_STATUS_FAILED;
576 }
577
578 // We can use getSchemeSpecificPart because we don't allow #
579 // in the gateway numbers (treated a fragment delim.) However
580 // if we allow more complex gateway numbers sequence (with
581 // passwords or whatnot) that use #, this may break.
582 // TODO: Need to support MMI codes.
583 numberToDial = gatewayUri.getSchemeSpecificPart();
584 } else {
585 numberToDial = number;
586 }
587
588 // Remember if the phone state was in IDLE state before this call.
589 // After calling CallManager#dial(), getState() will return different state.
590 final boolean initiallyIdle = app.mCM.getState() == PhoneConstants.State.IDLE;
591
592 try {
Tyler Gunnc6514352015-06-02 21:46:34 -0700593 connection = app.mCM.dial(phone, numberToDial, VideoProfile.STATE_AUDIO_ONLY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700594 } catch (CallStateException ex) {
595 // CallStateException means a new outgoing call is not currently
596 // possible: either no more call slots exist, or there's another
597 // call already in the process of dialing or ringing.
598 Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
599 return CALL_STATUS_FAILED;
600
601 // Note that it's possible for CallManager.dial() to return
602 // null *without* throwing an exception; that indicates that
603 // we dialed an MMI (see below).
604 }
605
606 int phoneType = phone.getPhoneType();
607
608 // On GSM phones, null is returned for MMI codes
609 if (null == connection) {
Santos Cordonf77a3392014-07-21 19:48:10 -0700610 status = CALL_STATUS_FAILED;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700611 } else {
Tyler Gunn10f1c6a2014-01-17 12:01:11 -0800612 // Now that the call is successful, we can save the gateway info for the call
613 if (callGateway != null) {
614 callGateway.setGatewayInfoForConnection(connection, gatewayInfo);
615 }
616
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700617 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700618 updateCdmaCallStateOnNewOutgoingCall(app, connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700619 }
620
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700621 if (gatewayUri == null) {
622 // phone.dial() succeeded: we're now in a normal phone call.
623 // attach the URI to the CallerInfo Object if it is there,
624 // otherwise just attach the Uri Reference.
625 // if the uri does not have a "content" scheme, then we treat
626 // it as if it does NOT have a unique reference.
627 String content = context.getContentResolver().SCHEME_CONTENT;
628 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
629 Object userDataObject = connection.getUserData();
630 if (userDataObject == null) {
631 connection.setUserData(contactRef);
632 } else {
633 // TODO: This branch is dead code, we have
634 // just created the connection which has
635 // no user data (null) by default.
636 if (userDataObject instanceof CallerInfo) {
637 ((CallerInfo) userDataObject).contactRefUri = contactRef;
638 } else {
639 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
640 contactRef;
641 }
642 }
643 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700644 }
Santos Cordonc264cba2013-09-19 04:55:40 -0700645
Chiao Chenge365ba72013-09-26 14:18:12 -0700646 startGetCallerInfo(context, connection, null, null, gatewayInfo);
647
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700648 setAudioMode();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700649 }
650
651 return status;
652 }
653
654 /* package */ static String toLogSafePhoneNumber(String number) {
655 // For unknown number, log empty string.
656 if (number == null) {
657 return "";
658 }
659
660 if (VDBG) {
661 // When VDBG is true we emit PII.
662 return number;
663 }
664
665 // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
666 // sanitized phone numbers.
667 StringBuilder builder = new StringBuilder();
668 for (int i = 0; i < number.length(); i++) {
669 char c = number.charAt(i);
670 if (c == '-' || c == '@' || c == '.') {
671 builder.append(c);
672 } else {
673 builder.append('x');
674 }
675 }
676 return builder.toString();
677 }
678
679 /**
680 * Wrapper function to control when to send an empty Flash command to the network.
681 * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash
682 * to the network prior to placing a 3-way call for it to be successful.
683 */
684 static void sendEmptyFlash(Phone phone) {
685 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
686 Call fgCall = phone.getForegroundCall();
687 if (fgCall.getState() == Call.State.ACTIVE) {
688 // Send the empty flash
689 if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network");
690 switchHoldingAndActive(phone.getBackgroundCall());
691 }
692 }
693 }
694
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700695 static void swap() {
696 final PhoneGlobals mApp = PhoneGlobals.getInstance();
697 if (!okToSwapCalls(mApp.mCM)) {
698 // TODO: throw an error instead?
699 return;
700 }
701
702 // Swap the fg and bg calls.
703 // In the future we may provide some way for user to choose among
704 // multiple background calls, for now, always act on the first background call.
705 PhoneUtils.switchHoldingAndActive(mApp.mCM.getFirstActiveBgCall());
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700706 }
707
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700708 /**
709 * @param heldCall is the background call want to be swapped
710 */
711 static void switchHoldingAndActive(Call heldCall) {
712 log("switchHoldingAndActive()...");
713 try {
714 CallManager cm = PhoneGlobals.getInstance().mCM;
715 if (heldCall.isIdle()) {
716 // no heldCall, so it is to hold active call
717 cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall());
718 } else {
719 // has particular heldCall, so to switch
720 cm.switchHoldingAndActive(heldCall);
721 }
722 setAudioMode(cm);
723 } catch (CallStateException ex) {
724 Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
725 }
726 }
727
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700728 static void mergeCalls() {
729 mergeCalls(PhoneGlobals.getInstance().mCM);
730 }
731
732 static void mergeCalls(CallManager cm) {
733 int phoneType = cm.getFgPhone().getPhoneType();
734 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
735 log("mergeCalls(): CDMA...");
736 PhoneGlobals app = PhoneGlobals.getInstance();
737 if (app.cdmaPhoneCallState.getCurrentCallState()
738 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
739 // Set the Phone Call State to conference
740 app.cdmaPhoneCallState.setCurrentCallState(
741 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
742
743 // Send flash cmd
744 // TODO: Need to change the call from switchHoldingAndActive to
745 // something meaningful as we are not actually trying to swap calls but
746 // instead are merging two calls by sending a Flash command.
747 log("- sending flash...");
748 switchHoldingAndActive(cm.getFirstActiveBgCall());
749 }
750 } else {
751 try {
752 log("mergeCalls(): calling cm.conference()...");
753 cm.conference(cm.getFirstActiveBgCall());
754 } catch (CallStateException ex) {
755 Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
756 }
757 }
758 }
759
760 static void separateCall(Connection c) {
761 try {
762 if (DBG) log("separateCall: " + toLogSafePhoneNumber(c.getAddress()));
763 c.separate();
764 } catch (CallStateException ex) {
765 Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
766 }
767 }
768
769 /**
770 * Handle the MMIInitiate message and put up an alert that lets
771 * the user cancel the operation, if applicable.
772 *
773 * @param context context to get strings.
774 * @param mmiCode the MmiCode object being started.
775 * @param buttonCallbackMessage message to post when button is clicked.
776 * @param previousAlert a previous alert used in this activity.
777 * @return the dialog handle
778 */
779 static Dialog displayMMIInitiate(Context context,
780 MmiCode mmiCode,
781 Message buttonCallbackMessage,
782 Dialog previousAlert) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700783 log("displayMMIInitiate: " + android.telecom.Log.pii(mmiCode.toString()));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700784 if (previousAlert != null) {
785 previousAlert.dismiss();
786 }
787
788 // The UI paradigm we are using now requests that all dialogs have
789 // user interaction, and that any other messages to the user should
790 // be by way of Toasts.
791 //
792 // In adhering to this request, all MMI initiating "OK" dialogs
793 // (non-cancelable MMIs) that end up being closed when the MMI
794 // completes (thereby showing a completion dialog) are being
795 // replaced with Toasts.
796 //
797 // As a side effect, moving to Toasts for the non-cancelable MMIs
798 // also means that buttonCallbackMessage (which was tied into "OK")
799 // is no longer invokable for these dialogs. This is not a problem
800 // since the only callback messages we supported were for cancelable
801 // MMIs anyway.
802 //
803 // A cancelable MMI is really just a USSD request. The term
804 // "cancelable" here means that we can cancel the request when the
805 // system prompts us for a response, NOT while the network is
806 // processing the MMI request. Any request to cancel a USSD while
807 // the network is NOT ready for a response may be ignored.
808 //
809 // With this in mind, we replace the cancelable alert dialog with
810 // a progress dialog, displayed until we receive a request from
811 // the the network. For more information, please see the comments
812 // in the displayMMIComplete() method below.
813 //
814 // Anything that is NOT a USSD request is a normal MMI request,
815 // which will bring up a toast (desribed above).
816
817 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
818
819 if (!isCancelable) {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700820 log("displayMMIInitiate: not a USSD code, displaying status toast.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700821 CharSequence text = context.getText(R.string.mmiStarted);
822 Toast.makeText(context, text, Toast.LENGTH_SHORT)
823 .show();
824 return null;
825 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700826 log("displayMMIInitiate: running USSD code, displaying intermediate progress.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700827
828 // create the indeterminate progress dialog and display it.
Alex Hills779841a2015-10-22 13:23:28 -0400829 ProgressDialog pd = new ProgressDialog(context, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700830 pd.setMessage(context.getText(R.string.ussdRunning));
831 pd.setCancelable(false);
832 pd.setIndeterminate(true);
833 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
834
835 pd.show();
836
837 return pd;
838 }
839
840 }
841
842 /**
843 * Handle the MMIComplete message and fire off an intent to display
844 * the message.
845 *
846 * @param context context to get strings.
847 * @param mmiCode MMI result.
848 * @param previousAlert a previous alert used in this activity.
849 */
850 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
851 Message dismissCallbackMessage,
852 AlertDialog previousAlert) {
853 final PhoneGlobals app = PhoneGlobals.getInstance();
854 CharSequence text;
855 int title = 0; // title for the progress dialog, if needed.
856 MmiCode.State state = mmiCode.getState();
857
Tyler Gunn13fe2492017-05-22 14:14:20 -0700858 log("displayMMIComplete: state=" + state);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700859
860 switch (state) {
861 case PENDING:
862 // USSD code asking for feedback from user.
863 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700864 log("displayMMIComplete: using text from PENDING MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700865 break;
866 case CANCELLED:
867 text = null;
868 break;
869 case COMPLETE:
870 if (app.getPUKEntryActivity() != null) {
871 // if an attempt to unPUK the device was made, we specify
872 // the title and the message here.
873 title = com.android.internal.R.string.PinMmi;
874 text = context.getText(R.string.puk_unlocked);
875 break;
876 }
877 // All other conditions for the COMPLETE mmi state will cause
878 // the case to fall through to message logic in common with
879 // the FAILED case.
880
881 case FAILED:
882 text = mmiCode.getMessage();
Tyler Gunn13fe2492017-05-22 14:14:20 -0700883 log("displayMMIComplete (failed): using text from MMI message: '" + text + "'");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700884 break;
885 default:
886 throw new IllegalStateException("Unexpected MmiCode state: " + state);
887 }
888
889 if (previousAlert != null) {
890 previousAlert.dismiss();
891 }
892
893 // Check to see if a UI exists for the PUK activation. If it does
894 // exist, then it indicates that we're trying to unblock the PUK.
895 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
896 if (DBG) log("displaying PUK unblocking progress dialog.");
897
898 // create the progress dialog, make sure the flags and type are
899 // set correctly.
Alex Hills779841a2015-10-22 13:23:28 -0400900 ProgressDialog pd = new ProgressDialog(app, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700901 pd.setTitle(title);
902 pd.setMessage(text);
903 pd.setCancelable(false);
904 pd.setIndeterminate(true);
905 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
906 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
907
908 // display the dialog
909 pd.show();
910
911 // indicate to the Phone app that the progress dialog has
912 // been assigned for the PUK unlock / SIM READY process.
913 app.setPukEntryProgressDialog(pd);
914
SongFerngWangdfa107a2018-10-29 20:31:58 +0800915 } else if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.FAILED)) {
916 createUssdDialog(app, context, text,
917 WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
918 // In case of failure to unlock, we'll need to reset the
919 // PUK unlock activity, so that the user may try again.
920 app.setPukEntryActivity(null);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700921 } else {
922 // In case of failure to unlock, we'll need to reset the
923 // PUK unlock activity, so that the user may try again.
924 if (app.getPUKEntryActivity() != null) {
925 app.setPukEntryActivity(null);
926 }
927
928 // A USSD in a pending state means that it is still
929 // interacting with the user.
930 if (state != MmiCode.State.PENDING) {
SongFerngWangdfa107a2018-10-29 20:31:58 +0800931 createUssdDialog(app, context, text,
932 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700933 } else {
Tyler Gunn13fe2492017-05-22 14:14:20 -0700934 log("displayMMIComplete: USSD code has requested user input. Constructing input "
935 + "dialog.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700936
937 // USSD MMI code that is interacting with the user. The
938 // basic set of steps is this:
939 // 1. User enters a USSD request
940 // 2. We recognize the request and displayMMIInitiate
941 // (above) creates a progress dialog.
942 // 3. Request returns and we get a PENDING or COMPLETE
943 // message.
944 // 4. These MMI messages are caught in the PhoneApp
945 // (onMMIComplete) and the InCallScreen
946 // (mHandler.handleMessage) which bring up this dialog
947 // and closes the original progress dialog,
948 // respectively.
949 // 5. If the message is anything other than PENDING,
950 // we are done, and the alert dialog (directly above)
951 // displays the outcome.
952 // 6. If the network is requesting more information from
953 // the user, the MMI will be in a PENDING state, and
954 // we display this dialog with the message.
955 // 7. User input, or cancel requests result in a return
956 // to step 1. Keep in mind that this is the only
957 // time that a USSD should be canceled.
958
959 // inflate the layout with the scrolling text area for the dialog.
Andrew Leeb3ee4dc2015-01-23 17:35:00 -0800960 ContextThemeWrapper contextThemeWrapper =
961 new ContextThemeWrapper(context, R.style.DialerAlertDialogTheme);
962 LayoutInflater inflater = (LayoutInflater) contextThemeWrapper.getSystemService(
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700963 Context.LAYOUT_INFLATER_SERVICE);
964 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
965
966 // get the input field.
967 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
968
969 // specify the dialog's click listener, with SEND and CANCEL logic.
970 final DialogInterface.OnClickListener mUSSDDialogListener =
971 new DialogInterface.OnClickListener() {
972 public void onClick(DialogInterface dialog, int whichButton) {
973 switch (whichButton) {
974 case DialogInterface.BUTTON_POSITIVE:
975 // As per spec 24.080, valid length of ussd string
976 // is 1 - 160. If length is out of the range then
977 // display toast message & Cancel MMI operation.
978 if (inputText.length() < MIN_USSD_LEN
979 || inputText.length() > MAX_USSD_LEN) {
980 Toast.makeText(app,
981 app.getResources().getString(R.string.enter_input,
982 MIN_USSD_LEN, MAX_USSD_LEN),
983 Toast.LENGTH_LONG).show();
984 if (mmiCode.isCancelable()) {
985 mmiCode.cancel();
986 }
987 } else {
988 phone.sendUssdResponse(inputText.getText().toString());
989 }
990 break;
991 case DialogInterface.BUTTON_NEGATIVE:
992 if (mmiCode.isCancelable()) {
993 mmiCode.cancel();
994 }
995 break;
996 }
997 }
998 };
999
1000 // build the dialog
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001001 final AlertDialog newDialog = new AlertDialog.Builder(contextThemeWrapper)
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001002 .setMessage(text)
1003 .setView(dialogView)
1004 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
1005 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
1006 .setCancelable(false)
1007 .create();
1008
1009 // attach the key listener to the dialog's input field and make
1010 // sure focus is set.
1011 final View.OnKeyListener mUSSDDialogInputListener =
1012 new View.OnKeyListener() {
1013 public boolean onKey(View v, int keyCode, KeyEvent event) {
1014 switch (keyCode) {
1015 case KeyEvent.KEYCODE_CALL:
1016 case KeyEvent.KEYCODE_ENTER:
1017 if(event.getAction() == KeyEvent.ACTION_DOWN) {
1018 phone.sendUssdResponse(inputText.getText().toString());
1019 newDialog.dismiss();
1020 }
1021 return true;
1022 }
1023 return false;
1024 }
1025 };
1026 inputText.setOnKeyListener(mUSSDDialogInputListener);
1027 inputText.requestFocus();
1028
1029 // set the window properties of the dialog
1030 newDialog.getWindow().setType(
1031 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1032 newDialog.getWindow().addFlags(
1033 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1034
1035 // now show the dialog!
1036 newDialog.show();
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001037
1038 newDialog.getButton(DialogInterface.BUTTON_POSITIVE)
1039 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
1040 newDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
1041 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001042 }
1043 }
1044 }
1045
SongFerngWangdfa107a2018-10-29 20:31:58 +08001046 private static void createUssdDialog(PhoneGlobals app, Context context, CharSequence text,
1047 int windowType) {
1048 log("displayMMIComplete: MMI code has finished running.");
1049
1050 log("displayMMIComplete: Extended NW displayMMIInitiate (" + text + ")");
1051 if (text == null || text.length() == 0) {
1052 return;
1053 }
1054
1055 // displaying system alert dialog on the screen instead of
1056 // using another activity to display the message. This
1057 // places the message at the forefront of the UI.
1058
1059 if (sUssdDialog == null) {
1060 sUssdDialog = new AlertDialog.Builder(context, THEME)
1061 .setPositiveButton(R.string.ok, null)
1062 .setCancelable(true)
1063 .setOnDismissListener(new DialogInterface.OnDismissListener() {
1064 @Override
1065 public void onDismiss(DialogInterface dialog) {
1066 sUssdMsg.setLength(0);
1067 }
1068 })
1069 .create();
1070
1071 sUssdDialog.getWindow().setType(windowType);
1072 sUssdDialog.getWindow().addFlags(
1073 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1074 }
1075 if (sUssdMsg.length() != 0) {
1076 sUssdMsg
1077 .insert(0, "\n")
1078 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
1079 .insert(0, "\n");
1080 }
1081 sUssdMsg.insert(0, text);
1082 sUssdDialog.setMessage(sUssdMsg.toString());
1083 sUssdDialog.show();
1084 }
1085
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001086 /**
1087 * Cancels the current pending MMI operation, if applicable.
1088 * @return true if we canceled an MMI operation, or false
1089 * if the current pending MMI wasn't cancelable
1090 * or if there was no current pending MMI at all.
1091 *
1092 * @see displayMMIInitiate
1093 */
1094 static boolean cancelMmiCode(Phone phone) {
1095 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
1096 int count = pendingMmis.size();
1097 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
1098
1099 boolean canceled = false;
1100 if (count > 0) {
1101 // assume that we only have one pending MMI operation active at a time.
1102 // I don't think it's possible to enter multiple MMI codes concurrently
1103 // in the phone UI, because during the MMI operation, an Alert panel
1104 // is displayed, which prevents more MMI code from being entered.
1105 MmiCode mmiCode = pendingMmis.get(0);
1106 if (mmiCode.isCancelable()) {
1107 mmiCode.cancel();
1108 canceled = true;
1109 }
1110 }
1111 return canceled;
1112 }
1113
1114 public static class VoiceMailNumberMissingException extends Exception {
1115 VoiceMailNumberMissingException() {
1116 super();
1117 }
1118
1119 VoiceMailNumberMissingException(String msg) {
1120 super(msg);
1121 }
1122 }
1123
1124 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001125 * Gets the phone number to be called from an intent. Requires a Context
1126 * to access the contacts database, and a Phone to access the voicemail
1127 * number.
1128 *
1129 * <p>If <code>phone</code> is <code>null</code>, the function will return
1130 * <code>null</code> for <code>voicemail:</code> URIs;
1131 * if <code>context</code> is <code>null</code>, the function will return
1132 * <code>null</code> for person/phone URIs.</p>
1133 *
1134 * <p>If the intent contains a <code>sip:</code> URI, the returned
1135 * "number" is actually the SIP address.
1136 *
1137 * @param context a context to use (or
1138 * @param intent the intent
1139 *
1140 * @throws VoiceMailNumberMissingException if <code>intent</code> contains
1141 * a <code>voicemail:</code> URI, but <code>phone</code> does not
1142 * have a voicemail number set.
1143 *
1144 * @return the phone number (or SIP address) that would be called by the intent,
1145 * or <code>null</code> if the number cannot be found.
1146 */
1147 private static String getNumberFromIntent(Context context, Intent intent)
1148 throws VoiceMailNumberMissingException {
1149 Uri uri = intent.getData();
1150 String scheme = uri.getScheme();
1151
1152 // The sip: scheme is simple: just treat the rest of the URI as a
1153 // SIP address.
Jay Shrauner137458b2014-09-05 14:27:25 -07001154 if (PhoneAccount.SCHEME_SIP.equals(scheme)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001155 return uri.getSchemeSpecificPart();
1156 }
1157
1158 // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
1159 // the other cases (i.e. tel: and voicemail: and contact: URIs.)
1160
1161 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
1162
1163 // Check for a voicemail-dialing request. If the voicemail number is
1164 // empty, throw a VoiceMailNumberMissingException.
Jay Shrauner137458b2014-09-05 14:27:25 -07001165 if (PhoneAccount.SCHEME_VOICEMAIL.equals(scheme) &&
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001166 (number == null || TextUtils.isEmpty(number)))
1167 throw new VoiceMailNumberMissingException();
1168
1169 return number;
1170 }
1171
1172 /**
1173 * Returns the caller-id info corresponding to the specified Connection.
1174 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
1175 * extract a phone number from the specified Connection, and feed that
1176 * number into CallerInfo.getCallerInfo().)
1177 *
1178 * The returned CallerInfo may be null in certain error cases, like if the
1179 * specified Connection was null, or if we weren't able to get a valid
1180 * phone number from the Connection.
1181 *
1182 * Finally, if the getCallerInfo() call did succeed, we save the resulting
1183 * CallerInfo object in the "userData" field of the Connection.
1184 *
1185 * NOTE: This API should be avoided, with preference given to the
1186 * asynchronous startGetCallerInfo API.
1187 */
1188 static CallerInfo getCallerInfo(Context context, Connection c) {
1189 CallerInfo info = null;
1190
1191 if (c != null) {
1192 //See if there is a URI attached. If there is, this means
1193 //that there is no CallerInfo queried yet, so we'll need to
1194 //replace the URI with a full CallerInfo object.
1195 Object userDataObject = c.getUserData();
1196 if (userDataObject instanceof Uri) {
1197 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1198 if (info != null) {
1199 c.setUserData(info);
1200 }
1201 } else {
1202 if (userDataObject instanceof CallerInfoToken) {
1203 //temporary result, while query is running
1204 info = ((CallerInfoToken) userDataObject).currentInfo;
1205 } else {
1206 //final query result
1207 info = (CallerInfo) userDataObject;
1208 }
1209 if (info == null) {
1210 // No URI, or Existing CallerInfo, so we'll have to make do with
1211 // querying a new CallerInfo using the connection's phone number.
1212 String number = c.getAddress();
1213
1214 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
1215
1216 if (!TextUtils.isEmpty(number)) {
1217 info = CallerInfo.getCallerInfo(context, number);
1218 if (info != null) {
1219 c.setUserData(info);
1220 }
1221 }
1222 }
1223 }
1224 }
1225 return info;
1226 }
1227
1228 /**
1229 * Class returned by the startGetCallerInfo call to package a temporary
1230 * CallerInfo Object, to be superceded by the CallerInfo Object passed
1231 * into the listener when the query with token mAsyncQueryToken is complete.
1232 */
1233 public static class CallerInfoToken {
1234 /**indicates that there will no longer be updates to this request.*/
1235 public boolean isFinal;
1236
1237 public CallerInfo currentInfo;
1238 public CallerInfoAsyncQuery asyncQuery;
1239 }
1240
1241 /**
1242 * Start a CallerInfo Query based on the earliest connection in the call.
1243 */
1244 static CallerInfoToken startGetCallerInfo(Context context, Call call,
1245 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1246 Connection conn = null;
1247 int phoneType = call.getPhone().getPhoneType();
1248 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1249 conn = call.getLatestConnection();
1250 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001251 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07001252 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001253 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001254 conn = call.getEarliestConnection();
1255 } else {
1256 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1257 }
1258
1259 return startGetCallerInfo(context, conn, listener, cookie);
1260 }
1261
Chiao Chenge365ba72013-09-26 14:18:12 -07001262 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1263 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1264 return startGetCallerInfo(context, c, listener, cookie, null);
1265 }
1266
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001267 /**
1268 * place a temporary callerinfo object in the hands of the caller and notify
1269 * caller when the actual query is done.
1270 */
1271 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -07001272 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
1273 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001274 CallerInfoToken cit;
1275
1276 if (c == null) {
1277 //TODO: perhaps throw an exception here.
1278 cit = new CallerInfoToken();
1279 cit.asyncQuery = null;
1280 return cit;
1281 }
1282
1283 Object userDataObject = c.getUserData();
1284
1285 // There are now 3 states for the Connection's userData object:
1286 //
1287 // (1) Uri - query has not been executed yet
1288 //
1289 // (2) CallerInfoToken - query is executing, but has not completed.
1290 //
1291 // (3) CallerInfo - query has executed.
1292 //
1293 // In each case we have slightly different behaviour:
1294 // 1. If the query has not been executed yet (Uri or null), we start
1295 // query execution asynchronously, and note it by attaching a
1296 // CallerInfoToken as the userData.
1297 // 2. If the query is executing (CallerInfoToken), we've essentially
1298 // reached a state where we've received multiple requests for the
1299 // same callerInfo. That means that once the query is complete,
1300 // we'll need to execute the additional listener requested.
1301 // 3. If the query has already been executed (CallerInfo), we just
1302 // return the CallerInfo object as expected.
1303 // 4. Regarding isFinal - there are cases where the CallerInfo object
1304 // will not be attached, like when the number is empty (caller id
1305 // blocking). This flag is used to indicate that the
1306 // CallerInfoToken object is going to be permanent since no
1307 // query results will be returned. In the case where a query
1308 // has been completed, this flag is used to indicate to the caller
1309 // that the data will not be updated since it is valid.
1310 //
1311 // Note: For the case where a number is NOT retrievable, we leave
1312 // the CallerInfo as null in the CallerInfoToken. This is
1313 // something of a departure from the original code, since the old
1314 // code manufactured a CallerInfo object regardless of the query
1315 // outcome. From now on, we will append an empty CallerInfo
1316 // object, to mirror previous behaviour, and to avoid Null Pointer
1317 // Exceptions.
1318
1319 if (userDataObject instanceof Uri) {
1320 // State (1): query has not been executed yet
1321
1322 //create a dummy callerinfo, populate with what we know from URI.
1323 cit = new CallerInfoToken();
1324 cit.currentInfo = new CallerInfo();
1325 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1326 (Uri) userDataObject, sCallerInfoQueryListener, c);
1327 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1328 cit.isFinal = false;
1329
1330 c.setUserData(cit);
1331
1332 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1333
1334 } else if (userDataObject == null) {
1335 // No URI, or Existing CallerInfo, so we'll have to make do with
1336 // querying a new CallerInfo using the connection's phone number.
1337 String number = c.getAddress();
1338
Chiao Cheng685dcb62013-10-02 11:51:06 -07001339 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -07001340 // Gateway number, the connection number is actually the gateway number.
1341 // need to lookup via dialed number.
1342 number = info.trueNumber;
1343 }
1344
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001345 if (DBG) {
1346 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
1347 log("- number (address): " + toLogSafePhoneNumber(number));
1348 log("- c: " + c);
1349 log("- phone: " + c.getCall().getPhone());
1350 int phoneType = c.getCall().getPhone().getPhoneType();
1351 log("- phoneType: " + phoneType);
1352 switch (phoneType) {
1353 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
1354 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -07001355 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001356 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
1357 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001358 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
1359 log(" ==> PHONE_TYPE_THIRD_PARTY");
1360 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001361 default: log(" ==> Unknown phone type"); break;
1362 }
1363 }
1364
1365 cit = new CallerInfoToken();
1366 cit.currentInfo = new CallerInfo();
1367
1368 // Store CNAP information retrieved from the Connection (we want to do this
1369 // here regardless of whether the number is empty or not).
1370 cit.currentInfo.cnapName = c.getCnapName();
1371 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1372 // by ContactInfo later
1373 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1374 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1375
1376 if (VDBG) {
1377 log("startGetCallerInfo: number = " + number);
1378 log("startGetCallerInfo: CNAP Info from FW(1): name="
1379 + cit.currentInfo.cnapName
1380 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1381 }
1382
1383 // handling case where number is null (caller id hidden) as well.
1384 if (!TextUtils.isEmpty(number)) {
1385 // Check for special CNAP cases and modify the CallerInfo accordingly
1386 // to be sure we keep the right information to display/log later
1387 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
1388 cit.currentInfo.numberPresentation);
1389
1390 cit.currentInfo.phoneNumber = number;
1391 // For scenarios where we may receive a valid number from the network but a
1392 // restricted/unavailable presentation, we do not want to perform a contact query
1393 // (see note on isFinal above). So we set isFinal to true here as well.
1394 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1395 cit.isFinal = true;
1396 } else {
1397 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
1398 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1399 number, sCallerInfoQueryListener, c);
1400 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1401 cit.isFinal = false;
1402 }
1403 } else {
1404 // This is the case where we are querying on a number that
1405 // is null or empty, like a caller whose caller id is
1406 // blocked or empty (CLIR). The previous behaviour was to
1407 // throw a null CallerInfo object back to the user, but
1408 // this departure is somewhat cleaner.
1409 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1410 cit.isFinal = true; // please see note on isFinal, above.
1411 }
1412
1413 c.setUserData(cit);
1414
1415 if (DBG) {
1416 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
1417 }
1418
1419 } else if (userDataObject instanceof CallerInfoToken) {
1420 // State (2): query is executing, but has not completed.
1421
1422 // just tack on this listener to the queue.
1423 cit = (CallerInfoToken) userDataObject;
1424
1425 // handling case where number is null (caller id hidden) as well.
1426 if (cit.asyncQuery != null) {
1427 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1428
1429 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1430 listener.getClass().toString());
1431 } else {
1432 // handling case where number/name gets updated later on by the network
1433 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -07001434
1435 if (info != null) {
1436 // Gateway number, the connection number is actually the gateway number.
1437 // need to lookup via dialed number.
1438 updatedNumber = info.trueNumber;
1439 }
1440
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001441 if (DBG) {
1442 log("startGetCallerInfo: updatedNumber initially = "
1443 + toLogSafePhoneNumber(updatedNumber));
1444 }
1445 if (!TextUtils.isEmpty(updatedNumber)) {
1446 // Store CNAP information retrieved from the Connection
1447 cit.currentInfo.cnapName = c.getCnapName();
1448 // This can still get overwritten by ContactInfo
1449 cit.currentInfo.name = cit.currentInfo.cnapName;
1450 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1451 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1452
1453 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1454 updatedNumber, cit.currentInfo.numberPresentation);
1455
1456 cit.currentInfo.phoneNumber = updatedNumber;
1457 if (DBG) {
1458 log("startGetCallerInfo: updatedNumber="
1459 + toLogSafePhoneNumber(updatedNumber));
1460 }
1461 if (VDBG) {
1462 log("startGetCallerInfo: CNAP Info from FW(2): name="
1463 + cit.currentInfo.cnapName
1464 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1465 } else if (DBG) {
1466 log("startGetCallerInfo: CNAP Info from FW(2)");
1467 }
1468 // For scenarios where we may receive a valid number from the network but a
1469 // restricted/unavailable presentation, we do not want to perform a contact query
1470 // (see note on isFinal above). So we set isFinal to true here as well.
1471 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1472 cit.isFinal = true;
1473 } else {
1474 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1475 updatedNumber, sCallerInfoQueryListener, c);
1476 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1477 cit.isFinal = false;
1478 }
1479 } else {
1480 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1481 if (cit.currentInfo == null) {
1482 cit.currentInfo = new CallerInfo();
1483 }
1484 // Store CNAP information retrieved from the Connection
1485 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
1486 // overwritten by ContactInfo
1487 cit.currentInfo.name = cit.currentInfo.cnapName;
1488 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1489 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1490
1491 if (VDBG) {
1492 log("startGetCallerInfo: CNAP Info from FW(3): name="
1493 + cit.currentInfo.cnapName
1494 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1495 } else if (DBG) {
1496 log("startGetCallerInfo: CNAP Info from FW(3)");
1497 }
1498 cit.isFinal = true; // please see note on isFinal, above.
1499 }
1500 }
1501 } else {
1502 // State (3): query is complete.
1503
1504 // The connection's userDataObject is a full-fledged
1505 // CallerInfo instance. Wrap it in a CallerInfoToken and
1506 // return it to the user.
1507
1508 cit = new CallerInfoToken();
1509 cit.currentInfo = (CallerInfo) userDataObject;
1510 cit.asyncQuery = null;
1511 cit.isFinal = true;
1512 // since the query is already done, call the listener.
1513 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1514 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
1515 }
1516 return cit;
1517 }
1518
1519 /**
1520 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
1521 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
1522 */
1523 private static final int QUERY_TOKEN = -1;
1524 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1525 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1526 /**
1527 * When the query completes, we stash the resulting CallerInfo
1528 * object away in the Connection's "userData" (where it will
1529 * later be retrieved by the in-call UI.)
1530 */
1531 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1532 if (DBG) log("query complete, updating connection.userdata");
1533 Connection conn = (Connection) cookie;
1534
1535 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1536 // If no ContactInfo, then we want to use CNAP information coming from network
1537 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1538 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1539 // If the number presentation has not been set by
1540 // the ContactInfo, use the one from the
1541 // connection.
1542
1543 // TODO: Need a new util method to merge the info
1544 // from the Connection in a CallerInfo object.
1545 // Here 'ci' is a new CallerInfo instance read
1546 // from the DB. It has lost all the connection
1547 // info preset before the query (see PhoneUtils
1548 // line 1334). We should have a method to merge
1549 // back into this new instance the info from the
1550 // connection object not set by the DB. If the
1551 // Connection already has a CallerInfo instance in
1552 // userData, then we could use this instance to
1553 // fill 'ci' in. The same routine could be used in
1554 // PhoneUtils.
1555 if (0 == ci.numberPresentation) {
1556 ci.numberPresentation = conn.getNumberPresentation();
1557 }
1558 } else {
1559 // No matching contact was found for this number.
1560 // Return a new CallerInfo based solely on the CNAP
1561 // information from the network.
1562
1563 CallerInfo newCi = getCallerInfo(null, conn);
1564
1565 // ...but copy over the (few) things we care about
1566 // from the original CallerInfo object:
1567 if (newCi != null) {
1568 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1569 newCi.geoDescription = ci.geoDescription; // To get geo description string
1570 ci = newCi;
1571 }
1572 }
1573
1574 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1575 conn.setUserData(ci);
1576 }
1577 };
1578
1579
1580 /**
1581 * Returns a single "name" for the specified given a CallerInfo object.
1582 * If the name is null, return defaultString as the default value, usually
1583 * context.getString(R.string.unknown).
1584 */
1585 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1586 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1587
1588 String compactName = null;
1589 if (ci != null) {
1590 if (TextUtils.isEmpty(ci.name)) {
1591 // Perform any modifications for special CNAP cases to
1592 // the phone number being displayed, if applicable.
1593 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1594 ci.numberPresentation);
1595 } else {
1596 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1597 compactName = ci.name;
1598 }
1599 }
1600
1601 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1602 // If we're still null/empty here, then check if we have a presentation
1603 // string that takes precedence that we could return, otherwise display
1604 // "unknown" string.
1605 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1606 compactName = context.getString(R.string.private_num);
1607 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1608 compactName = context.getString(R.string.payphone);
1609 } else {
1610 compactName = context.getString(R.string.unknown);
1611 }
1612 }
1613 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1614 return compactName;
1615 }
1616
1617 /**
1618 * Returns true if the specified Call is a "conference call", meaning
1619 * that it owns more than one Connection object. This information is
1620 * used to trigger certain UI changes that appear when a conference
1621 * call is active (like displaying the label "Conference call", and
1622 * enabling the "Manage conference" UI.)
1623 *
1624 * Watch out: This method simply checks the number of Connections,
1625 * *not* their states. So if a Call has (for example) one ACTIVE
1626 * connection and one DISCONNECTED connection, this method will return
1627 * true (which is unintuitive, since the Call isn't *really* a
1628 * conference call any more.)
1629 *
1630 * @return true if the specified call has more than one connection (in any state.)
1631 */
1632 static boolean isConferenceCall(Call call) {
1633 // CDMA phones don't have the same concept of "conference call" as
1634 // GSM phones do; there's no special "conference call" state of
1635 // the UI or a "manage conference" function. (Instead, when
1636 // you're in a 3-way call, all we can do is display the "generic"
1637 // state of the UI.) So as far as the in-call UI is concerned,
1638 // Conference corresponds to generic display.
1639 final PhoneGlobals app = PhoneGlobals.getInstance();
1640 int phoneType = call.getPhone().getPhoneType();
1641 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1642 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
1643 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
1644 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1645 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
1646 return true;
1647 }
1648 } else {
1649 List<Connection> connections = call.getConnections();
1650 if (connections != null && connections.size() > 1) {
1651 return true;
1652 }
1653 }
1654 return false;
1655
1656 // TODO: We may still want to change the semantics of this method
1657 // to say that a given call is only really a conference call if
1658 // the number of ACTIVE connections, not the total number of
1659 // connections, is greater than one. (See warning comment in the
1660 // javadoc above.)
1661 // Here's an implementation of that:
1662 // if (connections == null) {
1663 // return false;
1664 // }
1665 // int numActiveConnections = 0;
1666 // for (Connection conn : connections) {
1667 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
1668 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1669 // if (numActiveConnections > 1) {
1670 // return true;
1671 // }
1672 // }
1673 // return false;
1674 }
1675
1676 /**
1677 * Launch the Dialer to start a new call.
1678 * This is just a wrapper around the ACTION_DIAL intent.
1679 */
1680 /* package */ static boolean startNewCall(final CallManager cm) {
1681 final PhoneGlobals app = PhoneGlobals.getInstance();
1682
1683 // Sanity-check that this is OK given the current state of the phone.
1684 if (!okToAddCall(cm)) {
1685 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1686 dumpCallManager();
1687 return false;
1688 }
1689
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001690 Intent intent = new Intent(Intent.ACTION_DIAL);
1691 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1692
1693 // when we request the dialer come up, we also want to inform
1694 // it that we're going through the "add call" option from the
1695 // InCallScreen / PhoneUtils.
1696 intent.putExtra(ADD_CALL_MODE_KEY, true);
1697 try {
1698 app.startActivity(intent);
1699 } catch (ActivityNotFoundException e) {
1700 // This is rather rare but possible.
1701 // Note: this method is used even when the phone is encrypted. At that moment
1702 // the system may not find any Activity which can accept this Intent.
1703 Log.e(LOG_TAG, "Activity for adding calls isn't found.");
1704 return false;
1705 }
1706
1707 return true;
1708 }
1709
1710 /**
1711 * Turns on/off speaker.
1712 *
1713 * @param context Context
1714 * @param flag True when speaker should be on. False otherwise.
1715 * @param store True when the settings should be stored in the device.
1716 */
1717 /* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1718 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
1719 final PhoneGlobals app = PhoneGlobals.getInstance();
1720
1721 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1722 audioManager.setSpeakerphoneOn(flag);
1723
1724 // record the speaker-enable value
1725 if (store) {
1726 sIsSpeakerEnabled = flag;
1727 }
1728
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001729 // We also need to make a fresh call to PhoneApp.updateWakeState()
1730 // any time the speaker state changes, since the screen timeout is
1731 // sometimes different depending on whether or not the speaker is
1732 // in use.
1733 app.updateWakeState();
1734
Hariprasad Jayakumareee6a9e2014-04-25 15:33:13 -07001735 app.mCM.setEchoSuppressionEnabled();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001736 }
1737
1738 /**
1739 * Restore the speaker mode, called after a wired headset disconnect
1740 * event.
1741 */
1742 static void restoreSpeakerMode(Context context) {
1743 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1744
1745 // change the mode if needed.
1746 if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1747 turnOnSpeaker(context, sIsSpeakerEnabled, false);
1748 }
1749 }
1750
1751 static boolean isSpeakerOn(Context context) {
1752 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1753 return audioManager.isSpeakerphoneOn();
1754 }
1755
Santos Cordonc264cba2013-09-19 04:55:40 -07001756 static boolean isInEmergencyCall(CallManager cm) {
Brad Ebingerbaeabcf2016-04-25 13:11:40 -07001757 Call fgCall = cm.getActiveFgCall();
1758 // isIdle includes checks for the DISCONNECTING/DISCONNECTED state.
1759 if(!fgCall.isIdle()) {
1760 for (Connection cn : fgCall.getConnections()) {
1761 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
1762 cn.getAddress())) {
1763 return true;
1764 }
Santos Cordonc264cba2013-09-19 04:55:40 -07001765 }
1766 }
1767 return false;
1768 }
1769
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001770 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001771 * Get the mute state of foreground phone, which has the current
1772 * foreground call
1773 */
1774 static boolean getMute() {
Santos Cordonbb2bcef2014-08-05 19:08:10 -07001775 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001776 }
1777
1778 /* package */ static void setAudioMode() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001779 }
1780
1781 /**
1782 * Sets the audio mode per current phone state.
1783 */
1784 /* package */ static void setAudioMode(CallManager cm) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001785 }
1786
1787 /**
1788 * Look for ANY connections on the phone that qualify as being
1789 * disconnected.
1790 *
1791 * @return true if we find a connection that is disconnected over
1792 * all the phone's call objects.
1793 */
1794 /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1795 return hasDisconnectedConnections(phone.getForegroundCall()) ||
1796 hasDisconnectedConnections(phone.getBackgroundCall()) ||
1797 hasDisconnectedConnections(phone.getRingingCall());
1798 }
1799
1800 /**
1801 * Iterate over all connections in a call to see if there are any
1802 * that are not alive (disconnected or idle).
1803 *
1804 * @return true if we find a connection that is disconnected, and
1805 * pending removal via
Amit Mahajan6d83e5e2015-12-14 13:24:48 -08001806 * {@link com.android.internal.telephony.Call#clearDisconnected()}.
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001807 */
1808 private static final boolean hasDisconnectedConnections(Call call) {
1809 // look through all connections for non-active ones.
1810 for (Connection c : call.getConnections()) {
1811 if (!c.isAlive()) {
1812 return true;
1813 }
1814 }
1815 return false;
1816 }
1817
1818 //
1819 // Misc UI policy helper functions
1820 //
1821
1822 /**
Christine Chenaf2fd0a2013-09-13 16:27:40 -07001823 * @return true if we're allowed to hold calls, given the current
1824 * state of the Phone.
1825 */
1826 /* package */ static boolean okToHoldCall(CallManager cm) {
1827 final Call fgCall = cm.getActiveFgCall();
1828 final boolean hasHoldingCall = cm.hasActiveBgCall();
1829 final Call.State fgCallState = fgCall.getState();
1830
1831 // The "Hold" control is disabled entirely if there's
1832 // no way to either hold or unhold in the current state.
1833 final boolean okToHold = (fgCallState == Call.State.ACTIVE) && !hasHoldingCall;
1834 final boolean okToUnhold = cm.hasActiveBgCall() && (fgCallState == Call.State.IDLE);
1835 final boolean canHold = okToHold || okToUnhold;
1836
1837 return canHold;
1838 }
1839
1840 /**
1841 * @return true if we support holding calls, given the current
1842 * state of the Phone.
1843 */
1844 /* package */ static boolean okToSupportHold(CallManager cm) {
1845 boolean supportsHold = false;
1846
1847 final Call fgCall = cm.getActiveFgCall();
1848 final boolean hasHoldingCall = cm.hasActiveBgCall();
1849 final Call.State fgCallState = fgCall.getState();
1850
1851 if (TelephonyCapabilities.supportsHoldAndUnhold(fgCall.getPhone())) {
1852 // This phone has the concept of explicit "Hold" and "Unhold" actions.
1853 supportsHold = true;
1854 } else if (hasHoldingCall && (fgCallState == Call.State.IDLE)) {
1855 // Even when foreground phone device doesn't support hold/unhold, phone devices
1856 // for background holding calls may do.
1857 final Call bgCall = cm.getFirstActiveBgCall();
1858 if (bgCall != null &&
1859 TelephonyCapabilities.supportsHoldAndUnhold(bgCall.getPhone())) {
1860 supportsHold = true;
1861 }
1862 }
1863 return supportsHold;
1864 }
1865
1866 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001867 * @return true if we're allowed to swap calls, given the current
1868 * state of the Phone.
1869 */
1870 /* package */ static boolean okToSwapCalls(CallManager cm) {
1871 int phoneType = cm.getDefaultPhone().getPhoneType();
1872 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1873 // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
1874 // state by either accepting a Call Waiting or by merging two calls
1875 PhoneGlobals app = PhoneGlobals.getInstance();
1876 return (app.cdmaPhoneCallState.getCurrentCallState()
1877 == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
1878 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001879 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07001880 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001881 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001882 // GSM: "Swap" is available if both lines are in use and there's no
1883 // incoming call. (Actually we need to verify that the active
1884 // call really is in the ACTIVE state and the holding call really
1885 // is in the HOLDING state, since you *can't* actually swap calls
1886 // when the foreground call is DIALING or ALERTING.)
1887 return !cm.hasActiveRingingCall()
1888 && (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
1889 && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
1890 } else {
1891 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1892 }
1893 }
1894
1895 /**
1896 * @return true if we're allowed to merge calls, given the current
1897 * state of the Phone.
1898 */
1899 /* package */ static boolean okToMergeCalls(CallManager cm) {
1900 int phoneType = cm.getFgPhone().getPhoneType();
1901 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1902 // CDMA: "Merge" is enabled only when the user is in a 3Way call.
1903 PhoneGlobals app = PhoneGlobals.getInstance();
1904 return ((app.cdmaPhoneCallState.getCurrentCallState()
1905 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1906 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
1907 } else {
1908 // GSM: "Merge" is available if both lines are in use and there's no
1909 // incoming call, *and* the current conference isn't already
1910 // "full".
1911 // TODO: shall move all okToMerge logic to CallManager
1912 return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
1913 && cm.hasActiveBgCall()
1914 && cm.canConference(cm.getFirstActiveBgCall());
1915 }
1916 }
1917
1918 /**
1919 * @return true if the UI should let you add a new call, given the current
1920 * state of the Phone.
1921 */
1922 /* package */ static boolean okToAddCall(CallManager cm) {
1923 Phone phone = cm.getActiveFgCall().getPhone();
1924
1925 // "Add call" is never allowed in emergency callback mode (ECM).
1926 if (isPhoneInEcm(phone)) {
1927 return false;
1928 }
1929
1930 int phoneType = phone.getPhoneType();
1931 final Call.State fgCallState = cm.getActiveFgCall().getState();
1932 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1933 // CDMA: "Add call" button is only enabled when:
1934 // - ForegroundCall is in ACTIVE state
1935 // - After 30 seconds of user Ignoring/Missing a Call Waiting call.
1936 PhoneGlobals app = PhoneGlobals.getInstance();
1937 return ((fgCallState == Call.State.ACTIVE)
1938 && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
1939 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001940 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07001941 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001942 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001943 // GSM: "Add call" is available only if ALL of the following are true:
1944 // - There's no incoming ringing call
1945 // - There's < 2 lines in use
1946 // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
1947 // (We mainly need to make sure it *isn't* DIALING or ALERTING.)
1948 final boolean hasRingingCall = cm.hasActiveRingingCall();
1949 final boolean hasActiveCall = cm.hasActiveFgCall();
1950 final boolean hasHoldingCall = cm.hasActiveBgCall();
1951 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1952
1953 return !hasRingingCall
1954 && !allLinesTaken
1955 && ((fgCallState == Call.State.ACTIVE)
1956 || (fgCallState == Call.State.IDLE)
1957 || (fgCallState == Call.State.DISCONNECTED));
1958 } else {
1959 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1960 }
1961 }
1962
1963 /**
1964 * Based on the input CNAP number string,
1965 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1966 * Otherwise, return CNAP_SPECIAL_CASE_NO.
1967 */
1968 private static int checkCnapSpecialCases(String n) {
1969 if (n.equals("PRIVATE") ||
1970 n.equals("P") ||
1971 n.equals("RES")) {
1972 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1973 return PhoneConstants.PRESENTATION_RESTRICTED;
1974 } else if (n.equals("UNAVAILABLE") ||
1975 n.equals("UNKNOWN") ||
1976 n.equals("UNA") ||
1977 n.equals("U")) {
1978 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1979 return PhoneConstants.PRESENTATION_UNKNOWN;
1980 } else {
1981 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1982 return CNAP_SPECIAL_CASE_NO;
1983 }
1984 }
1985
1986 /**
1987 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
1988 * from the network to indicate different number presentations, convert them to
1989 * expected number and presentation values within the CallerInfo object.
1990 * @param number number we use to verify if we are in a corner case
1991 * @param presentation presentation value used to verify if we are in a corner case
1992 * @return the new String that should be used for the phone number
1993 */
1994 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
1995 String number, int presentation) {
1996 // Obviously we return number if ci == null, but still return number if
1997 // number == null, because in these cases the correct string will still be
1998 // displayed/logged after this function returns based on the presentation value.
1999 if (ci == null || number == null) return number;
2000
2001 if (DBG) {
2002 log("modifyForSpecialCnapCases: initially, number="
2003 + toLogSafePhoneNumber(number)
2004 + ", presentation=" + presentation + " ci " + ci);
2005 }
2006
2007 // "ABSENT NUMBER" is a possible value we could get from the network as the
2008 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
2009 // and fix the presentation to be the same.
2010 final String[] absentNumberValues =
2011 context.getResources().getStringArray(R.array.absent_num);
2012 if (Arrays.asList(absentNumberValues).contains(number)
2013 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
2014 number = context.getString(R.string.unknown);
2015 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
2016 }
2017
2018 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
2019 // cases only apply if we received an allowed presentation from the network, so check
2020 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
2021 // match the presentation passed in for verification (meaning we changed it previously
2022 // because it's a corner case and we're being called from a different entry point).
2023 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
2024 || (ci.numberPresentation != presentation
2025 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
2026 int cnapSpecialCase = checkCnapSpecialCases(number);
2027 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
2028 // For all special strings, change number & numberPresentation.
2029 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
2030 number = context.getString(R.string.private_num);
2031 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
2032 number = context.getString(R.string.unknown);
2033 }
2034 if (DBG) {
2035 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
2036 + "; presentation now=" + cnapSpecialCase);
2037 }
2038 ci.numberPresentation = cnapSpecialCase;
2039 }
2040 }
2041 if (DBG) {
2042 log("modifyForSpecialCnapCases: returning number string="
2043 + toLogSafePhoneNumber(number));
2044 }
2045 return number;
2046 }
2047
2048 //
2049 // Support for 3rd party phone service providers.
2050 //
2051
2052 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002053 * Check if a phone number can be route through a 3rd party
2054 * gateway. The number must be a global phone number in numerical
2055 * form (1-800-666-SEXY won't work).
2056 *
2057 * MMI codes and the like cannot be used as a dial number for the
2058 * gateway either.
2059 *
2060 * @param number To be dialed via a 3rd party gateway.
2061 * @return true If the number can be routed through the 3rd party network.
2062 */
Santos Cordon69a69192013-08-22 14:25:42 -07002063 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002064 if (TextUtils.isEmpty(number)) {
2065 return false;
2066 }
2067 number = PhoneNumberUtils.stripSeparators(number);
2068 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
2069 return false;
2070 }
2071 number = PhoneNumberUtils.extractNetworkPortion(number);
2072 return PhoneNumberUtils.isGlobalPhoneNumber(number);
2073 }
2074
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002075 /**
2076 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
2077 */
2078 /* package */ static boolean isPhoneInEcm(Phone phone) {
2079 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
Shuo Qiandd210312017-04-12 22:11:33 +00002080 return phone.isInEcm();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002081 }
2082 return false;
2083 }
2084
2085 /**
2086 * Returns the most appropriate Phone object to handle a call
2087 * to the specified number.
2088 *
2089 * @param cm the CallManager.
2090 * @param scheme the scheme from the data URI that the number originally came from.
2091 * @param number the phone number, or SIP address.
2092 */
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002093 public static Phone pickPhoneBasedOnNumber(CallManager cm, String scheme, String number,
2094 String primarySipUri, ComponentName thirdPartyCallComponent) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002095 if (DBG) {
2096 log("pickPhoneBasedOnNumber: scheme " + scheme
2097 + ", number " + toLogSafePhoneNumber(number)
2098 + ", sipUri "
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002099 + (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null")
2100 + ", thirdPartyCallComponent: " + thirdPartyCallComponent);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002101 }
2102
2103 if (primarySipUri != null) {
2104 Phone phone = getSipPhoneFromUri(cm, primarySipUri);
2105 if (phone != null) return phone;
2106 }
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002107
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002108 return cm.getDefaultPhone();
2109 }
2110
2111 public static Phone getSipPhoneFromUri(CallManager cm, String target) {
2112 for (Phone phone : cm.getAllPhones()) {
2113 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
2114 String sipUri = ((SipPhone) phone).getSipUri();
2115 if (target.equals(sipUri)) {
2116 if (DBG) log("- pickPhoneBasedOnNumber:" +
2117 "found SipPhone! obj = " + phone + ", "
2118 + phone.getClass());
2119 return phone;
2120 }
2121 }
2122 }
2123 return null;
2124 }
2125
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002126 /**
2127 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
2128 * meaning the call is the first real incoming call the phone is having.
2129 */
2130 public static boolean isRealIncomingCall(Call.State state) {
2131 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
2132 }
2133
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002134 public static String getPresentationString(Context context, int presentation) {
2135 String name = context.getString(R.string.unknown);
2136 if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
2137 name = context.getString(R.string.private_num);
2138 } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
2139 name = context.getString(R.string.payphone);
2140 }
2141 return name;
2142 }
2143
2144 public static void sendViewNotificationAsync(Context context, Uri contactUri) {
2145 if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")");
2146 Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri);
2147 intent.setClassName("com.android.contacts",
2148 "com.android.contacts.ViewNotificationService");
2149 context.startService(intent);
2150 }
2151
2152 //
2153 // General phone and call state debugging/testing code
2154 //
2155
2156 /* package */ static void dumpCallState(Phone phone) {
2157 PhoneGlobals app = PhoneGlobals.getInstance();
2158 Log.d(LOG_TAG, "dumpCallState():");
2159 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
2160 + ", state = " + phone.getState());
2161
2162 StringBuilder b = new StringBuilder(128);
2163
2164 Call call = phone.getForegroundCall();
2165 b.setLength(0);
2166 b.append(" - FG call: ").append(call.getState());
2167 b.append(" isAlive ").append(call.getState().isAlive());
2168 b.append(" isRinging ").append(call.getState().isRinging());
2169 b.append(" isDialing ").append(call.getState().isDialing());
2170 b.append(" isIdle ").append(call.isIdle());
2171 b.append(" hasConnections ").append(call.hasConnections());
2172 Log.d(LOG_TAG, b.toString());
2173
2174 call = phone.getBackgroundCall();
2175 b.setLength(0);
2176 b.append(" - BG call: ").append(call.getState());
2177 b.append(" isAlive ").append(call.getState().isAlive());
2178 b.append(" isRinging ").append(call.getState().isRinging());
2179 b.append(" isDialing ").append(call.getState().isDialing());
2180 b.append(" isIdle ").append(call.isIdle());
2181 b.append(" hasConnections ").append(call.hasConnections());
2182 Log.d(LOG_TAG, b.toString());
2183
2184 call = phone.getRingingCall();
2185 b.setLength(0);
2186 b.append(" - RINGING call: ").append(call.getState());
2187 b.append(" isAlive ").append(call.getState().isAlive());
2188 b.append(" isRinging ").append(call.getState().isRinging());
2189 b.append(" isDialing ").append(call.getState().isDialing());
2190 b.append(" isIdle ").append(call.isIdle());
2191 b.append(" hasConnections ").append(call.hasConnections());
2192 Log.d(LOG_TAG, b.toString());
2193
2194
2195 final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2196 final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2197 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2198 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2199 b.setLength(0);
2200 b.append(" - hasRingingCall ").append(hasRingingCall);
2201 b.append(" hasActiveCall ").append(hasActiveCall);
2202 b.append(" hasHoldingCall ").append(hasHoldingCall);
2203 b.append(" allLinesTaken ").append(allLinesTaken);
2204 Log.d(LOG_TAG, b.toString());
2205
2206 // On CDMA phones, dump out the CdmaPhoneCallState too:
2207 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
2208 if (app.cdmaPhoneCallState != null) {
2209 Log.d(LOG_TAG, " - CDMA call state: "
2210 + app.cdmaPhoneCallState.getCurrentCallState());
2211 } else {
2212 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!");
2213 }
2214 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002215 }
2216
2217 private static void log(String msg) {
2218 Log.d(LOG_TAG, msg);
2219 }
2220
2221 static void dumpCallManager() {
2222 Call call;
2223 CallManager cm = PhoneGlobals.getInstance().mCM;
2224 StringBuilder b = new StringBuilder(128);
2225
2226
2227
2228 Log.d(LOG_TAG, "############### dumpCallManager() ##############");
2229 // TODO: Don't log "cm" itself, since CallManager.toString()
2230 // already spews out almost all this same information.
2231 // We should fix CallManager.toString() to be more minimal, and
2232 // use an explicit dumpState() method for the verbose dump.
2233 // Log.d(LOG_TAG, "CallManager: " + cm
2234 // + ", state = " + cm.getState());
2235 Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
2236 b.setLength(0);
2237 call = cm.getActiveFgCall();
2238 b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
2239 b.append(call);
2240 b.append( " State: ").append(cm.getActiveFgCallState());
2241 b.append( " Conn: ").append(cm.getFgCallConnections());
2242 Log.d(LOG_TAG, b.toString());
2243 b.setLength(0);
2244 call = cm.getFirstActiveBgCall();
2245 b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
2246 b.append(call);
2247 b.append( " State: ").append(cm.getFirstActiveBgCall().getState());
2248 b.append( " Conn: ").append(cm.getBgCallConnections());
2249 Log.d(LOG_TAG, b.toString());
2250 b.setLength(0);
2251 call = cm.getFirstActiveRingingCall();
2252 b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
2253 b.append(call);
2254 b.append( " State: ").append(cm.getFirstActiveRingingCall().getState());
2255 Log.d(LOG_TAG, b.toString());
2256
2257
2258
2259 for (Phone phone : CallManager.getInstance().getAllPhones()) {
2260 if (phone != null) {
2261 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
2262 + ", state = " + phone.getState());
2263 b.setLength(0);
2264 call = phone.getForegroundCall();
2265 b.append(" - FG call: ").append(call);
2266 b.append( " State: ").append(call.getState());
2267 b.append( " Conn: ").append(call.hasConnections());
2268 Log.d(LOG_TAG, b.toString());
2269 b.setLength(0);
2270 call = phone.getBackgroundCall();
2271 b.append(" - BG call: ").append(call);
2272 b.append( " State: ").append(call.getState());
2273 b.append( " Conn: ").append(call.hasConnections());
2274 Log.d(LOG_TAG, b.toString());b.setLength(0);
2275 call = phone.getRingingCall();
2276 b.append(" - RINGING call: ").append(call);
2277 b.append( " State: ").append(call.getState());
2278 b.append( " Conn: ").append(call.hasConnections());
2279 Log.d(LOG_TAG, b.toString());
2280 }
2281 }
2282
2283 Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
2284 }
2285
2286 /**
2287 * @return if the context is in landscape orientation.
2288 */
2289 public static boolean isLandscape(Context context) {
2290 return context.getResources().getConfiguration().orientation
2291 == Configuration.ORIENTATION_LANDSCAPE;
2292 }
Andrew Leed5165b02014-12-05 15:53:58 -08002293
Nancy Chene53a0642015-03-12 11:20:12 -07002294 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
2295 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
2296 }
2297
Nancy Chen32031f42015-03-04 21:00:07 -08002298 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
2299 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
2300 }
2301
Andrew Leed5165b02014-12-05 15:53:58 -08002302 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
2303 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
2304 }
2305
2306 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
2307 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08002308 // TODO: Should use some sort of special hidden flag to decorate this account as
2309 // an emergency-only account
Brad Ebingerd3edc222016-03-23 19:44:38 -07002310 String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
Brad Ebinger4fe48112016-04-13 11:21:53 -07002311 String.valueOf(phone.getFullIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07002312 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
2313 }
2314
2315 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
2316 String id, String prefix, boolean isEmergency) {
2317 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08002318 return new PhoneAccountHandle(pstnConnectionServiceName, id);
2319 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08002320
Santos Cordonf69df962015-02-03 11:15:19 -08002321 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08002322 if (phoneAccount != null
2323 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
2324 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
2325 }
2326 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
2327 }
2328
2329 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08002330 Phone phone = getPhoneForPhoneAccountHandle(handle);
2331 if (phone != null) {
2332 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08002333 }
2334 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
2335 }
2336
Ta-wei Yen845f6992016-06-16 12:53:46 -07002337 public static Phone getPhoneForPhoneAccountHandle(PhoneAccountHandle handle) {
Nancy Chen31f9ba12016-01-06 11:42:12 -08002338 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
2339 return getPhoneFromIccId(handle.getId());
2340 }
2341 return null;
2342 }
2343
2344
Nancy Chene53a0642015-03-12 11:20:12 -07002345 /**
2346 * Determine if a given phone account corresponds to an active SIM
2347 *
2348 * @param sm An instance of the subscription manager so it is not recreated for each calling of
2349 * this method.
2350 * @param handle The handle for the phone account to check
2351 * @return {@code true} If there is an active SIM for this phone account,
2352 * {@code false} otherwise.
2353 */
2354 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
2355 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
2356 }
2357
Santos Cordonf69df962015-02-03 11:15:19 -08002358 private static ComponentName getPstnConnectionServiceName() {
Tony Mak4c8f3c62015-12-07 02:30:37 +00002359 return PSTN_CONNECTION_SERVICE_COMPONENT;
Santos Cordonf69df962015-02-03 11:15:19 -08002360 }
2361
Santos Cordon80855d52015-02-10 04:33:36 -08002362 private static Phone getPhoneFromIccId(String iccId) {
2363 if (!TextUtils.isEmpty(iccId)) {
2364 for (Phone phone : PhoneFactory.getPhones()) {
Brad Ebinger4fe48112016-04-13 11:21:53 -07002365 String phoneIccId = phone.getFullIccSerialNumber();
Santos Cordon80855d52015-02-10 04:33:36 -08002366 if (iccId.equals(phoneIccId)) {
2367 return phone;
2368 }
2369 }
2370 }
Santos Cordon80855d52015-02-10 04:33:36 -08002371 return null;
2372 }
2373
Stuart Scottdcf40a92014-12-09 10:45:01 -08002374 /**
2375 * Register ICC status for all phones.
2376 */
2377 static final void registerIccStatus(Handler handler, int event) {
2378 for (Phone phone : PhoneFactory.getPhones()) {
2379 IccCard sim = phone.getIccCard();
2380 if (sim != null) {
2381 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
2382 sim.registerForNetworkLocked(handler, event, phone);
2383 }
2384 }
2385 }
2386
2387 /**
2388 * Set the radio power on/off state for all phones.
2389 *
2390 * @param enabled true means on, false means off.
2391 */
2392 static final void setRadioPower(boolean enabled) {
2393 for (Phone phone : PhoneFactory.getPhones()) {
2394 phone.setRadioPower(enabled);
2395 }
2396 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002397}