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