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