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