blob: a3b4cfb6f071922d2ea41a503818f5c712a214dc [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;
Jonathan Basseri3b9c21f2015-06-19 15:51:10 -070033import android.os.PersistableBundle;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070034import android.os.RemoteException;
35import android.os.SystemProperties;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070036import android.telecom.PhoneAccount;
Andrew Leed5165b02014-12-05 15:53:58 -080037import android.telecom.PhoneAccountHandle;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070038import android.telecom.VideoProfile;
Jonathan Basseri3b9c21f2015-06-19 15:51:10 -070039import android.telephony.CarrierConfigManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070040import android.telephony.PhoneNumberUtils;
Santos Cordonf69df962015-02-03 11:15:19 -080041import android.telephony.SubscriptionManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070042import android.text.TextUtils;
43import android.util.Log;
Andrew Leeb3ee4dc2015-01-23 17:35:00 -080044import android.view.ContextThemeWrapper;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070045import android.view.KeyEvent;
46import android.view.LayoutInflater;
47import android.view.View;
48import android.view.WindowManager;
49import android.widget.EditText;
50import android.widget.Toast;
51
52import com.android.internal.telephony.Call;
53import com.android.internal.telephony.CallManager;
54import com.android.internal.telephony.CallStateException;
55import com.android.internal.telephony.CallerInfo;
56import com.android.internal.telephony.CallerInfoAsyncQuery;
57import com.android.internal.telephony.Connection;
Stuart Scottdcf40a92014-12-09 10:45:01 -080058import com.android.internal.telephony.IccCard;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070059import com.android.internal.telephony.MmiCode;
60import com.android.internal.telephony.Phone;
61import com.android.internal.telephony.PhoneConstants;
Stuart Scottdcf40a92014-12-09 10:45:01 -080062import com.android.internal.telephony.PhoneFactory;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070063import com.android.internal.telephony.TelephonyCapabilities;
64import com.android.internal.telephony.TelephonyProperties;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070065import com.android.internal.telephony.sip.SipPhone;
Santos Cordon69a69192013-08-22 14:25:42 -070066import com.android.phone.CallGatewayManager.RawGatewayInfo;
Andrew Leed5165b02014-12-05 15:53:58 -080067import com.android.services.telephony.TelephonyConnectionService;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070068
Santos Cordon7d4ddf62013-07-10 11:58:08 -070069import java.util.Arrays;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070070import java.util.List;
71
72/**
73 * Misc utilities for the Phone app.
74 */
75public class PhoneUtils {
76 private static final String LOG_TAG = "PhoneUtils";
77 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
78
79 // Do not check in with VDBG = true, since that may write PII to the system log.
80 private static final boolean VDBG = false;
81
82 /** Control stack trace for Audio Mode settings */
83 private static final boolean DBG_SETAUDIOMODE_STACK = false;
84
85 /** Identifier for the "Add Call" intent extra. */
86 static final String ADD_CALL_MODE_KEY = "add_call_mode";
87
88 // Return codes from placeCall()
89 static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed
90 static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code
91 static final int CALL_STATUS_FAILED = 2; // The call failed
92
93 // State of the Phone's audio modes
94 // Each state can move to the other states, but within the state only certain
95 // transitions for AudioManager.setMode() are allowed.
96 static final int AUDIO_IDLE = 0; /** audio behaviour at phone idle */
97 static final int AUDIO_RINGING = 1; /** audio behaviour while ringing */
98 static final int AUDIO_OFFHOOK = 2; /** audio behaviour while in call. */
99
100 // USSD string length for MMI operations
101 static final int MIN_USSD_LEN = 1;
102 static final int MAX_USSD_LEN = 160;
103
104 /** Speaker state, persisting between wired headset connection events */
105 private static boolean sIsSpeakerEnabled = false;
106
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700107 /** Static handler for the connection/mute tracking */
108 private static ConnectionHandler mConnectionHandler;
109
110 /** Phone state changed event*/
111 private static final int PHONE_STATE_CHANGED = -1;
112
Zhihai Xua4915c72013-10-18 17:01:16 -0700113 /** check status then decide whether answerCall */
114 private static final int MSG_CHECK_STATUS_ANSWERCALL = 100;
115
116 /** poll phone DISCONNECTING status interval */
117 private static final int DISCONNECTING_POLLING_INTERVAL_MS = 200;
118
119 /** poll phone DISCONNECTING status times limit */
120 private static final int DISCONNECTING_POLLING_TIMES_LIMIT = 8;
121
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700122 /** Define for not a special CNAP string */
123 private static final int CNAP_SPECIAL_CASE_NO = -1;
124
125 /** Noise suppression status as selected by user */
126 private static boolean sIsNoiseSuppressionEnabled = true;
127
Yorke Leee0f2b792014-10-15 12:30:44 -0700128 /**
129 * Theme to use for dialogs displayed by utility methods in this class. This is needed
130 * because these dialogs are displayed using the application context, which does not resolve
131 * the dialog theme correctly.
132 */
133 private static final int THEME = AlertDialog.THEME_DEVICE_DEFAULT_LIGHT;
134
Zhihai Xua4915c72013-10-18 17:01:16 -0700135 private static class FgRingCalls {
136 private Call fgCall;
137 private Call ringing;
138 public FgRingCalls(Call fg, Call ring) {
139 fgCall = fg;
140 ringing = ring;
141 }
142 }
143
Etan Cohen37abbab2014-03-07 16:57:03 -0800144 /** USSD information used to aggregate all USSD messages */
145 private static AlertDialog sUssdDialog = null;
146 private static StringBuilder sUssdMsg = new StringBuilder();
147
Tony Mak4c8f3c62015-12-07 02:30:37 +0000148 private static final ComponentName PSTN_CONNECTION_SERVICE_COMPONENT =
149 new ComponentName("com.android.phone",
150 "com.android.services.telephony.TelephonyConnectionService");
151
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700152 /**
153 * Handler that tracks the connections and updates the value of the
154 * Mute settings for each connection as needed.
155 */
156 private static class ConnectionHandler extends Handler {
157 @Override
158 public void handleMessage(Message msg) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700159 switch (msg.what) {
Zhihai Xua4915c72013-10-18 17:01:16 -0700160 case MSG_CHECK_STATUS_ANSWERCALL:
161 FgRingCalls frC = (FgRingCalls) msg.obj;
162 // wait for finishing disconnecting
163 // before check the ringing call state
164 if ((frC.fgCall != null) &&
165 (frC.fgCall.getState() == Call.State.DISCONNECTING) &&
166 (msg.arg1 < DISCONNECTING_POLLING_TIMES_LIMIT)) {
167 Message retryMsg =
168 mConnectionHandler.obtainMessage(MSG_CHECK_STATUS_ANSWERCALL);
169 retryMsg.arg1 = 1 + msg.arg1;
170 retryMsg.obj = msg.obj;
171 mConnectionHandler.sendMessageDelayed(retryMsg,
172 DISCONNECTING_POLLING_INTERVAL_MS);
173 // since hangupActiveCall() also accepts the ringing call
174 // check if the ringing call was already answered or not
175 // only answer it when the call still is ringing
176 } else if (frC.ringing.isRinging()) {
177 if (msg.arg1 == DISCONNECTING_POLLING_TIMES_LIMIT) {
178 Log.e(LOG_TAG, "DISCONNECTING time out");
179 }
180 answerCall(frC.ringing);
181 }
182 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700183 }
184 }
185 }
186
187 /**
188 * Register the ConnectionHandler with the phone, to receive connection events
189 */
190 public static void initializeConnectionHandler(CallManager cm) {
191 if (mConnectionHandler == null) {
192 mConnectionHandler = new ConnectionHandler();
193 }
194
195 // pass over cm as user.obj
196 cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm);
197
198 }
199
200 /** This class is never instantiated. */
201 private PhoneUtils() {
202 }
203
204 /**
205 * Answer the currently-ringing call.
206 *
207 * @return true if we answered the call, or false if there wasn't
208 * actually a ringing incoming call, or some other error occurred.
209 *
210 * @see #answerAndEndHolding(CallManager, Call)
211 * @see #answerAndEndActive(CallManager, Call)
212 */
213 /* package */ static boolean answerCall(Call ringingCall) {
214 log("answerCall(" + ringingCall + ")...");
215 final PhoneGlobals app = PhoneGlobals.getInstance();
216 final CallNotifier notifier = app.notifier;
217
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700218 final Phone phone = ringingCall.getPhone();
219 final boolean phoneIsCdma = (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA);
220 boolean answered = false;
221 IBluetoothHeadsetPhone btPhone = null;
222
223 if (phoneIsCdma) {
224 // Stop any signalInfo tone being played when a Call waiting gets answered
225 if (ringingCall.getState() == Call.State.WAITING) {
226 notifier.stopSignalInfoTone();
227 }
228 }
229
230 if (ringingCall != null && ringingCall.isRinging()) {
231 if (DBG) log("answerCall: call state = " + ringingCall.getState());
232 try {
233 if (phoneIsCdma) {
234 if (app.cdmaPhoneCallState.getCurrentCallState()
235 == CdmaPhoneCallState.PhoneCallState.IDLE) {
236 // This is the FIRST incoming call being answered.
237 // Set the Phone Call State to SINGLE_ACTIVE
238 app.cdmaPhoneCallState.setCurrentCallState(
239 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
240 } else {
241 // This is the CALL WAITING call being answered.
242 // Set the Phone Call State to CONF_CALL
243 app.cdmaPhoneCallState.setCurrentCallState(
244 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
245 // Enable "Add Call" option after answering a Call Waiting as the user
246 // should be allowed to add another call in case one of the parties
247 // drops off
248 app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
Santos Cordon13fed9f2014-09-24 13:10:34 -0700249 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700250 }
251
252 final boolean isRealIncomingCall = isRealIncomingCall(ringingCall.getState());
253
254 //if (DBG) log("sPhone.acceptCall");
255 app.mCM.acceptCall(ringingCall);
256 answered = true;
257
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700258 setAudioMode();
259
260 // Check is phone in any dock, and turn on speaker accordingly
261 final boolean speakerActivated = activateSpeakerIfDocked(phone);
262
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700263 final BluetoothManager btManager = app.getBluetoothManager();
264
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700265 // When answering a phone call, the user will move the phone near to her/his ear
266 // and start conversation, without checking its speaker status. If some other
267 // application turned on the speaker mode before the call and didn't turn it off,
268 // Phone app would need to be responsible for the speaker phone.
269 // Here, we turn off the speaker if
270 // - the phone call is the first in-coming call,
271 // - we did not activate speaker by ourselves during the process above, and
272 // - Bluetooth headset is not in use.
273 if (isRealIncomingCall && !speakerActivated && isSpeakerOn(app)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700274 && !btManager.isBluetoothHeadsetAudioOn()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700275 // This is not an error but might cause users' confusion. Add log just in case.
276 Log.i(LOG_TAG, "Forcing speaker off due to new incoming call...");
277 turnOnSpeaker(app, false, true);
278 }
279 } catch (CallStateException ex) {
280 Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
281
282 if (phoneIsCdma) {
283 // restore the cdmaPhoneCallState and btPhone.cdmaSetSecondCallState:
284 app.cdmaPhoneCallState.setCurrentCallState(
285 app.cdmaPhoneCallState.getPreviousCallState());
286 if (btPhone != null) {
287 try {
288 btPhone.cdmaSetSecondCallState(false);
289 } catch (RemoteException e) {
290 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
291 }
292 }
293 }
294 }
295 }
296 return answered;
297 }
298
299 /**
Santos Cordonde10b752013-09-19 04:11:33 -0700300 * Hangs up all active calls.
301 */
302 static void hangupAllCalls(CallManager cm) {
303 final Call ringing = cm.getFirstActiveRingingCall();
304 final Call fg = cm.getActiveFgCall();
305 final Call bg = cm.getFirstActiveBgCall();
306
307 // We go in reverse order, BG->FG->RINGING because hanging up a ringing call or an active
308 // call can move a bg call to a fg call which would force us to loop over each call
309 // several times. This ordering works best to ensure we dont have any more calls.
310 if (bg != null && !bg.isIdle()) {
311 hangup(bg);
312 }
313 if (fg != null && !fg.isIdle()) {
314 hangup(fg);
315 }
316 if (ringing != null && !ringing.isIdle()) {
317 hangupRingingCall(fg);
318 }
319 }
320
321 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700322 * Smart "hang up" helper method which hangs up exactly one connection,
323 * based on the current Phone state, as follows:
324 * <ul>
325 * <li>If there's a ringing call, hang that up.
326 * <li>Else if there's a foreground call, hang that up.
327 * <li>Else if there's a background call, hang that up.
328 * <li>Otherwise do nothing.
329 * </ul>
330 * @return true if we successfully hung up, or false
331 * if there were no active calls at all.
332 */
333 static boolean hangup(CallManager cm) {
334 boolean hungup = false;
335 Call ringing = cm.getFirstActiveRingingCall();
336 Call fg = cm.getActiveFgCall();
337 Call bg = cm.getFirstActiveBgCall();
338
339 if (!ringing.isIdle()) {
340 log("hangup(): hanging up ringing call");
341 hungup = hangupRingingCall(ringing);
342 } else if (!fg.isIdle()) {
343 log("hangup(): hanging up foreground call");
344 hungup = hangup(fg);
345 } else if (!bg.isIdle()) {
346 log("hangup(): hanging up background call");
347 hungup = hangup(bg);
348 } else {
349 // No call to hang up! This is unlikely in normal usage,
350 // since the UI shouldn't be providing an "End call" button in
351 // the first place. (But it *can* happen, rarely, if an
352 // active call happens to disconnect on its own right when the
353 // user is trying to hang up..)
354 log("hangup(): no active call to hang up");
355 }
356 if (DBG) log("==> hungup = " + hungup);
357
358 return hungup;
359 }
360
361 static boolean hangupRingingCall(Call ringing) {
362 if (DBG) log("hangup ringing call");
363 int phoneType = ringing.getPhone().getPhoneType();
364 Call.State state = ringing.getState();
365
366 if (state == Call.State.INCOMING) {
367 // Regular incoming call (with no other active calls)
368 log("hangupRingingCall(): regular incoming call: hangup()");
369 return hangup(ringing);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700370 } else {
371 // Unexpected state: the ringing call isn't INCOMING or
372 // WAITING, so there's no reason to have called
373 // hangupRingingCall() in the first place.
374 // (Presumably the incoming call went away at the exact moment
375 // we got here, so just do nothing.)
376 Log.w(LOG_TAG, "hangupRingingCall: no INCOMING or WAITING call");
377 return false;
378 }
379 }
380
381 static boolean hangupActiveCall(Call foreground) {
382 if (DBG) log("hangup active call");
383 return hangup(foreground);
384 }
385
386 static boolean hangupHoldingCall(Call background) {
387 if (DBG) log("hangup holding call");
388 return hangup(background);
389 }
390
391 /**
392 * Used in CDMA phones to end the complete Call session
393 * @param phone the Phone object.
394 * @return true if *any* call was successfully hung up
395 */
396 static boolean hangupRingingAndActive(Phone phone) {
397 boolean hungUpRingingCall = false;
398 boolean hungUpFgCall = false;
399 Call ringingCall = phone.getRingingCall();
400 Call fgCall = phone.getForegroundCall();
401
402 // Hang up any Ringing Call
403 if (!ringingCall.isIdle()) {
404 log("hangupRingingAndActive: Hang up Ringing Call");
405 hungUpRingingCall = hangupRingingCall(ringingCall);
406 }
407
408 // Hang up any Active Call
409 if (!fgCall.isIdle()) {
410 log("hangupRingingAndActive: Hang up Foreground Call");
411 hungUpFgCall = hangupActiveCall(fgCall);
412 }
413
414 return hungUpRingingCall || hungUpFgCall;
415 }
416
417 /**
418 * Trivial wrapper around Call.hangup(), except that we return a
419 * boolean success code rather than throwing CallStateException on
420 * failure.
421 *
422 * @return true if the call was successfully hung up, or false
423 * if the call wasn't actually active.
424 */
425 static boolean hangup(Call call) {
426 try {
427 CallManager cm = PhoneGlobals.getInstance().mCM;
428
429 if (call.getState() == Call.State.ACTIVE && cm.hasActiveBgCall()) {
430 // handle foreground call hangup while there is background call
431 log("- hangup(Call): hangupForegroundResumeBackground...");
432 cm.hangupForegroundResumeBackground(cm.getFirstActiveBgCall());
433 } else {
434 log("- hangup(Call): regular hangup()...");
435 call.hangup();
436 }
437 return true;
438 } catch (CallStateException ex) {
439 Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
440 }
441
442 return false;
443 }
444
445 /**
446 * Trivial wrapper around Connection.hangup(), except that we silently
447 * do nothing (rather than throwing CallStateException) if the
448 * connection wasn't actually active.
449 */
450 static void hangup(Connection c) {
451 try {
452 if (c != null) {
453 c.hangup();
454 }
455 } catch (CallStateException ex) {
456 Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
457 }
458 }
459
460 static boolean answerAndEndHolding(CallManager cm, Call ringing) {
461 if (DBG) log("end holding & answer waiting: 1");
462 if (!hangupHoldingCall(cm.getFirstActiveBgCall())) {
463 Log.e(LOG_TAG, "end holding failed!");
464 return false;
465 }
466
467 if (DBG) log("end holding & answer waiting: 2");
468 return answerCall(ringing);
469
470 }
471
472 /**
473 * Answers the incoming call specified by "ringing", and ends the currently active phone call.
474 *
475 * This method is useful when's there's an incoming call which we cannot manage with the
476 * current call. e.g. when you are having a phone call with CDMA network and has received
477 * a SIP call, then we won't expect our telephony can manage those phone calls simultaneously.
478 * Note that some types of network may allow multiple phone calls at once; GSM allows to hold
479 * an ongoing phone call, so we don't need to end the active call. The caller of this method
480 * needs to check if the network allows multiple phone calls or not.
481 *
482 * @see #answerCall(Call)
483 * @see InCallScreen#internalAnswerCall()
484 */
485 /* package */ static boolean answerAndEndActive(CallManager cm, Call ringing) {
486 if (DBG) log("answerAndEndActive()...");
487
488 // Unlike the answerCall() method, we *don't* need to stop the
489 // ringer or change audio modes here since the user is already
490 // in-call, which means that the audio mode is already set
491 // correctly, and that we wouldn't have started the ringer in the
492 // first place.
493
494 // hanging up the active call also accepts the waiting call
495 // while active call and waiting call are from the same phone
496 // i.e. both from GSM phone
Zhihai Xua4915c72013-10-18 17:01:16 -0700497 Call fgCall = cm.getActiveFgCall();
498 if (!hangupActiveCall(fgCall)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700499 Log.w(LOG_TAG, "end active call failed!");
500 return false;
501 }
502
Zhihai Xua4915c72013-10-18 17:01:16 -0700503 mConnectionHandler.removeMessages(MSG_CHECK_STATUS_ANSWERCALL);
504 Message msg = mConnectionHandler.obtainMessage(MSG_CHECK_STATUS_ANSWERCALL);
505 msg.arg1 = 1;
506 msg.obj = new FgRingCalls(fgCall, ringing);
507 mConnectionHandler.sendMessage(msg);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700508
509 return true;
510 }
511
512 /**
513 * For a CDMA phone, advance the call state upon making a new
514 * outgoing call.
515 *
516 * <pre>
517 * IDLE -> SINGLE_ACTIVE
518 * or
519 * SINGLE_ACTIVE -> THRWAY_ACTIVE
520 * </pre>
521 * @param app The phone instance.
522 */
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700523 private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app,
524 Connection connection) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700525 if (app.cdmaPhoneCallState.getCurrentCallState() ==
526 CdmaPhoneCallState.PhoneCallState.IDLE) {
527 // This is the first outgoing call. Set the Phone Call State to ACTIVE
528 app.cdmaPhoneCallState.setCurrentCallState(
529 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
530 } else {
531 // This is the second outgoing call. Set the Phone Call State to 3WAY
532 app.cdmaPhoneCallState.setCurrentCallState(
533 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700534
Santos Cordonda120f42014-08-06 04:44:34 -0700535 // TODO: Remove this code.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700536 //app.getCallModeler().setCdmaOutgoing3WayCall(connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700537 }
538 }
539
540 /**
Santos Cordon69a69192013-08-22 14:25:42 -0700541 * @see placeCall below
542 */
543 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
544 boolean isEmergencyCall) {
545 return placeCall(context, phone, number, contactRef, isEmergencyCall,
546 CallGatewayManager.EMPTY_INFO, null);
547 }
548
549 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700550 * Dial the number using the phone passed in.
551 *
552 * If the connection is establised, this method issues a sync call
553 * that may block to query the caller info.
554 * TODO: Change the logic to use the async query.
555 *
556 * @param context To perform the CallerInfo query.
557 * @param phone the Phone object.
558 * @param number to be dialed as requested by the user. This is
559 * NOT the phone number to connect to. It is used only to build the
560 * call card and to update the call log. See above for restrictions.
561 * @param contactRef that triggered the call. Typically a 'tel:'
562 * uri but can also be a 'content://contacts' one.
563 * @param isEmergencyCall indicates that whether or not this is an
564 * emergency call
565 * @param gatewayUri Is the address used to setup the connection, null
566 * if not using a gateway
Santos Cordon69a69192013-08-22 14:25:42 -0700567 * @param callGateway Class for setting gateway data on a successful call.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700568 *
569 * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
570 */
Santos Cordon69a69192013-08-22 14:25:42 -0700571 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
572 boolean isEmergencyCall, RawGatewayInfo gatewayInfo, CallGatewayManager callGateway) {
573 final Uri gatewayUri = gatewayInfo.gatewayUri;
574
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700575 if (VDBG) {
576 log("placeCall()... number: '" + number + "'"
577 + ", GW:'" + gatewayUri + "'"
578 + ", contactRef:" + contactRef
579 + ", isEmergencyCall: " + isEmergencyCall);
580 } else {
581 log("placeCall()... number: " + toLogSafePhoneNumber(number)
582 + ", GW: " + (gatewayUri != null ? "non-null" : "null")
583 + ", emergency? " + isEmergencyCall);
584 }
585 final PhoneGlobals app = PhoneGlobals.getInstance();
586
587 boolean useGateway = false;
588 if (null != gatewayUri &&
589 !isEmergencyCall &&
590 PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes.
591 useGateway = true;
592 }
593
594 int status = CALL_STATUS_DIALED;
595 Connection connection;
596 String numberToDial;
597 if (useGateway) {
598 // TODO: 'tel' should be a constant defined in framework base
599 // somewhere (it is in webkit.)
Jay Shrauner137458b2014-09-05 14:27:25 -0700600 if (null == gatewayUri || !PhoneAccount.SCHEME_TEL.equals(gatewayUri.getScheme())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700601 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
602 return CALL_STATUS_FAILED;
603 }
604
605 // We can use getSchemeSpecificPart because we don't allow #
606 // in the gateway numbers (treated a fragment delim.) However
607 // if we allow more complex gateway numbers sequence (with
608 // passwords or whatnot) that use #, this may break.
609 // TODO: Need to support MMI codes.
610 numberToDial = gatewayUri.getSchemeSpecificPart();
611 } else {
612 numberToDial = number;
613 }
614
615 // Remember if the phone state was in IDLE state before this call.
616 // After calling CallManager#dial(), getState() will return different state.
617 final boolean initiallyIdle = app.mCM.getState() == PhoneConstants.State.IDLE;
618
619 try {
Tyler Gunnc6514352015-06-02 21:46:34 -0700620 connection = app.mCM.dial(phone, numberToDial, VideoProfile.STATE_AUDIO_ONLY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700621 } catch (CallStateException ex) {
622 // CallStateException means a new outgoing call is not currently
623 // possible: either no more call slots exist, or there's another
624 // call already in the process of dialing or ringing.
625 Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
626 return CALL_STATUS_FAILED;
627
628 // Note that it's possible for CallManager.dial() to return
629 // null *without* throwing an exception; that indicates that
630 // we dialed an MMI (see below).
631 }
632
633 int phoneType = phone.getPhoneType();
634
635 // On GSM phones, null is returned for MMI codes
636 if (null == connection) {
Santos Cordonf77a3392014-07-21 19:48:10 -0700637 status = CALL_STATUS_FAILED;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700638 } else {
Tyler Gunn10f1c6a2014-01-17 12:01:11 -0800639 // Now that the call is successful, we can save the gateway info for the call
640 if (callGateway != null) {
641 callGateway.setGatewayInfoForConnection(connection, gatewayInfo);
642 }
643
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700644 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700645 updateCdmaCallStateOnNewOutgoingCall(app, connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700646 }
647
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700648 if (gatewayUri == null) {
649 // phone.dial() succeeded: we're now in a normal phone call.
650 // attach the URI to the CallerInfo Object if it is there,
651 // otherwise just attach the Uri Reference.
652 // if the uri does not have a "content" scheme, then we treat
653 // it as if it does NOT have a unique reference.
654 String content = context.getContentResolver().SCHEME_CONTENT;
655 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
656 Object userDataObject = connection.getUserData();
657 if (userDataObject == null) {
658 connection.setUserData(contactRef);
659 } else {
660 // TODO: This branch is dead code, we have
661 // just created the connection which has
662 // no user data (null) by default.
663 if (userDataObject instanceof CallerInfo) {
664 ((CallerInfo) userDataObject).contactRefUri = contactRef;
665 } else {
666 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
667 contactRef;
668 }
669 }
670 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700671 }
Santos Cordonc264cba2013-09-19 04:55:40 -0700672
Chiao Chenge365ba72013-09-26 14:18:12 -0700673 startGetCallerInfo(context, connection, null, null, gatewayInfo);
674
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700675 setAudioMode();
676
677 if (DBG) log("about to activate speaker");
678 // Check is phone in any dock, and turn on speaker accordingly
679 final boolean speakerActivated = activateSpeakerIfDocked(phone);
680
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700681 final BluetoothManager btManager = app.getBluetoothManager();
682
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700683 // See also similar logic in answerCall().
684 if (initiallyIdle && !speakerActivated && isSpeakerOn(app)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700685 && !btManager.isBluetoothHeadsetAudioOn()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700686 // This is not an error but might cause users' confusion. Add log just in case.
687 Log.i(LOG_TAG, "Forcing speaker off when initiating a new outgoing call...");
688 PhoneUtils.turnOnSpeaker(app, false, true);
689 }
690 }
691
692 return status;
693 }
694
695 /* package */ static String toLogSafePhoneNumber(String number) {
696 // For unknown number, log empty string.
697 if (number == null) {
698 return "";
699 }
700
701 if (VDBG) {
702 // When VDBG is true we emit PII.
703 return number;
704 }
705
706 // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
707 // sanitized phone numbers.
708 StringBuilder builder = new StringBuilder();
709 for (int i = 0; i < number.length(); i++) {
710 char c = number.charAt(i);
711 if (c == '-' || c == '@' || c == '.') {
712 builder.append(c);
713 } else {
714 builder.append('x');
715 }
716 }
717 return builder.toString();
718 }
719
720 /**
721 * Wrapper function to control when to send an empty Flash command to the network.
722 * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash
723 * to the network prior to placing a 3-way call for it to be successful.
724 */
725 static void sendEmptyFlash(Phone phone) {
726 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
727 Call fgCall = phone.getForegroundCall();
728 if (fgCall.getState() == Call.State.ACTIVE) {
729 // Send the empty flash
730 if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network");
731 switchHoldingAndActive(phone.getBackgroundCall());
732 }
733 }
734 }
735
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700736 static void swap() {
737 final PhoneGlobals mApp = PhoneGlobals.getInstance();
738 if (!okToSwapCalls(mApp.mCM)) {
739 // TODO: throw an error instead?
740 return;
741 }
742
743 // Swap the fg and bg calls.
744 // In the future we may provide some way for user to choose among
745 // multiple background calls, for now, always act on the first background call.
746 PhoneUtils.switchHoldingAndActive(mApp.mCM.getFirstActiveBgCall());
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700747 }
748
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700749 /**
750 * @param heldCall is the background call want to be swapped
751 */
752 static void switchHoldingAndActive(Call heldCall) {
753 log("switchHoldingAndActive()...");
754 try {
755 CallManager cm = PhoneGlobals.getInstance().mCM;
756 if (heldCall.isIdle()) {
757 // no heldCall, so it is to hold active call
758 cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall());
759 } else {
760 // has particular heldCall, so to switch
761 cm.switchHoldingAndActive(heldCall);
762 }
763 setAudioMode(cm);
764 } catch (CallStateException ex) {
765 Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
766 }
767 }
768
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700769 static void mergeCalls() {
770 mergeCalls(PhoneGlobals.getInstance().mCM);
771 }
772
773 static void mergeCalls(CallManager cm) {
774 int phoneType = cm.getFgPhone().getPhoneType();
775 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
776 log("mergeCalls(): CDMA...");
777 PhoneGlobals app = PhoneGlobals.getInstance();
778 if (app.cdmaPhoneCallState.getCurrentCallState()
779 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
780 // Set the Phone Call State to conference
781 app.cdmaPhoneCallState.setCurrentCallState(
782 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
783
784 // Send flash cmd
785 // TODO: Need to change the call from switchHoldingAndActive to
786 // something meaningful as we are not actually trying to swap calls but
787 // instead are merging two calls by sending a Flash command.
788 log("- sending flash...");
789 switchHoldingAndActive(cm.getFirstActiveBgCall());
790 }
791 } else {
792 try {
793 log("mergeCalls(): calling cm.conference()...");
794 cm.conference(cm.getFirstActiveBgCall());
795 } catch (CallStateException ex) {
796 Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
797 }
798 }
799 }
800
801 static void separateCall(Connection c) {
802 try {
803 if (DBG) log("separateCall: " + toLogSafePhoneNumber(c.getAddress()));
804 c.separate();
805 } catch (CallStateException ex) {
806 Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
807 }
808 }
809
810 /**
811 * Handle the MMIInitiate message and put up an alert that lets
812 * the user cancel the operation, if applicable.
813 *
814 * @param context context to get strings.
815 * @param mmiCode the MmiCode object being started.
816 * @param buttonCallbackMessage message to post when button is clicked.
817 * @param previousAlert a previous alert used in this activity.
818 * @return the dialog handle
819 */
820 static Dialog displayMMIInitiate(Context context,
821 MmiCode mmiCode,
822 Message buttonCallbackMessage,
823 Dialog previousAlert) {
824 if (DBG) log("displayMMIInitiate: " + mmiCode);
825 if (previousAlert != null) {
826 previousAlert.dismiss();
827 }
828
829 // The UI paradigm we are using now requests that all dialogs have
830 // user interaction, and that any other messages to the user should
831 // be by way of Toasts.
832 //
833 // In adhering to this request, all MMI initiating "OK" dialogs
834 // (non-cancelable MMIs) that end up being closed when the MMI
835 // completes (thereby showing a completion dialog) are being
836 // replaced with Toasts.
837 //
838 // As a side effect, moving to Toasts for the non-cancelable MMIs
839 // also means that buttonCallbackMessage (which was tied into "OK")
840 // is no longer invokable for these dialogs. This is not a problem
841 // since the only callback messages we supported were for cancelable
842 // MMIs anyway.
843 //
844 // A cancelable MMI is really just a USSD request. The term
845 // "cancelable" here means that we can cancel the request when the
846 // system prompts us for a response, NOT while the network is
847 // processing the MMI request. Any request to cancel a USSD while
848 // the network is NOT ready for a response may be ignored.
849 //
850 // With this in mind, we replace the cancelable alert dialog with
851 // a progress dialog, displayed until we receive a request from
852 // the the network. For more information, please see the comments
853 // in the displayMMIComplete() method below.
854 //
855 // Anything that is NOT a USSD request is a normal MMI request,
856 // which will bring up a toast (desribed above).
857
858 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
859
860 if (!isCancelable) {
861 if (DBG) log("not a USSD code, displaying status toast.");
862 CharSequence text = context.getText(R.string.mmiStarted);
863 Toast.makeText(context, text, Toast.LENGTH_SHORT)
864 .show();
865 return null;
866 } else {
867 if (DBG) log("running USSD code, displaying indeterminate progress.");
868
869 // create the indeterminate progress dialog and display it.
Alex Hills779841a2015-10-22 13:23:28 -0400870 ProgressDialog pd = new ProgressDialog(context, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700871 pd.setMessage(context.getText(R.string.ussdRunning));
872 pd.setCancelable(false);
873 pd.setIndeterminate(true);
874 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
875
876 pd.show();
877
878 return pd;
879 }
880
881 }
882
883 /**
884 * Handle the MMIComplete message and fire off an intent to display
885 * the message.
886 *
887 * @param context context to get strings.
888 * @param mmiCode MMI result.
889 * @param previousAlert a previous alert used in this activity.
890 */
891 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
892 Message dismissCallbackMessage,
893 AlertDialog previousAlert) {
894 final PhoneGlobals app = PhoneGlobals.getInstance();
895 CharSequence text;
896 int title = 0; // title for the progress dialog, if needed.
897 MmiCode.State state = mmiCode.getState();
898
899 if (DBG) log("displayMMIComplete: state=" + state);
900
901 switch (state) {
902 case PENDING:
903 // USSD code asking for feedback from user.
904 text = mmiCode.getMessage();
905 if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
906 break;
907 case CANCELLED:
908 text = null;
909 break;
910 case COMPLETE:
911 if (app.getPUKEntryActivity() != null) {
912 // if an attempt to unPUK the device was made, we specify
913 // the title and the message here.
914 title = com.android.internal.R.string.PinMmi;
915 text = context.getText(R.string.puk_unlocked);
916 break;
917 }
918 // All other conditions for the COMPLETE mmi state will cause
919 // the case to fall through to message logic in common with
920 // the FAILED case.
921
922 case FAILED:
923 text = mmiCode.getMessage();
924 if (DBG) log("- using text from MMI message: '" + text + "'");
925 break;
926 default:
927 throw new IllegalStateException("Unexpected MmiCode state: " + state);
928 }
929
930 if (previousAlert != null) {
931 previousAlert.dismiss();
932 }
933
934 // Check to see if a UI exists for the PUK activation. If it does
935 // exist, then it indicates that we're trying to unblock the PUK.
936 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
937 if (DBG) log("displaying PUK unblocking progress dialog.");
938
939 // create the progress dialog, make sure the flags and type are
940 // set correctly.
Alex Hills779841a2015-10-22 13:23:28 -0400941 ProgressDialog pd = new ProgressDialog(app, THEME);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700942 pd.setTitle(title);
943 pd.setMessage(text);
944 pd.setCancelable(false);
945 pd.setIndeterminate(true);
946 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
947 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
948
949 // display the dialog
950 pd.show();
951
952 // indicate to the Phone app that the progress dialog has
953 // been assigned for the PUK unlock / SIM READY process.
954 app.setPukEntryProgressDialog(pd);
955
956 } else {
957 // In case of failure to unlock, we'll need to reset the
958 // PUK unlock activity, so that the user may try again.
959 if (app.getPUKEntryActivity() != null) {
960 app.setPukEntryActivity(null);
961 }
962
963 // A USSD in a pending state means that it is still
964 // interacting with the user.
965 if (state != MmiCode.State.PENDING) {
966 if (DBG) log("MMI code has finished running.");
967
968 if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
969 if (text == null || text.length() == 0)
970 return;
971
972 // displaying system alert dialog on the screen instead of
973 // using another activity to display the message. This
974 // places the message at the forefront of the UI.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700975
Etan Cohen37abbab2014-03-07 16:57:03 -0800976 if (sUssdDialog == null) {
Yorke Leee0f2b792014-10-15 12:30:44 -0700977 sUssdDialog = new AlertDialog.Builder(context, THEME)
Etan Cohen37abbab2014-03-07 16:57:03 -0800978 .setPositiveButton(R.string.ok, null)
979 .setCancelable(true)
980 .setOnDismissListener(new DialogInterface.OnDismissListener() {
981 @Override
982 public void onDismiss(DialogInterface dialog) {
983 sUssdMsg.setLength(0);
984 }
985 })
986 .create();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700987
Etan Cohen37abbab2014-03-07 16:57:03 -0800988 sUssdDialog.getWindow().setType(
Wenlu Wue8e05712015-03-06 14:20:18 +0100989 WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
Etan Cohen37abbab2014-03-07 16:57:03 -0800990 sUssdDialog.getWindow().addFlags(
991 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
992 }
993 if (sUssdMsg.length() != 0) {
994 sUssdMsg
995 .insert(0, "\n")
996 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
997 .insert(0, "\n");
998 }
999 sUssdMsg.insert(0, text);
1000 sUssdDialog.setMessage(sUssdMsg.toString());
1001 sUssdDialog.show();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001002 } else {
1003 if (DBG) log("USSD code has requested user input. Constructing input dialog.");
1004
1005 // USSD MMI code that is interacting with the user. The
1006 // basic set of steps is this:
1007 // 1. User enters a USSD request
1008 // 2. We recognize the request and displayMMIInitiate
1009 // (above) creates a progress dialog.
1010 // 3. Request returns and we get a PENDING or COMPLETE
1011 // message.
1012 // 4. These MMI messages are caught in the PhoneApp
1013 // (onMMIComplete) and the InCallScreen
1014 // (mHandler.handleMessage) which bring up this dialog
1015 // and closes the original progress dialog,
1016 // respectively.
1017 // 5. If the message is anything other than PENDING,
1018 // we are done, and the alert dialog (directly above)
1019 // displays the outcome.
1020 // 6. If the network is requesting more information from
1021 // the user, the MMI will be in a PENDING state, and
1022 // we display this dialog with the message.
1023 // 7. User input, or cancel requests result in a return
1024 // to step 1. Keep in mind that this is the only
1025 // time that a USSD should be canceled.
1026
1027 // inflate the layout with the scrolling text area for the dialog.
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001028 ContextThemeWrapper contextThemeWrapper =
1029 new ContextThemeWrapper(context, R.style.DialerAlertDialogTheme);
1030 LayoutInflater inflater = (LayoutInflater) contextThemeWrapper.getSystemService(
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001031 Context.LAYOUT_INFLATER_SERVICE);
1032 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
1033
1034 // get the input field.
1035 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
1036
1037 // specify the dialog's click listener, with SEND and CANCEL logic.
1038 final DialogInterface.OnClickListener mUSSDDialogListener =
1039 new DialogInterface.OnClickListener() {
1040 public void onClick(DialogInterface dialog, int whichButton) {
1041 switch (whichButton) {
1042 case DialogInterface.BUTTON_POSITIVE:
1043 // As per spec 24.080, valid length of ussd string
1044 // is 1 - 160. If length is out of the range then
1045 // display toast message & Cancel MMI operation.
1046 if (inputText.length() < MIN_USSD_LEN
1047 || inputText.length() > MAX_USSD_LEN) {
1048 Toast.makeText(app,
1049 app.getResources().getString(R.string.enter_input,
1050 MIN_USSD_LEN, MAX_USSD_LEN),
1051 Toast.LENGTH_LONG).show();
1052 if (mmiCode.isCancelable()) {
1053 mmiCode.cancel();
1054 }
1055 } else {
1056 phone.sendUssdResponse(inputText.getText().toString());
1057 }
1058 break;
1059 case DialogInterface.BUTTON_NEGATIVE:
1060 if (mmiCode.isCancelable()) {
1061 mmiCode.cancel();
1062 }
1063 break;
1064 }
1065 }
1066 };
1067
1068 // build the dialog
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001069 final AlertDialog newDialog = new AlertDialog.Builder(contextThemeWrapper)
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001070 .setMessage(text)
1071 .setView(dialogView)
1072 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
1073 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
1074 .setCancelable(false)
1075 .create();
1076
1077 // attach the key listener to the dialog's input field and make
1078 // sure focus is set.
1079 final View.OnKeyListener mUSSDDialogInputListener =
1080 new View.OnKeyListener() {
1081 public boolean onKey(View v, int keyCode, KeyEvent event) {
1082 switch (keyCode) {
1083 case KeyEvent.KEYCODE_CALL:
1084 case KeyEvent.KEYCODE_ENTER:
1085 if(event.getAction() == KeyEvent.ACTION_DOWN) {
1086 phone.sendUssdResponse(inputText.getText().toString());
1087 newDialog.dismiss();
1088 }
1089 return true;
1090 }
1091 return false;
1092 }
1093 };
1094 inputText.setOnKeyListener(mUSSDDialogInputListener);
1095 inputText.requestFocus();
1096
1097 // set the window properties of the dialog
1098 newDialog.getWindow().setType(
1099 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1100 newDialog.getWindow().addFlags(
1101 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1102
1103 // now show the dialog!
1104 newDialog.show();
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001105
1106 newDialog.getButton(DialogInterface.BUTTON_POSITIVE)
1107 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
1108 newDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
1109 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001110 }
1111 }
1112 }
1113
1114 /**
1115 * Cancels the current pending MMI operation, if applicable.
1116 * @return true if we canceled an MMI operation, or false
1117 * if the current pending MMI wasn't cancelable
1118 * or if there was no current pending MMI at all.
1119 *
1120 * @see displayMMIInitiate
1121 */
1122 static boolean cancelMmiCode(Phone phone) {
1123 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
1124 int count = pendingMmis.size();
1125 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
1126
1127 boolean canceled = false;
1128 if (count > 0) {
1129 // assume that we only have one pending MMI operation active at a time.
1130 // I don't think it's possible to enter multiple MMI codes concurrently
1131 // in the phone UI, because during the MMI operation, an Alert panel
1132 // is displayed, which prevents more MMI code from being entered.
1133 MmiCode mmiCode = pendingMmis.get(0);
1134 if (mmiCode.isCancelable()) {
1135 mmiCode.cancel();
1136 canceled = true;
1137 }
1138 }
1139 return canceled;
1140 }
1141
1142 public static class VoiceMailNumberMissingException extends Exception {
1143 VoiceMailNumberMissingException() {
1144 super();
1145 }
1146
1147 VoiceMailNumberMissingException(String msg) {
1148 super(msg);
1149 }
1150 }
1151
1152 /**
1153 * Given an Intent (which is presumably the ACTION_CALL intent that
1154 * initiated this outgoing call), figure out the actual phone number we
1155 * should dial.
1156 *
1157 * Note that the returned "number" may actually be a SIP address,
1158 * if the specified intent contains a sip: URI.
1159 *
1160 * This method is basically a wrapper around PhoneUtils.getNumberFromIntent(),
1161 * except it's also aware of the EXTRA_ACTUAL_NUMBER_TO_DIAL extra.
1162 * (That extra, if present, tells us the exact string to pass down to the
1163 * telephony layer. It's guaranteed to be safe to dial: it's either a PSTN
1164 * phone number with separators and keypad letters stripped out, or a raw
1165 * unencoded SIP address.)
1166 *
1167 * @return the phone number corresponding to the specified Intent, or null
1168 * if the Intent has no action or if the intent's data is malformed or
1169 * missing.
1170 *
1171 * @throws VoiceMailNumberMissingException if the intent
1172 * contains a "voicemail" URI, but there's no voicemail
1173 * number configured on the device.
1174 */
1175 public static String getInitialNumber(Intent intent)
1176 throws PhoneUtils.VoiceMailNumberMissingException {
1177 if (DBG) log("getInitialNumber(): " + intent);
1178
1179 String action = intent.getAction();
1180 if (TextUtils.isEmpty(action)) {
1181 return null;
1182 }
1183
1184 // If the EXTRA_ACTUAL_NUMBER_TO_DIAL extra is present, get the phone
1185 // number from there. (That extra takes precedence over the actual data
1186 // included in the intent.)
1187 if (intent.hasExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL)) {
1188 String actualNumberToDial =
1189 intent.getStringExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL);
1190 if (DBG) {
1191 log("==> got EXTRA_ACTUAL_NUMBER_TO_DIAL; returning '"
1192 + toLogSafePhoneNumber(actualNumberToDial) + "'");
1193 }
1194 return actualNumberToDial;
1195 }
1196
1197 return getNumberFromIntent(PhoneGlobals.getInstance(), intent);
1198 }
1199
1200 /**
1201 * Gets the phone number to be called from an intent. Requires a Context
1202 * to access the contacts database, and a Phone to access the voicemail
1203 * number.
1204 *
1205 * <p>If <code>phone</code> is <code>null</code>, the function will return
1206 * <code>null</code> for <code>voicemail:</code> URIs;
1207 * if <code>context</code> is <code>null</code>, the function will return
1208 * <code>null</code> for person/phone URIs.</p>
1209 *
1210 * <p>If the intent contains a <code>sip:</code> URI, the returned
1211 * "number" is actually the SIP address.
1212 *
1213 * @param context a context to use (or
1214 * @param intent the intent
1215 *
1216 * @throws VoiceMailNumberMissingException if <code>intent</code> contains
1217 * a <code>voicemail:</code> URI, but <code>phone</code> does not
1218 * have a voicemail number set.
1219 *
1220 * @return the phone number (or SIP address) that would be called by the intent,
1221 * or <code>null</code> if the number cannot be found.
1222 */
1223 private static String getNumberFromIntent(Context context, Intent intent)
1224 throws VoiceMailNumberMissingException {
1225 Uri uri = intent.getData();
1226 String scheme = uri.getScheme();
1227
1228 // The sip: scheme is simple: just treat the rest of the URI as a
1229 // SIP address.
Jay Shrauner137458b2014-09-05 14:27:25 -07001230 if (PhoneAccount.SCHEME_SIP.equals(scheme)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001231 return uri.getSchemeSpecificPart();
1232 }
1233
1234 // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
1235 // the other cases (i.e. tel: and voicemail: and contact: URIs.)
1236
1237 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
1238
1239 // Check for a voicemail-dialing request. If the voicemail number is
1240 // empty, throw a VoiceMailNumberMissingException.
Jay Shrauner137458b2014-09-05 14:27:25 -07001241 if (PhoneAccount.SCHEME_VOICEMAIL.equals(scheme) &&
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001242 (number == null || TextUtils.isEmpty(number)))
1243 throw new VoiceMailNumberMissingException();
1244
1245 return number;
1246 }
1247
1248 /**
1249 * Returns the caller-id info corresponding to the specified Connection.
1250 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
1251 * extract a phone number from the specified Connection, and feed that
1252 * number into CallerInfo.getCallerInfo().)
1253 *
1254 * The returned CallerInfo may be null in certain error cases, like if the
1255 * specified Connection was null, or if we weren't able to get a valid
1256 * phone number from the Connection.
1257 *
1258 * Finally, if the getCallerInfo() call did succeed, we save the resulting
1259 * CallerInfo object in the "userData" field of the Connection.
1260 *
1261 * NOTE: This API should be avoided, with preference given to the
1262 * asynchronous startGetCallerInfo API.
1263 */
1264 static CallerInfo getCallerInfo(Context context, Connection c) {
1265 CallerInfo info = null;
1266
1267 if (c != null) {
1268 //See if there is a URI attached. If there is, this means
1269 //that there is no CallerInfo queried yet, so we'll need to
1270 //replace the URI with a full CallerInfo object.
1271 Object userDataObject = c.getUserData();
1272 if (userDataObject instanceof Uri) {
1273 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1274 if (info != null) {
1275 c.setUserData(info);
1276 }
1277 } else {
1278 if (userDataObject instanceof CallerInfoToken) {
1279 //temporary result, while query is running
1280 info = ((CallerInfoToken) userDataObject).currentInfo;
1281 } else {
1282 //final query result
1283 info = (CallerInfo) userDataObject;
1284 }
1285 if (info == null) {
1286 // No URI, or Existing CallerInfo, so we'll have to make do with
1287 // querying a new CallerInfo using the connection's phone number.
1288 String number = c.getAddress();
1289
1290 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
1291
1292 if (!TextUtils.isEmpty(number)) {
1293 info = CallerInfo.getCallerInfo(context, number);
1294 if (info != null) {
1295 c.setUserData(info);
1296 }
1297 }
1298 }
1299 }
1300 }
1301 return info;
1302 }
1303
1304 /**
1305 * Class returned by the startGetCallerInfo call to package a temporary
1306 * CallerInfo Object, to be superceded by the CallerInfo Object passed
1307 * into the listener when the query with token mAsyncQueryToken is complete.
1308 */
1309 public static class CallerInfoToken {
1310 /**indicates that there will no longer be updates to this request.*/
1311 public boolean isFinal;
1312
1313 public CallerInfo currentInfo;
1314 public CallerInfoAsyncQuery asyncQuery;
1315 }
1316
1317 /**
1318 * Start a CallerInfo Query based on the earliest connection in the call.
1319 */
1320 static CallerInfoToken startGetCallerInfo(Context context, Call call,
1321 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1322 Connection conn = null;
1323 int phoneType = call.getPhone().getPhoneType();
1324 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1325 conn = call.getLatestConnection();
1326 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001327 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07001328 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001329 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001330 conn = call.getEarliestConnection();
1331 } else {
1332 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1333 }
1334
1335 return startGetCallerInfo(context, conn, listener, cookie);
1336 }
1337
Chiao Chenge365ba72013-09-26 14:18:12 -07001338 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1339 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1340 return startGetCallerInfo(context, c, listener, cookie, null);
1341 }
1342
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001343 /**
1344 * place a temporary callerinfo object in the hands of the caller and notify
1345 * caller when the actual query is done.
1346 */
1347 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -07001348 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
1349 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001350 CallerInfoToken cit;
1351
1352 if (c == null) {
1353 //TODO: perhaps throw an exception here.
1354 cit = new CallerInfoToken();
1355 cit.asyncQuery = null;
1356 return cit;
1357 }
1358
1359 Object userDataObject = c.getUserData();
1360
1361 // There are now 3 states for the Connection's userData object:
1362 //
1363 // (1) Uri - query has not been executed yet
1364 //
1365 // (2) CallerInfoToken - query is executing, but has not completed.
1366 //
1367 // (3) CallerInfo - query has executed.
1368 //
1369 // In each case we have slightly different behaviour:
1370 // 1. If the query has not been executed yet (Uri or null), we start
1371 // query execution asynchronously, and note it by attaching a
1372 // CallerInfoToken as the userData.
1373 // 2. If the query is executing (CallerInfoToken), we've essentially
1374 // reached a state where we've received multiple requests for the
1375 // same callerInfo. That means that once the query is complete,
1376 // we'll need to execute the additional listener requested.
1377 // 3. If the query has already been executed (CallerInfo), we just
1378 // return the CallerInfo object as expected.
1379 // 4. Regarding isFinal - there are cases where the CallerInfo object
1380 // will not be attached, like when the number is empty (caller id
1381 // blocking). This flag is used to indicate that the
1382 // CallerInfoToken object is going to be permanent since no
1383 // query results will be returned. In the case where a query
1384 // has been completed, this flag is used to indicate to the caller
1385 // that the data will not be updated since it is valid.
1386 //
1387 // Note: For the case where a number is NOT retrievable, we leave
1388 // the CallerInfo as null in the CallerInfoToken. This is
1389 // something of a departure from the original code, since the old
1390 // code manufactured a CallerInfo object regardless of the query
1391 // outcome. From now on, we will append an empty CallerInfo
1392 // object, to mirror previous behaviour, and to avoid Null Pointer
1393 // Exceptions.
1394
1395 if (userDataObject instanceof Uri) {
1396 // State (1): query has not been executed yet
1397
1398 //create a dummy callerinfo, populate with what we know from URI.
1399 cit = new CallerInfoToken();
1400 cit.currentInfo = new CallerInfo();
1401 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1402 (Uri) userDataObject, sCallerInfoQueryListener, c);
1403 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1404 cit.isFinal = false;
1405
1406 c.setUserData(cit);
1407
1408 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1409
1410 } else if (userDataObject == null) {
1411 // No URI, or Existing CallerInfo, so we'll have to make do with
1412 // querying a new CallerInfo using the connection's phone number.
1413 String number = c.getAddress();
1414
Chiao Cheng685dcb62013-10-02 11:51:06 -07001415 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -07001416 // Gateway number, the connection number is actually the gateway number.
1417 // need to lookup via dialed number.
1418 number = info.trueNumber;
1419 }
1420
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001421 if (DBG) {
1422 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
1423 log("- number (address): " + toLogSafePhoneNumber(number));
1424 log("- c: " + c);
1425 log("- phone: " + c.getCall().getPhone());
1426 int phoneType = c.getCall().getPhone().getPhoneType();
1427 log("- phoneType: " + phoneType);
1428 switch (phoneType) {
1429 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
1430 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -07001431 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001432 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
1433 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001434 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
1435 log(" ==> PHONE_TYPE_THIRD_PARTY");
1436 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001437 default: log(" ==> Unknown phone type"); break;
1438 }
1439 }
1440
1441 cit = new CallerInfoToken();
1442 cit.currentInfo = new CallerInfo();
1443
1444 // Store CNAP information retrieved from the Connection (we want to do this
1445 // here regardless of whether the number is empty or not).
1446 cit.currentInfo.cnapName = c.getCnapName();
1447 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1448 // by ContactInfo later
1449 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1450 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1451
1452 if (VDBG) {
1453 log("startGetCallerInfo: number = " + number);
1454 log("startGetCallerInfo: CNAP Info from FW(1): name="
1455 + cit.currentInfo.cnapName
1456 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1457 }
1458
1459 // handling case where number is null (caller id hidden) as well.
1460 if (!TextUtils.isEmpty(number)) {
1461 // Check for special CNAP cases and modify the CallerInfo accordingly
1462 // to be sure we keep the right information to display/log later
1463 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
1464 cit.currentInfo.numberPresentation);
1465
1466 cit.currentInfo.phoneNumber = number;
1467 // For scenarios where we may receive a valid number from the network but a
1468 // restricted/unavailable presentation, we do not want to perform a contact query
1469 // (see note on isFinal above). So we set isFinal to true here as well.
1470 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1471 cit.isFinal = true;
1472 } else {
1473 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
1474 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1475 number, sCallerInfoQueryListener, c);
1476 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1477 cit.isFinal = false;
1478 }
1479 } else {
1480 // This is the case where we are querying on a number that
1481 // is null or empty, like a caller whose caller id is
1482 // blocked or empty (CLIR). The previous behaviour was to
1483 // throw a null CallerInfo object back to the user, but
1484 // this departure is somewhat cleaner.
1485 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1486 cit.isFinal = true; // please see note on isFinal, above.
1487 }
1488
1489 c.setUserData(cit);
1490
1491 if (DBG) {
1492 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
1493 }
1494
1495 } else if (userDataObject instanceof CallerInfoToken) {
1496 // State (2): query is executing, but has not completed.
1497
1498 // just tack on this listener to the queue.
1499 cit = (CallerInfoToken) userDataObject;
1500
1501 // handling case where number is null (caller id hidden) as well.
1502 if (cit.asyncQuery != null) {
1503 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1504
1505 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1506 listener.getClass().toString());
1507 } else {
1508 // handling case where number/name gets updated later on by the network
1509 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -07001510
1511 if (info != null) {
1512 // Gateway number, the connection number is actually the gateway number.
1513 // need to lookup via dialed number.
1514 updatedNumber = info.trueNumber;
1515 }
1516
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001517 if (DBG) {
1518 log("startGetCallerInfo: updatedNumber initially = "
1519 + toLogSafePhoneNumber(updatedNumber));
1520 }
1521 if (!TextUtils.isEmpty(updatedNumber)) {
1522 // Store CNAP information retrieved from the Connection
1523 cit.currentInfo.cnapName = c.getCnapName();
1524 // This can still get overwritten by ContactInfo
1525 cit.currentInfo.name = cit.currentInfo.cnapName;
1526 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1527 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1528
1529 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1530 updatedNumber, cit.currentInfo.numberPresentation);
1531
1532 cit.currentInfo.phoneNumber = updatedNumber;
1533 if (DBG) {
1534 log("startGetCallerInfo: updatedNumber="
1535 + toLogSafePhoneNumber(updatedNumber));
1536 }
1537 if (VDBG) {
1538 log("startGetCallerInfo: CNAP Info from FW(2): name="
1539 + cit.currentInfo.cnapName
1540 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1541 } else if (DBG) {
1542 log("startGetCallerInfo: CNAP Info from FW(2)");
1543 }
1544 // For scenarios where we may receive a valid number from the network but a
1545 // restricted/unavailable presentation, we do not want to perform a contact query
1546 // (see note on isFinal above). So we set isFinal to true here as well.
1547 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1548 cit.isFinal = true;
1549 } else {
1550 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1551 updatedNumber, sCallerInfoQueryListener, c);
1552 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1553 cit.isFinal = false;
1554 }
1555 } else {
1556 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1557 if (cit.currentInfo == null) {
1558 cit.currentInfo = new CallerInfo();
1559 }
1560 // Store CNAP information retrieved from the Connection
1561 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
1562 // overwritten by ContactInfo
1563 cit.currentInfo.name = cit.currentInfo.cnapName;
1564 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1565 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1566
1567 if (VDBG) {
1568 log("startGetCallerInfo: CNAP Info from FW(3): name="
1569 + cit.currentInfo.cnapName
1570 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1571 } else if (DBG) {
1572 log("startGetCallerInfo: CNAP Info from FW(3)");
1573 }
1574 cit.isFinal = true; // please see note on isFinal, above.
1575 }
1576 }
1577 } else {
1578 // State (3): query is complete.
1579
1580 // The connection's userDataObject is a full-fledged
1581 // CallerInfo instance. Wrap it in a CallerInfoToken and
1582 // return it to the user.
1583
1584 cit = new CallerInfoToken();
1585 cit.currentInfo = (CallerInfo) userDataObject;
1586 cit.asyncQuery = null;
1587 cit.isFinal = true;
1588 // since the query is already done, call the listener.
1589 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1590 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
1591 }
1592 return cit;
1593 }
1594
1595 /**
1596 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
1597 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
1598 */
1599 private static final int QUERY_TOKEN = -1;
1600 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1601 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1602 /**
1603 * When the query completes, we stash the resulting CallerInfo
1604 * object away in the Connection's "userData" (where it will
1605 * later be retrieved by the in-call UI.)
1606 */
1607 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1608 if (DBG) log("query complete, updating connection.userdata");
1609 Connection conn = (Connection) cookie;
1610
1611 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1612 // If no ContactInfo, then we want to use CNAP information coming from network
1613 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1614 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1615 // If the number presentation has not been set by
1616 // the ContactInfo, use the one from the
1617 // connection.
1618
1619 // TODO: Need a new util method to merge the info
1620 // from the Connection in a CallerInfo object.
1621 // Here 'ci' is a new CallerInfo instance read
1622 // from the DB. It has lost all the connection
1623 // info preset before the query (see PhoneUtils
1624 // line 1334). We should have a method to merge
1625 // back into this new instance the info from the
1626 // connection object not set by the DB. If the
1627 // Connection already has a CallerInfo instance in
1628 // userData, then we could use this instance to
1629 // fill 'ci' in. The same routine could be used in
1630 // PhoneUtils.
1631 if (0 == ci.numberPresentation) {
1632 ci.numberPresentation = conn.getNumberPresentation();
1633 }
1634 } else {
1635 // No matching contact was found for this number.
1636 // Return a new CallerInfo based solely on the CNAP
1637 // information from the network.
1638
1639 CallerInfo newCi = getCallerInfo(null, conn);
1640
1641 // ...but copy over the (few) things we care about
1642 // from the original CallerInfo object:
1643 if (newCi != null) {
1644 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1645 newCi.geoDescription = ci.geoDescription; // To get geo description string
1646 ci = newCi;
1647 }
1648 }
1649
1650 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1651 conn.setUserData(ci);
1652 }
1653 };
1654
1655
1656 /**
1657 * Returns a single "name" for the specified given a CallerInfo object.
1658 * If the name is null, return defaultString as the default value, usually
1659 * context.getString(R.string.unknown).
1660 */
1661 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1662 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1663
1664 String compactName = null;
1665 if (ci != null) {
1666 if (TextUtils.isEmpty(ci.name)) {
1667 // Perform any modifications for special CNAP cases to
1668 // the phone number being displayed, if applicable.
1669 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1670 ci.numberPresentation);
1671 } else {
1672 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1673 compactName = ci.name;
1674 }
1675 }
1676
1677 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1678 // If we're still null/empty here, then check if we have a presentation
1679 // string that takes precedence that we could return, otherwise display
1680 // "unknown" string.
1681 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1682 compactName = context.getString(R.string.private_num);
1683 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1684 compactName = context.getString(R.string.payphone);
1685 } else {
1686 compactName = context.getString(R.string.unknown);
1687 }
1688 }
1689 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1690 return compactName;
1691 }
1692
1693 /**
1694 * Returns true if the specified Call is a "conference call", meaning
1695 * that it owns more than one Connection object. This information is
1696 * used to trigger certain UI changes that appear when a conference
1697 * call is active (like displaying the label "Conference call", and
1698 * enabling the "Manage conference" UI.)
1699 *
1700 * Watch out: This method simply checks the number of Connections,
1701 * *not* their states. So if a Call has (for example) one ACTIVE
1702 * connection and one DISCONNECTED connection, this method will return
1703 * true (which is unintuitive, since the Call isn't *really* a
1704 * conference call any more.)
1705 *
1706 * @return true if the specified call has more than one connection (in any state.)
1707 */
1708 static boolean isConferenceCall(Call call) {
1709 // CDMA phones don't have the same concept of "conference call" as
1710 // GSM phones do; there's no special "conference call" state of
1711 // the UI or a "manage conference" function. (Instead, when
1712 // you're in a 3-way call, all we can do is display the "generic"
1713 // state of the UI.) So as far as the in-call UI is concerned,
1714 // Conference corresponds to generic display.
1715 final PhoneGlobals app = PhoneGlobals.getInstance();
1716 int phoneType = call.getPhone().getPhoneType();
1717 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1718 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
1719 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
1720 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1721 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
1722 return true;
1723 }
1724 } else {
1725 List<Connection> connections = call.getConnections();
1726 if (connections != null && connections.size() > 1) {
1727 return true;
1728 }
1729 }
1730 return false;
1731
1732 // TODO: We may still want to change the semantics of this method
1733 // to say that a given call is only really a conference call if
1734 // the number of ACTIVE connections, not the total number of
1735 // connections, is greater than one. (See warning comment in the
1736 // javadoc above.)
1737 // Here's an implementation of that:
1738 // if (connections == null) {
1739 // return false;
1740 // }
1741 // int numActiveConnections = 0;
1742 // for (Connection conn : connections) {
1743 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
1744 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1745 // if (numActiveConnections > 1) {
1746 // return true;
1747 // }
1748 // }
1749 // return false;
1750 }
1751
1752 /**
1753 * Launch the Dialer to start a new call.
1754 * This is just a wrapper around the ACTION_DIAL intent.
1755 */
1756 /* package */ static boolean startNewCall(final CallManager cm) {
1757 final PhoneGlobals app = PhoneGlobals.getInstance();
1758
1759 // Sanity-check that this is OK given the current state of the phone.
1760 if (!okToAddCall(cm)) {
1761 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1762 dumpCallManager();
1763 return false;
1764 }
1765
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001766 Intent intent = new Intent(Intent.ACTION_DIAL);
1767 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1768
1769 // when we request the dialer come up, we also want to inform
1770 // it that we're going through the "add call" option from the
1771 // InCallScreen / PhoneUtils.
1772 intent.putExtra(ADD_CALL_MODE_KEY, true);
1773 try {
1774 app.startActivity(intent);
1775 } catch (ActivityNotFoundException e) {
1776 // This is rather rare but possible.
1777 // Note: this method is used even when the phone is encrypted. At that moment
1778 // the system may not find any Activity which can accept this Intent.
1779 Log.e(LOG_TAG, "Activity for adding calls isn't found.");
1780 return false;
1781 }
1782
1783 return true;
1784 }
1785
1786 /**
1787 * Turns on/off speaker.
1788 *
1789 * @param context Context
1790 * @param flag True when speaker should be on. False otherwise.
1791 * @param store True when the settings should be stored in the device.
1792 */
1793 /* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1794 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
1795 final PhoneGlobals app = PhoneGlobals.getInstance();
1796
1797 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1798 audioManager.setSpeakerphoneOn(flag);
1799
1800 // record the speaker-enable value
1801 if (store) {
1802 sIsSpeakerEnabled = flag;
1803 }
1804
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001805 // We also need to make a fresh call to PhoneApp.updateWakeState()
1806 // any time the speaker state changes, since the screen timeout is
1807 // sometimes different depending on whether or not the speaker is
1808 // in use.
1809 app.updateWakeState();
1810
Hariprasad Jayakumareee6a9e2014-04-25 15:33:13 -07001811 app.mCM.setEchoSuppressionEnabled();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001812 }
1813
1814 /**
1815 * Restore the speaker mode, called after a wired headset disconnect
1816 * event.
1817 */
1818 static void restoreSpeakerMode(Context context) {
1819 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1820
1821 // change the mode if needed.
1822 if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1823 turnOnSpeaker(context, sIsSpeakerEnabled, false);
1824 }
1825 }
1826
1827 static boolean isSpeakerOn(Context context) {
1828 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1829 return audioManager.isSpeakerphoneOn();
1830 }
1831
1832
1833 static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) {
1834 if (DBG) log("turnOnNoiseSuppression: " + flag);
1835 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1836
Jonathan Basseri3b9c21f2015-06-19 15:51:10 -07001837 PersistableBundle b = PhoneGlobals.getInstance().getCarrierConfig();
1838 if (!b.getBoolean(CarrierConfigManager.KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001839 return;
1840 }
1841
1842 if (flag) {
1843 audioManager.setParameters("noise_suppression=auto");
1844 } else {
1845 audioManager.setParameters("noise_suppression=off");
1846 }
1847
1848 // record the speaker-enable value
1849 if (store) {
1850 sIsNoiseSuppressionEnabled = flag;
1851 }
1852
1853 // TODO: implement and manage ICON
1854
1855 }
1856
1857 static void restoreNoiseSuppression(Context context) {
1858 if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled);
1859
Jonathan Basseri3b9c21f2015-06-19 15:51:10 -07001860 PersistableBundle b = PhoneGlobals.getInstance().getCarrierConfig();
1861 if (!b.getBoolean(CarrierConfigManager.KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001862 return;
1863 }
1864
1865 // change the mode if needed.
1866 if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) {
1867 turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false);
1868 }
1869 }
1870
1871 static boolean isNoiseSuppressionOn(Context context) {
1872
Jonathan Basseri3b9c21f2015-06-19 15:51:10 -07001873 PersistableBundle b = PhoneGlobals.getInstance().getCarrierConfig();
1874 if (!b.getBoolean(CarrierConfigManager.KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001875 return false;
1876 }
1877
1878 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1879 String noiseSuppression = audioManager.getParameters("noise_suppression");
1880 if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression);
1881 if (noiseSuppression.contains("off")) {
1882 return false;
1883 } else {
1884 return true;
1885 }
1886 }
1887
Santos Cordonc264cba2013-09-19 04:55:40 -07001888 static boolean isInEmergencyCall(CallManager cm) {
1889 for (Connection cn : cm.getActiveFgCall().getConnections()) {
Yorke Lee36bb2542014-06-05 08:09:52 -07001890 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
1891 cn.getAddress())) {
Santos Cordonc264cba2013-09-19 04:55:40 -07001892 return true;
1893 }
1894 }
1895 return false;
1896 }
1897
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001898 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001899 * Get the mute state of foreground phone, which has the current
1900 * foreground call
1901 */
1902 static boolean getMute() {
Santos Cordonbb2bcef2014-08-05 19:08:10 -07001903 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001904 }
1905
1906 /* package */ static void setAudioMode() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001907 }
1908
1909 /**
1910 * Sets the audio mode per current phone state.
1911 */
1912 /* package */ static void setAudioMode(CallManager cm) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001913 }
1914
1915 /**
1916 * Look for ANY connections on the phone that qualify as being
1917 * disconnected.
1918 *
1919 * @return true if we find a connection that is disconnected over
1920 * all the phone's call objects.
1921 */
1922 /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1923 return hasDisconnectedConnections(phone.getForegroundCall()) ||
1924 hasDisconnectedConnections(phone.getBackgroundCall()) ||
1925 hasDisconnectedConnections(phone.getRingingCall());
1926 }
1927
1928 /**
1929 * Iterate over all connections in a call to see if there are any
1930 * that are not alive (disconnected or idle).
1931 *
1932 * @return true if we find a connection that is disconnected, and
1933 * pending removal via
1934 * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
1935 */
1936 private static final boolean hasDisconnectedConnections(Call call) {
1937 // look through all connections for non-active ones.
1938 for (Connection c : call.getConnections()) {
1939 if (!c.isAlive()) {
1940 return true;
1941 }
1942 }
1943 return false;
1944 }
1945
1946 //
1947 // Misc UI policy helper functions
1948 //
1949
1950 /**
Christine Chenaf2fd0a2013-09-13 16:27:40 -07001951 * @return true if we're allowed to hold calls, given the current
1952 * state of the Phone.
1953 */
1954 /* package */ static boolean okToHoldCall(CallManager cm) {
1955 final Call fgCall = cm.getActiveFgCall();
1956 final boolean hasHoldingCall = cm.hasActiveBgCall();
1957 final Call.State fgCallState = fgCall.getState();
1958
1959 // The "Hold" control is disabled entirely if there's
1960 // no way to either hold or unhold in the current state.
1961 final boolean okToHold = (fgCallState == Call.State.ACTIVE) && !hasHoldingCall;
1962 final boolean okToUnhold = cm.hasActiveBgCall() && (fgCallState == Call.State.IDLE);
1963 final boolean canHold = okToHold || okToUnhold;
1964
1965 return canHold;
1966 }
1967
1968 /**
1969 * @return true if we support holding calls, given the current
1970 * state of the Phone.
1971 */
1972 /* package */ static boolean okToSupportHold(CallManager cm) {
1973 boolean supportsHold = false;
1974
1975 final Call fgCall = cm.getActiveFgCall();
1976 final boolean hasHoldingCall = cm.hasActiveBgCall();
1977 final Call.State fgCallState = fgCall.getState();
1978
1979 if (TelephonyCapabilities.supportsHoldAndUnhold(fgCall.getPhone())) {
1980 // This phone has the concept of explicit "Hold" and "Unhold" actions.
1981 supportsHold = true;
1982 } else if (hasHoldingCall && (fgCallState == Call.State.IDLE)) {
1983 // Even when foreground phone device doesn't support hold/unhold, phone devices
1984 // for background holding calls may do.
1985 final Call bgCall = cm.getFirstActiveBgCall();
1986 if (bgCall != null &&
1987 TelephonyCapabilities.supportsHoldAndUnhold(bgCall.getPhone())) {
1988 supportsHold = true;
1989 }
1990 }
1991 return supportsHold;
1992 }
1993
1994 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001995 * @return true if we're allowed to swap calls, given the current
1996 * state of the Phone.
1997 */
1998 /* package */ static boolean okToSwapCalls(CallManager cm) {
1999 int phoneType = cm.getDefaultPhone().getPhoneType();
2000 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
2001 // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
2002 // state by either accepting a Call Waiting or by merging two calls
2003 PhoneGlobals app = PhoneGlobals.getInstance();
2004 return (app.cdmaPhoneCallState.getCurrentCallState()
2005 == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
2006 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002007 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07002008 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002009 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002010 // GSM: "Swap" is available if both lines are in use and there's no
2011 // incoming call. (Actually we need to verify that the active
2012 // call really is in the ACTIVE state and the holding call really
2013 // is in the HOLDING state, since you *can't* actually swap calls
2014 // when the foreground call is DIALING or ALERTING.)
2015 return !cm.hasActiveRingingCall()
2016 && (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
2017 && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
2018 } else {
2019 throw new IllegalStateException("Unexpected phone type: " + phoneType);
2020 }
2021 }
2022
2023 /**
2024 * @return true if we're allowed to merge calls, given the current
2025 * state of the Phone.
2026 */
2027 /* package */ static boolean okToMergeCalls(CallManager cm) {
2028 int phoneType = cm.getFgPhone().getPhoneType();
2029 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
2030 // CDMA: "Merge" is enabled only when the user is in a 3Way call.
2031 PhoneGlobals app = PhoneGlobals.getInstance();
2032 return ((app.cdmaPhoneCallState.getCurrentCallState()
2033 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
2034 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
2035 } else {
2036 // GSM: "Merge" is available if both lines are in use and there's no
2037 // incoming call, *and* the current conference isn't already
2038 // "full".
2039 // TODO: shall move all okToMerge logic to CallManager
2040 return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
2041 && cm.hasActiveBgCall()
2042 && cm.canConference(cm.getFirstActiveBgCall());
2043 }
2044 }
2045
2046 /**
2047 * @return true if the UI should let you add a new call, given the current
2048 * state of the Phone.
2049 */
2050 /* package */ static boolean okToAddCall(CallManager cm) {
2051 Phone phone = cm.getActiveFgCall().getPhone();
2052
2053 // "Add call" is never allowed in emergency callback mode (ECM).
2054 if (isPhoneInEcm(phone)) {
2055 return false;
2056 }
2057
2058 int phoneType = phone.getPhoneType();
2059 final Call.State fgCallState = cm.getActiveFgCall().getState();
2060 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
2061 // CDMA: "Add call" button is only enabled when:
2062 // - ForegroundCall is in ACTIVE state
2063 // - After 30 seconds of user Ignoring/Missing a Call Waiting call.
2064 PhoneGlobals app = PhoneGlobals.getInstance();
2065 return ((fgCallState == Call.State.ACTIVE)
2066 && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
2067 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002068 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07002069 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002070 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002071 // GSM: "Add call" is available only if ALL of the following are true:
2072 // - There's no incoming ringing call
2073 // - There's < 2 lines in use
2074 // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
2075 // (We mainly need to make sure it *isn't* DIALING or ALERTING.)
2076 final boolean hasRingingCall = cm.hasActiveRingingCall();
2077 final boolean hasActiveCall = cm.hasActiveFgCall();
2078 final boolean hasHoldingCall = cm.hasActiveBgCall();
2079 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2080
2081 return !hasRingingCall
2082 && !allLinesTaken
2083 && ((fgCallState == Call.State.ACTIVE)
2084 || (fgCallState == Call.State.IDLE)
2085 || (fgCallState == Call.State.DISCONNECTED));
2086 } else {
2087 throw new IllegalStateException("Unexpected phone type: " + phoneType);
2088 }
2089 }
2090
2091 /**
2092 * Based on the input CNAP number string,
2093 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
2094 * Otherwise, return CNAP_SPECIAL_CASE_NO.
2095 */
2096 private static int checkCnapSpecialCases(String n) {
2097 if (n.equals("PRIVATE") ||
2098 n.equals("P") ||
2099 n.equals("RES")) {
2100 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
2101 return PhoneConstants.PRESENTATION_RESTRICTED;
2102 } else if (n.equals("UNAVAILABLE") ||
2103 n.equals("UNKNOWN") ||
2104 n.equals("UNA") ||
2105 n.equals("U")) {
2106 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
2107 return PhoneConstants.PRESENTATION_UNKNOWN;
2108 } else {
2109 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
2110 return CNAP_SPECIAL_CASE_NO;
2111 }
2112 }
2113
2114 /**
2115 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
2116 * from the network to indicate different number presentations, convert them to
2117 * expected number and presentation values within the CallerInfo object.
2118 * @param number number we use to verify if we are in a corner case
2119 * @param presentation presentation value used to verify if we are in a corner case
2120 * @return the new String that should be used for the phone number
2121 */
2122 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
2123 String number, int presentation) {
2124 // Obviously we return number if ci == null, but still return number if
2125 // number == null, because in these cases the correct string will still be
2126 // displayed/logged after this function returns based on the presentation value.
2127 if (ci == null || number == null) return number;
2128
2129 if (DBG) {
2130 log("modifyForSpecialCnapCases: initially, number="
2131 + toLogSafePhoneNumber(number)
2132 + ", presentation=" + presentation + " ci " + ci);
2133 }
2134
2135 // "ABSENT NUMBER" is a possible value we could get from the network as the
2136 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
2137 // and fix the presentation to be the same.
2138 final String[] absentNumberValues =
2139 context.getResources().getStringArray(R.array.absent_num);
2140 if (Arrays.asList(absentNumberValues).contains(number)
2141 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
2142 number = context.getString(R.string.unknown);
2143 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
2144 }
2145
2146 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
2147 // cases only apply if we received an allowed presentation from the network, so check
2148 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
2149 // match the presentation passed in for verification (meaning we changed it previously
2150 // because it's a corner case and we're being called from a different entry point).
2151 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
2152 || (ci.numberPresentation != presentation
2153 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
2154 int cnapSpecialCase = checkCnapSpecialCases(number);
2155 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
2156 // For all special strings, change number & numberPresentation.
2157 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
2158 number = context.getString(R.string.private_num);
2159 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
2160 number = context.getString(R.string.unknown);
2161 }
2162 if (DBG) {
2163 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
2164 + "; presentation now=" + cnapSpecialCase);
2165 }
2166 ci.numberPresentation = cnapSpecialCase;
2167 }
2168 }
2169 if (DBG) {
2170 log("modifyForSpecialCnapCases: returning number string="
2171 + toLogSafePhoneNumber(number));
2172 }
2173 return number;
2174 }
2175
2176 //
2177 // Support for 3rd party phone service providers.
2178 //
2179
2180 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002181 * Check if a phone number can be route through a 3rd party
2182 * gateway. The number must be a global phone number in numerical
2183 * form (1-800-666-SEXY won't work).
2184 *
2185 * MMI codes and the like cannot be used as a dial number for the
2186 * gateway either.
2187 *
2188 * @param number To be dialed via a 3rd party gateway.
2189 * @return true If the number can be routed through the 3rd party network.
2190 */
Santos Cordon69a69192013-08-22 14:25:42 -07002191 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002192 if (TextUtils.isEmpty(number)) {
2193 return false;
2194 }
2195 number = PhoneNumberUtils.stripSeparators(number);
2196 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
2197 return false;
2198 }
2199 number = PhoneNumberUtils.extractNetworkPortion(number);
2200 return PhoneNumberUtils.isGlobalPhoneNumber(number);
2201 }
2202
2203 /**
2204 * This function is called when phone answers or places a call.
2205 * Check if the phone is in a car dock or desk dock.
2206 * If yes, turn on the speaker, when no wired or BT headsets are connected.
2207 * Otherwise do nothing.
2208 * @return true if activated
2209 */
2210 private static boolean activateSpeakerIfDocked(Phone phone) {
2211 if (DBG) log("activateSpeakerIfDocked()...");
2212
2213 boolean activated = false;
2214 if (PhoneGlobals.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
2215 if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
Santos Cordon593ab382013-08-06 21:58:23 -07002216 final PhoneGlobals app = PhoneGlobals.getInstance();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002217
Christine Chen3e0f0412013-09-18 20:33:49 -07002218 // TODO: This function should move to AudioRouter
Santos Cordon593ab382013-08-06 21:58:23 -07002219 final BluetoothManager btManager = app.getBluetoothManager();
Santos Cordonbb2bcef2014-08-05 19:08:10 -07002220 //final WiredHeadsetManager wiredHeadset = app.getWiredHeadsetManager();
2221 //final AudioRouter audioRouter = app.getAudioRouter();
Santos Cordon593ab382013-08-06 21:58:23 -07002222
Santos Cordonbb2bcef2014-08-05 19:08:10 -07002223 /*if (!wiredHeadset.isHeadsetPlugged() && !btManager.isBluetoothHeadsetAudioOn()) {
2224 //audioRouter.setSpeaker(true);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002225 activated = true;
Santos Cordonbb2bcef2014-08-05 19:08:10 -07002226 }*/
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002227 }
2228 return activated;
2229 }
2230
2231
2232 /**
2233 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
2234 */
2235 /* package */ static boolean isPhoneInEcm(Phone phone) {
2236 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
2237 // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true".
2238 // TODO: There ought to be a better API for this than just
2239 // exposing a system property all the way up to the app layer,
2240 // probably a method like "inEcm()" provided by the telephony
2241 // layer.
2242 String ecmMode =
2243 SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
2244 if (ecmMode != null) {
2245 return ecmMode.equals("true");
2246 }
2247 }
2248 return false;
2249 }
2250
2251 /**
2252 * Returns the most appropriate Phone object to handle a call
2253 * to the specified number.
2254 *
2255 * @param cm the CallManager.
2256 * @param scheme the scheme from the data URI that the number originally came from.
2257 * @param number the phone number, or SIP address.
2258 */
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002259 public static Phone pickPhoneBasedOnNumber(CallManager cm, String scheme, String number,
2260 String primarySipUri, ComponentName thirdPartyCallComponent) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002261 if (DBG) {
2262 log("pickPhoneBasedOnNumber: scheme " + scheme
2263 + ", number " + toLogSafePhoneNumber(number)
2264 + ", sipUri "
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002265 + (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null")
2266 + ", thirdPartyCallComponent: " + thirdPartyCallComponent);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002267 }
2268
2269 if (primarySipUri != null) {
2270 Phone phone = getSipPhoneFromUri(cm, primarySipUri);
2271 if (phone != null) return phone;
2272 }
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002273
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002274 return cm.getDefaultPhone();
2275 }
2276
2277 public static Phone getSipPhoneFromUri(CallManager cm, String target) {
2278 for (Phone phone : cm.getAllPhones()) {
2279 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
2280 String sipUri = ((SipPhone) phone).getSipUri();
2281 if (target.equals(sipUri)) {
2282 if (DBG) log("- pickPhoneBasedOnNumber:" +
2283 "found SipPhone! obj = " + phone + ", "
2284 + phone.getClass());
2285 return phone;
2286 }
2287 }
2288 }
2289 return null;
2290 }
2291
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002292 /**
2293 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
2294 * meaning the call is the first real incoming call the phone is having.
2295 */
2296 public static boolean isRealIncomingCall(Call.State state) {
2297 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
2298 }
2299
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002300 public static String getPresentationString(Context context, int presentation) {
2301 String name = context.getString(R.string.unknown);
2302 if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
2303 name = context.getString(R.string.private_num);
2304 } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
2305 name = context.getString(R.string.payphone);
2306 }
2307 return name;
2308 }
2309
2310 public static void sendViewNotificationAsync(Context context, Uri contactUri) {
2311 if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")");
2312 Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri);
2313 intent.setClassName("com.android.contacts",
2314 "com.android.contacts.ViewNotificationService");
2315 context.startService(intent);
2316 }
2317
2318 //
2319 // General phone and call state debugging/testing code
2320 //
2321
2322 /* package */ static void dumpCallState(Phone phone) {
2323 PhoneGlobals app = PhoneGlobals.getInstance();
2324 Log.d(LOG_TAG, "dumpCallState():");
2325 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
2326 + ", state = " + phone.getState());
2327
2328 StringBuilder b = new StringBuilder(128);
2329
2330 Call call = phone.getForegroundCall();
2331 b.setLength(0);
2332 b.append(" - FG call: ").append(call.getState());
2333 b.append(" isAlive ").append(call.getState().isAlive());
2334 b.append(" isRinging ").append(call.getState().isRinging());
2335 b.append(" isDialing ").append(call.getState().isDialing());
2336 b.append(" isIdle ").append(call.isIdle());
2337 b.append(" hasConnections ").append(call.hasConnections());
2338 Log.d(LOG_TAG, b.toString());
2339
2340 call = phone.getBackgroundCall();
2341 b.setLength(0);
2342 b.append(" - BG call: ").append(call.getState());
2343 b.append(" isAlive ").append(call.getState().isAlive());
2344 b.append(" isRinging ").append(call.getState().isRinging());
2345 b.append(" isDialing ").append(call.getState().isDialing());
2346 b.append(" isIdle ").append(call.isIdle());
2347 b.append(" hasConnections ").append(call.hasConnections());
2348 Log.d(LOG_TAG, b.toString());
2349
2350 call = phone.getRingingCall();
2351 b.setLength(0);
2352 b.append(" - RINGING call: ").append(call.getState());
2353 b.append(" isAlive ").append(call.getState().isAlive());
2354 b.append(" isRinging ").append(call.getState().isRinging());
2355 b.append(" isDialing ").append(call.getState().isDialing());
2356 b.append(" isIdle ").append(call.isIdle());
2357 b.append(" hasConnections ").append(call.hasConnections());
2358 Log.d(LOG_TAG, b.toString());
2359
2360
2361 final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2362 final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2363 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2364 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2365 b.setLength(0);
2366 b.append(" - hasRingingCall ").append(hasRingingCall);
2367 b.append(" hasActiveCall ").append(hasActiveCall);
2368 b.append(" hasHoldingCall ").append(hasHoldingCall);
2369 b.append(" allLinesTaken ").append(allLinesTaken);
2370 Log.d(LOG_TAG, b.toString());
2371
2372 // On CDMA phones, dump out the CdmaPhoneCallState too:
2373 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
2374 if (app.cdmaPhoneCallState != null) {
2375 Log.d(LOG_TAG, " - CDMA call state: "
2376 + app.cdmaPhoneCallState.getCurrentCallState());
2377 } else {
2378 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!");
2379 }
2380 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002381 }
2382
2383 private static void log(String msg) {
2384 Log.d(LOG_TAG, msg);
2385 }
2386
2387 static void dumpCallManager() {
2388 Call call;
2389 CallManager cm = PhoneGlobals.getInstance().mCM;
2390 StringBuilder b = new StringBuilder(128);
2391
2392
2393
2394 Log.d(LOG_TAG, "############### dumpCallManager() ##############");
2395 // TODO: Don't log "cm" itself, since CallManager.toString()
2396 // already spews out almost all this same information.
2397 // We should fix CallManager.toString() to be more minimal, and
2398 // use an explicit dumpState() method for the verbose dump.
2399 // Log.d(LOG_TAG, "CallManager: " + cm
2400 // + ", state = " + cm.getState());
2401 Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
2402 b.setLength(0);
2403 call = cm.getActiveFgCall();
2404 b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
2405 b.append(call);
2406 b.append( " State: ").append(cm.getActiveFgCallState());
2407 b.append( " Conn: ").append(cm.getFgCallConnections());
2408 Log.d(LOG_TAG, b.toString());
2409 b.setLength(0);
2410 call = cm.getFirstActiveBgCall();
2411 b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
2412 b.append(call);
2413 b.append( " State: ").append(cm.getFirstActiveBgCall().getState());
2414 b.append( " Conn: ").append(cm.getBgCallConnections());
2415 Log.d(LOG_TAG, b.toString());
2416 b.setLength(0);
2417 call = cm.getFirstActiveRingingCall();
2418 b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
2419 b.append(call);
2420 b.append( " State: ").append(cm.getFirstActiveRingingCall().getState());
2421 Log.d(LOG_TAG, b.toString());
2422
2423
2424
2425 for (Phone phone : CallManager.getInstance().getAllPhones()) {
2426 if (phone != null) {
2427 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
2428 + ", state = " + phone.getState());
2429 b.setLength(0);
2430 call = phone.getForegroundCall();
2431 b.append(" - FG call: ").append(call);
2432 b.append( " State: ").append(call.getState());
2433 b.append( " Conn: ").append(call.hasConnections());
2434 Log.d(LOG_TAG, b.toString());
2435 b.setLength(0);
2436 call = phone.getBackgroundCall();
2437 b.append(" - BG call: ").append(call);
2438 b.append( " State: ").append(call.getState());
2439 b.append( " Conn: ").append(call.hasConnections());
2440 Log.d(LOG_TAG, b.toString());b.setLength(0);
2441 call = phone.getRingingCall();
2442 b.append(" - RINGING call: ").append(call);
2443 b.append( " State: ").append(call.getState());
2444 b.append( " Conn: ").append(call.hasConnections());
2445 Log.d(LOG_TAG, b.toString());
2446 }
2447 }
2448
2449 Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
2450 }
2451
2452 /**
2453 * @return if the context is in landscape orientation.
2454 */
2455 public static boolean isLandscape(Context context) {
2456 return context.getResources().getConfiguration().orientation
2457 == Configuration.ORIENTATION_LANDSCAPE;
2458 }
Andrew Leed5165b02014-12-05 15:53:58 -08002459
Nancy Chene53a0642015-03-12 11:20:12 -07002460 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
2461 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
2462 }
2463
Nancy Chen32031f42015-03-04 21:00:07 -08002464 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
2465 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
2466 }
2467
Andrew Leed5165b02014-12-05 15:53:58 -08002468 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
2469 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
2470 }
2471
2472 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
2473 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08002474 // TODO: Should use some sort of special hidden flag to decorate this account as
2475 // an emergency-only account
Santos Cordon80855d52015-02-10 04:33:36 -08002476 String id = isEmergency ? "E" : prefix + String.valueOf(phone.getIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07002477 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
2478 }
2479
2480 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
2481 String id, String prefix, boolean isEmergency) {
2482 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08002483 return new PhoneAccountHandle(pstnConnectionServiceName, id);
2484 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08002485
Santos Cordonf69df962015-02-03 11:15:19 -08002486 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08002487 if (phoneAccount != null
2488 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
2489 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
2490 }
2491 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
2492 }
2493
2494 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
2495 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
Santos Cordon80855d52015-02-10 04:33:36 -08002496 Phone phone = getPhoneFromIccId(handle.getId());
2497 if (phone != null) {
2498 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08002499 }
2500 }
2501 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
2502 }
2503
Nancy Chene53a0642015-03-12 11:20:12 -07002504 /**
2505 * Determine if a given phone account corresponds to an active SIM
2506 *
2507 * @param sm An instance of the subscription manager so it is not recreated for each calling of
2508 * this method.
2509 * @param handle The handle for the phone account to check
2510 * @return {@code true} If there is an active SIM for this phone account,
2511 * {@code false} otherwise.
2512 */
2513 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
2514 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
2515 }
2516
Santos Cordonf69df962015-02-03 11:15:19 -08002517 private static ComponentName getPstnConnectionServiceName() {
Tony Mak4c8f3c62015-12-07 02:30:37 +00002518 return PSTN_CONNECTION_SERVICE_COMPONENT;
Santos Cordonf69df962015-02-03 11:15:19 -08002519 }
2520
Santos Cordon80855d52015-02-10 04:33:36 -08002521 private static Phone getPhoneFromIccId(String iccId) {
2522 if (!TextUtils.isEmpty(iccId)) {
2523 for (Phone phone : PhoneFactory.getPhones()) {
2524 String phoneIccId = phone.getIccSerialNumber();
2525 if (iccId.equals(phoneIccId)) {
2526 return phone;
2527 }
2528 }
2529 }
Santos Cordon80855d52015-02-10 04:33:36 -08002530 return null;
2531 }
2532
Stuart Scottdcf40a92014-12-09 10:45:01 -08002533 /**
2534 * Register ICC status for all phones.
2535 */
2536 static final void registerIccStatus(Handler handler, int event) {
2537 for (Phone phone : PhoneFactory.getPhones()) {
2538 IccCard sim = phone.getIccCard();
2539 if (sim != null) {
2540 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
2541 sim.registerForNetworkLocked(handler, event, phone);
2542 }
2543 }
2544 }
2545
2546 /**
2547 * Set the radio power on/off state for all phones.
2548 *
2549 * @param enabled true means on, false means off.
2550 */
2551 static final void setRadioPower(boolean enabled) {
2552 for (Phone phone : PhoneFactory.getPhones()) {
2553 phone.setRadioPower(enabled);
2554 }
2555 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002556}