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