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