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