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