blob: f446d369ee5117c38b54f2145b2b1447fb24f07f [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;
34import android.net.sip.SipManager;
35import android.os.AsyncResult;
36import android.os.Handler;
37import android.os.Message;
38import android.os.RemoteException;
39import android.os.SystemProperties;
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 {
717 connection = app.mCM.dial(phone, numberToDial);
718 } 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) {
734 if (phoneType == PhoneConstants.PHONE_TYPE_GSM && gatewayUri == null) {
735 if (DBG) log("dialed MMI code: " + number);
736 status = CALL_STATUS_DIALED_MMI;
737 } else {
738 status = CALL_STATUS_FAILED;
739 }
740 } else {
Tyler Gunn10f1c6a2014-01-17 12:01:11 -0800741 // Now that the call is successful, we can save the gateway info for the call
742 if (callGateway != null) {
743 callGateway.setGatewayInfoForConnection(connection, gatewayInfo);
744 }
745
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700746 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700747 updateCdmaCallStateOnNewOutgoingCall(app, connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700748 }
749
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700750 if (gatewayUri == null) {
751 // phone.dial() succeeded: we're now in a normal phone call.
752 // attach the URI to the CallerInfo Object if it is there,
753 // otherwise just attach the Uri Reference.
754 // if the uri does not have a "content" scheme, then we treat
755 // it as if it does NOT have a unique reference.
756 String content = context.getContentResolver().SCHEME_CONTENT;
757 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
758 Object userDataObject = connection.getUserData();
759 if (userDataObject == null) {
760 connection.setUserData(contactRef);
761 } else {
762 // TODO: This branch is dead code, we have
763 // just created the connection which has
764 // no user data (null) by default.
765 if (userDataObject instanceof CallerInfo) {
766 ((CallerInfo) userDataObject).contactRefUri = contactRef;
767 } else {
768 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
769 contactRef;
770 }
771 }
772 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700773 }
Santos Cordonc264cba2013-09-19 04:55:40 -0700774
Chiao Chenge365ba72013-09-26 14:18:12 -0700775 startGetCallerInfo(context, connection, null, null, gatewayInfo);
776
Santos Cordonc264cba2013-09-19 04:55:40 -0700777 // Always set mute to off when we are dialing an emergency number
778 if (isEmergencyCall) {
779 setMute(false);
780 }
781
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700782 setAudioMode();
783
784 if (DBG) log("about to activate speaker");
785 // Check is phone in any dock, and turn on speaker accordingly
786 final boolean speakerActivated = activateSpeakerIfDocked(phone);
787
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700788 final BluetoothManager btManager = app.getBluetoothManager();
789
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700790 // See also similar logic in answerCall().
791 if (initiallyIdle && !speakerActivated && isSpeakerOn(app)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700792 && !btManager.isBluetoothHeadsetAudioOn()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700793 // This is not an error but might cause users' confusion. Add log just in case.
794 Log.i(LOG_TAG, "Forcing speaker off when initiating a new outgoing call...");
795 PhoneUtils.turnOnSpeaker(app, false, true);
796 }
797 }
798
799 return status;
800 }
801
802 /* package */ static String toLogSafePhoneNumber(String number) {
803 // For unknown number, log empty string.
804 if (number == null) {
805 return "";
806 }
807
808 if (VDBG) {
809 // When VDBG is true we emit PII.
810 return number;
811 }
812
813 // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
814 // sanitized phone numbers.
815 StringBuilder builder = new StringBuilder();
816 for (int i = 0; i < number.length(); i++) {
817 char c = number.charAt(i);
818 if (c == '-' || c == '@' || c == '.') {
819 builder.append(c);
820 } else {
821 builder.append('x');
822 }
823 }
824 return builder.toString();
825 }
826
827 /**
828 * Wrapper function to control when to send an empty Flash command to the network.
829 * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash
830 * to the network prior to placing a 3-way call for it to be successful.
831 */
832 static void sendEmptyFlash(Phone phone) {
833 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
834 Call fgCall = phone.getForegroundCall();
835 if (fgCall.getState() == Call.State.ACTIVE) {
836 // Send the empty flash
837 if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network");
838 switchHoldingAndActive(phone.getBackgroundCall());
839 }
840 }
841 }
842
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700843 static void swap() {
844 final PhoneGlobals mApp = PhoneGlobals.getInstance();
845 if (!okToSwapCalls(mApp.mCM)) {
846 // TODO: throw an error instead?
847 return;
848 }
849
850 // Swap the fg and bg calls.
851 // In the future we may provide some way for user to choose among
852 // multiple background calls, for now, always act on the first background call.
853 PhoneUtils.switchHoldingAndActive(mApp.mCM.getFirstActiveBgCall());
854
855 // If we have a valid BluetoothPhoneService then since CDMA network or
856 // Telephony FW does not send us information on which caller got swapped
857 // we need to update the second call active state in BluetoothPhoneService internally
858 if (mApp.mCM.getBgPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
859 final IBluetoothHeadsetPhone btPhone = mApp.getBluetoothPhoneService();
860 if (btPhone != null) {
861 try {
862 btPhone.cdmaSwapSecondCallState();
863 } catch (RemoteException e) {
864 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
865 }
866 }
867 }
868 }
869
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700870 /**
871 * @param heldCall is the background call want to be swapped
872 */
873 static void switchHoldingAndActive(Call heldCall) {
874 log("switchHoldingAndActive()...");
875 try {
876 CallManager cm = PhoneGlobals.getInstance().mCM;
877 if (heldCall.isIdle()) {
878 // no heldCall, so it is to hold active call
879 cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall());
880 } else {
881 // has particular heldCall, so to switch
882 cm.switchHoldingAndActive(heldCall);
883 }
884 setAudioMode(cm);
885 } catch (CallStateException ex) {
886 Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
887 }
888 }
889
890 /**
891 * Restore the mute setting from the earliest connection of the
892 * foreground call.
893 */
894 static Boolean restoreMuteState() {
895 Phone phone = PhoneGlobals.getInstance().mCM.getFgPhone();
896
897 //get the earliest connection
898 Connection c = phone.getForegroundCall().getEarliestConnection();
899
900 // only do this if connection is not null.
901 if (c != null) {
902
903 int phoneType = phone.getPhoneType();
904
905 // retrieve the mute value.
906 Boolean shouldMute = null;
907
908 // In CDMA, mute is not maintained per Connection. Single mute apply for
909 // a call where call can have multiple connections such as
910 // Three way and Call Waiting. Therefore retrieving Mute state for
911 // latest connection can apply for all connection in that call
912 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
913 shouldMute = sConnectionMuteTable.get(
914 phone.getForegroundCall().getLatestConnection());
915 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -0700916 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
917 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700918 shouldMute = sConnectionMuteTable.get(c);
919 }
920 if (shouldMute == null) {
921 if (DBG) log("problem retrieving mute value for this connection.");
922 shouldMute = Boolean.FALSE;
923 }
924
925 // set the mute value and return the result.
926 setMute (shouldMute.booleanValue());
927 return shouldMute;
928 }
929 return Boolean.valueOf(getMute());
930 }
931
932 static void mergeCalls() {
933 mergeCalls(PhoneGlobals.getInstance().mCM);
934 }
935
936 static void mergeCalls(CallManager cm) {
937 int phoneType = cm.getFgPhone().getPhoneType();
938 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
939 log("mergeCalls(): CDMA...");
940 PhoneGlobals app = PhoneGlobals.getInstance();
941 if (app.cdmaPhoneCallState.getCurrentCallState()
942 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
943 // Set the Phone Call State to conference
944 app.cdmaPhoneCallState.setCurrentCallState(
945 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
946
947 // Send flash cmd
948 // TODO: Need to change the call from switchHoldingAndActive to
949 // something meaningful as we are not actually trying to swap calls but
950 // instead are merging two calls by sending a Flash command.
951 log("- sending flash...");
952 switchHoldingAndActive(cm.getFirstActiveBgCall());
953 }
954 } else {
955 try {
956 log("mergeCalls(): calling cm.conference()...");
957 cm.conference(cm.getFirstActiveBgCall());
958 } catch (CallStateException ex) {
959 Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
960 }
961 }
962 }
963
964 static void separateCall(Connection c) {
965 try {
966 if (DBG) log("separateCall: " + toLogSafePhoneNumber(c.getAddress()));
967 c.separate();
968 } catch (CallStateException ex) {
969 Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
970 }
971 }
972
973 /**
974 * Handle the MMIInitiate message and put up an alert that lets
975 * the user cancel the operation, if applicable.
976 *
977 * @param context context to get strings.
978 * @param mmiCode the MmiCode object being started.
979 * @param buttonCallbackMessage message to post when button is clicked.
980 * @param previousAlert a previous alert used in this activity.
981 * @return the dialog handle
982 */
983 static Dialog displayMMIInitiate(Context context,
984 MmiCode mmiCode,
985 Message buttonCallbackMessage,
986 Dialog previousAlert) {
987 if (DBG) log("displayMMIInitiate: " + mmiCode);
988 if (previousAlert != null) {
989 previousAlert.dismiss();
990 }
991
992 // The UI paradigm we are using now requests that all dialogs have
993 // user interaction, and that any other messages to the user should
994 // be by way of Toasts.
995 //
996 // In adhering to this request, all MMI initiating "OK" dialogs
997 // (non-cancelable MMIs) that end up being closed when the MMI
998 // completes (thereby showing a completion dialog) are being
999 // replaced with Toasts.
1000 //
1001 // As a side effect, moving to Toasts for the non-cancelable MMIs
1002 // also means that buttonCallbackMessage (which was tied into "OK")
1003 // is no longer invokable for these dialogs. This is not a problem
1004 // since the only callback messages we supported were for cancelable
1005 // MMIs anyway.
1006 //
1007 // A cancelable MMI is really just a USSD request. The term
1008 // "cancelable" here means that we can cancel the request when the
1009 // system prompts us for a response, NOT while the network is
1010 // processing the MMI request. Any request to cancel a USSD while
1011 // the network is NOT ready for a response may be ignored.
1012 //
1013 // With this in mind, we replace the cancelable alert dialog with
1014 // a progress dialog, displayed until we receive a request from
1015 // the the network. For more information, please see the comments
1016 // in the displayMMIComplete() method below.
1017 //
1018 // Anything that is NOT a USSD request is a normal MMI request,
1019 // which will bring up a toast (desribed above).
1020
1021 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
1022
1023 if (!isCancelable) {
1024 if (DBG) log("not a USSD code, displaying status toast.");
1025 CharSequence text = context.getText(R.string.mmiStarted);
1026 Toast.makeText(context, text, Toast.LENGTH_SHORT)
1027 .show();
1028 return null;
1029 } else {
1030 if (DBG) log("running USSD code, displaying indeterminate progress.");
1031
1032 // create the indeterminate progress dialog and display it.
1033 ProgressDialog pd = new ProgressDialog(context);
1034 pd.setMessage(context.getText(R.string.ussdRunning));
1035 pd.setCancelable(false);
1036 pd.setIndeterminate(true);
1037 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1038
1039 pd.show();
1040
1041 return pd;
1042 }
1043
1044 }
1045
1046 /**
1047 * Handle the MMIComplete message and fire off an intent to display
1048 * the message.
1049 *
1050 * @param context context to get strings.
1051 * @param mmiCode MMI result.
1052 * @param previousAlert a previous alert used in this activity.
1053 */
1054 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
1055 Message dismissCallbackMessage,
1056 AlertDialog previousAlert) {
1057 final PhoneGlobals app = PhoneGlobals.getInstance();
1058 CharSequence text;
1059 int title = 0; // title for the progress dialog, if needed.
1060 MmiCode.State state = mmiCode.getState();
1061
1062 if (DBG) log("displayMMIComplete: state=" + state);
1063
1064 switch (state) {
1065 case PENDING:
1066 // USSD code asking for feedback from user.
1067 text = mmiCode.getMessage();
1068 if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
1069 break;
1070 case CANCELLED:
1071 text = null;
1072 break;
1073 case COMPLETE:
1074 if (app.getPUKEntryActivity() != null) {
1075 // if an attempt to unPUK the device was made, we specify
1076 // the title and the message here.
1077 title = com.android.internal.R.string.PinMmi;
1078 text = context.getText(R.string.puk_unlocked);
1079 break;
1080 }
1081 // All other conditions for the COMPLETE mmi state will cause
1082 // the case to fall through to message logic in common with
1083 // the FAILED case.
1084
1085 case FAILED:
1086 text = mmiCode.getMessage();
1087 if (DBG) log("- using text from MMI message: '" + text + "'");
1088 break;
1089 default:
1090 throw new IllegalStateException("Unexpected MmiCode state: " + state);
1091 }
1092
1093 if (previousAlert != null) {
1094 previousAlert.dismiss();
1095 }
1096
1097 // Check to see if a UI exists for the PUK activation. If it does
1098 // exist, then it indicates that we're trying to unblock the PUK.
1099 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
1100 if (DBG) log("displaying PUK unblocking progress dialog.");
1101
1102 // create the progress dialog, make sure the flags and type are
1103 // set correctly.
1104 ProgressDialog pd = new ProgressDialog(app);
1105 pd.setTitle(title);
1106 pd.setMessage(text);
1107 pd.setCancelable(false);
1108 pd.setIndeterminate(true);
1109 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1110 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1111
1112 // display the dialog
1113 pd.show();
1114
1115 // indicate to the Phone app that the progress dialog has
1116 // been assigned for the PUK unlock / SIM READY process.
1117 app.setPukEntryProgressDialog(pd);
1118
1119 } else {
1120 // In case of failure to unlock, we'll need to reset the
1121 // PUK unlock activity, so that the user may try again.
1122 if (app.getPUKEntryActivity() != null) {
1123 app.setPukEntryActivity(null);
1124 }
1125
1126 // A USSD in a pending state means that it is still
1127 // interacting with the user.
1128 if (state != MmiCode.State.PENDING) {
1129 if (DBG) log("MMI code has finished running.");
1130
1131 if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
1132 if (text == null || text.length() == 0)
1133 return;
1134
1135 // displaying system alert dialog on the screen instead of
1136 // using another activity to display the message. This
1137 // places the message at the forefront of the UI.
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001138
Etan Cohen37abbab2014-03-07 16:57:03 -08001139 if (sUssdDialog == null) {
1140 sUssdDialog = new AlertDialog.Builder(context)
1141 .setPositiveButton(R.string.ok, null)
1142 .setCancelable(true)
1143 .setOnDismissListener(new DialogInterface.OnDismissListener() {
1144 @Override
1145 public void onDismiss(DialogInterface dialog) {
1146 sUssdMsg.setLength(0);
1147 }
1148 })
1149 .create();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001150
Etan Cohen37abbab2014-03-07 16:57:03 -08001151 sUssdDialog.getWindow().setType(
1152 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1153 sUssdDialog.getWindow().addFlags(
1154 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1155 }
1156 if (sUssdMsg.length() != 0) {
1157 sUssdMsg
1158 .insert(0, "\n")
1159 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
1160 .insert(0, "\n");
1161 }
1162 sUssdMsg.insert(0, text);
1163 sUssdDialog.setMessage(sUssdMsg.toString());
1164 sUssdDialog.show();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001165 } else {
1166 if (DBG) log("USSD code has requested user input. Constructing input dialog.");
1167
1168 // USSD MMI code that is interacting with the user. The
1169 // basic set of steps is this:
1170 // 1. User enters a USSD request
1171 // 2. We recognize the request and displayMMIInitiate
1172 // (above) creates a progress dialog.
1173 // 3. Request returns and we get a PENDING or COMPLETE
1174 // message.
1175 // 4. These MMI messages are caught in the PhoneApp
1176 // (onMMIComplete) and the InCallScreen
1177 // (mHandler.handleMessage) which bring up this dialog
1178 // and closes the original progress dialog,
1179 // respectively.
1180 // 5. If the message is anything other than PENDING,
1181 // we are done, and the alert dialog (directly above)
1182 // displays the outcome.
1183 // 6. If the network is requesting more information from
1184 // the user, the MMI will be in a PENDING state, and
1185 // we display this dialog with the message.
1186 // 7. User input, or cancel requests result in a return
1187 // to step 1. Keep in mind that this is the only
1188 // time that a USSD should be canceled.
1189
1190 // inflate the layout with the scrolling text area for the dialog.
1191 LayoutInflater inflater = (LayoutInflater) context.getSystemService(
1192 Context.LAYOUT_INFLATER_SERVICE);
1193 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
1194
1195 // get the input field.
1196 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
1197
1198 // specify the dialog's click listener, with SEND and CANCEL logic.
1199 final DialogInterface.OnClickListener mUSSDDialogListener =
1200 new DialogInterface.OnClickListener() {
1201 public void onClick(DialogInterface dialog, int whichButton) {
1202 switch (whichButton) {
1203 case DialogInterface.BUTTON_POSITIVE:
1204 // As per spec 24.080, valid length of ussd string
1205 // is 1 - 160. If length is out of the range then
1206 // display toast message & Cancel MMI operation.
1207 if (inputText.length() < MIN_USSD_LEN
1208 || inputText.length() > MAX_USSD_LEN) {
1209 Toast.makeText(app,
1210 app.getResources().getString(R.string.enter_input,
1211 MIN_USSD_LEN, MAX_USSD_LEN),
1212 Toast.LENGTH_LONG).show();
1213 if (mmiCode.isCancelable()) {
1214 mmiCode.cancel();
1215 }
1216 } else {
1217 phone.sendUssdResponse(inputText.getText().toString());
1218 }
1219 break;
1220 case DialogInterface.BUTTON_NEGATIVE:
1221 if (mmiCode.isCancelable()) {
1222 mmiCode.cancel();
1223 }
1224 break;
1225 }
1226 }
1227 };
1228
1229 // build the dialog
1230 final AlertDialog newDialog = new AlertDialog.Builder(context)
1231 .setMessage(text)
1232 .setView(dialogView)
1233 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
1234 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
1235 .setCancelable(false)
1236 .create();
1237
1238 // attach the key listener to the dialog's input field and make
1239 // sure focus is set.
1240 final View.OnKeyListener mUSSDDialogInputListener =
1241 new View.OnKeyListener() {
1242 public boolean onKey(View v, int keyCode, KeyEvent event) {
1243 switch (keyCode) {
1244 case KeyEvent.KEYCODE_CALL:
1245 case KeyEvent.KEYCODE_ENTER:
1246 if(event.getAction() == KeyEvent.ACTION_DOWN) {
1247 phone.sendUssdResponse(inputText.getText().toString());
1248 newDialog.dismiss();
1249 }
1250 return true;
1251 }
1252 return false;
1253 }
1254 };
1255 inputText.setOnKeyListener(mUSSDDialogInputListener);
1256 inputText.requestFocus();
1257
1258 // set the window properties of the dialog
1259 newDialog.getWindow().setType(
1260 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1261 newDialog.getWindow().addFlags(
1262 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1263
1264 // now show the dialog!
1265 newDialog.show();
1266 }
1267 }
1268 }
1269
1270 /**
1271 * Cancels the current pending MMI operation, if applicable.
1272 * @return true if we canceled an MMI operation, or false
1273 * if the current pending MMI wasn't cancelable
1274 * or if there was no current pending MMI at all.
1275 *
1276 * @see displayMMIInitiate
1277 */
1278 static boolean cancelMmiCode(Phone phone) {
1279 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
1280 int count = pendingMmis.size();
1281 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
1282
1283 boolean canceled = false;
1284 if (count > 0) {
1285 // assume that we only have one pending MMI operation active at a time.
1286 // I don't think it's possible to enter multiple MMI codes concurrently
1287 // in the phone UI, because during the MMI operation, an Alert panel
1288 // is displayed, which prevents more MMI code from being entered.
1289 MmiCode mmiCode = pendingMmis.get(0);
1290 if (mmiCode.isCancelable()) {
1291 mmiCode.cancel();
1292 canceled = true;
1293 }
1294 }
1295 return canceled;
1296 }
1297
1298 public static class VoiceMailNumberMissingException extends Exception {
1299 VoiceMailNumberMissingException() {
1300 super();
1301 }
1302
1303 VoiceMailNumberMissingException(String msg) {
1304 super(msg);
1305 }
1306 }
1307
1308 /**
1309 * Given an Intent (which is presumably the ACTION_CALL intent that
1310 * initiated this outgoing call), figure out the actual phone number we
1311 * should dial.
1312 *
1313 * Note that the returned "number" may actually be a SIP address,
1314 * if the specified intent contains a sip: URI.
1315 *
1316 * This method is basically a wrapper around PhoneUtils.getNumberFromIntent(),
1317 * except it's also aware of the EXTRA_ACTUAL_NUMBER_TO_DIAL extra.
1318 * (That extra, if present, tells us the exact string to pass down to the
1319 * telephony layer. It's guaranteed to be safe to dial: it's either a PSTN
1320 * phone number with separators and keypad letters stripped out, or a raw
1321 * unencoded SIP address.)
1322 *
1323 * @return the phone number corresponding to the specified Intent, or null
1324 * if the Intent has no action or if the intent's data is malformed or
1325 * missing.
1326 *
1327 * @throws VoiceMailNumberMissingException if the intent
1328 * contains a "voicemail" URI, but there's no voicemail
1329 * number configured on the device.
1330 */
1331 public static String getInitialNumber(Intent intent)
1332 throws PhoneUtils.VoiceMailNumberMissingException {
1333 if (DBG) log("getInitialNumber(): " + intent);
1334
1335 String action = intent.getAction();
1336 if (TextUtils.isEmpty(action)) {
1337 return null;
1338 }
1339
1340 // If the EXTRA_ACTUAL_NUMBER_TO_DIAL extra is present, get the phone
1341 // number from there. (That extra takes precedence over the actual data
1342 // included in the intent.)
1343 if (intent.hasExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL)) {
1344 String actualNumberToDial =
1345 intent.getStringExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL);
1346 if (DBG) {
1347 log("==> got EXTRA_ACTUAL_NUMBER_TO_DIAL; returning '"
1348 + toLogSafePhoneNumber(actualNumberToDial) + "'");
1349 }
1350 return actualNumberToDial;
1351 }
1352
1353 return getNumberFromIntent(PhoneGlobals.getInstance(), intent);
1354 }
1355
1356 /**
1357 * Gets the phone number to be called from an intent. Requires a Context
1358 * to access the contacts database, and a Phone to access the voicemail
1359 * number.
1360 *
1361 * <p>If <code>phone</code> is <code>null</code>, the function will return
1362 * <code>null</code> for <code>voicemail:</code> URIs;
1363 * if <code>context</code> is <code>null</code>, the function will return
1364 * <code>null</code> for person/phone URIs.</p>
1365 *
1366 * <p>If the intent contains a <code>sip:</code> URI, the returned
1367 * "number" is actually the SIP address.
1368 *
1369 * @param context a context to use (or
1370 * @param intent the intent
1371 *
1372 * @throws VoiceMailNumberMissingException if <code>intent</code> contains
1373 * a <code>voicemail:</code> URI, but <code>phone</code> does not
1374 * have a voicemail number set.
1375 *
1376 * @return the phone number (or SIP address) that would be called by the intent,
1377 * or <code>null</code> if the number cannot be found.
1378 */
1379 private static String getNumberFromIntent(Context context, Intent intent)
1380 throws VoiceMailNumberMissingException {
1381 Uri uri = intent.getData();
1382 String scheme = uri.getScheme();
1383
1384 // The sip: scheme is simple: just treat the rest of the URI as a
1385 // SIP address.
1386 if (Constants.SCHEME_SIP.equals(scheme)) {
1387 return uri.getSchemeSpecificPart();
1388 }
1389
1390 // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
1391 // the other cases (i.e. tel: and voicemail: and contact: URIs.)
1392
1393 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
1394
1395 // Check for a voicemail-dialing request. If the voicemail number is
1396 // empty, throw a VoiceMailNumberMissingException.
1397 if (Constants.SCHEME_VOICEMAIL.equals(scheme) &&
1398 (number == null || TextUtils.isEmpty(number)))
1399 throw new VoiceMailNumberMissingException();
1400
1401 return number;
1402 }
1403
1404 /**
1405 * Returns the caller-id info corresponding to the specified Connection.
1406 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
1407 * extract a phone number from the specified Connection, and feed that
1408 * number into CallerInfo.getCallerInfo().)
1409 *
1410 * The returned CallerInfo may be null in certain error cases, like if the
1411 * specified Connection was null, or if we weren't able to get a valid
1412 * phone number from the Connection.
1413 *
1414 * Finally, if the getCallerInfo() call did succeed, we save the resulting
1415 * CallerInfo object in the "userData" field of the Connection.
1416 *
1417 * NOTE: This API should be avoided, with preference given to the
1418 * asynchronous startGetCallerInfo API.
1419 */
1420 static CallerInfo getCallerInfo(Context context, Connection c) {
1421 CallerInfo info = null;
1422
1423 if (c != null) {
1424 //See if there is a URI attached. If there is, this means
1425 //that there is no CallerInfo queried yet, so we'll need to
1426 //replace the URI with a full CallerInfo object.
1427 Object userDataObject = c.getUserData();
1428 if (userDataObject instanceof Uri) {
1429 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1430 if (info != null) {
1431 c.setUserData(info);
1432 }
1433 } else {
1434 if (userDataObject instanceof CallerInfoToken) {
1435 //temporary result, while query is running
1436 info = ((CallerInfoToken) userDataObject).currentInfo;
1437 } else {
1438 //final query result
1439 info = (CallerInfo) userDataObject;
1440 }
1441 if (info == null) {
1442 // No URI, or Existing CallerInfo, so we'll have to make do with
1443 // querying a new CallerInfo using the connection's phone number.
1444 String number = c.getAddress();
1445
1446 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
1447
1448 if (!TextUtils.isEmpty(number)) {
1449 info = CallerInfo.getCallerInfo(context, number);
1450 if (info != null) {
1451 c.setUserData(info);
1452 }
1453 }
1454 }
1455 }
1456 }
1457 return info;
1458 }
1459
1460 /**
1461 * Class returned by the startGetCallerInfo call to package a temporary
1462 * CallerInfo Object, to be superceded by the CallerInfo Object passed
1463 * into the listener when the query with token mAsyncQueryToken is complete.
1464 */
1465 public static class CallerInfoToken {
1466 /**indicates that there will no longer be updates to this request.*/
1467 public boolean isFinal;
1468
1469 public CallerInfo currentInfo;
1470 public CallerInfoAsyncQuery asyncQuery;
1471 }
1472
1473 /**
1474 * Start a CallerInfo Query based on the earliest connection in the call.
1475 */
1476 static CallerInfoToken startGetCallerInfo(Context context, Call call,
1477 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1478 Connection conn = null;
1479 int phoneType = call.getPhone().getPhoneType();
1480 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1481 conn = call.getLatestConnection();
1482 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001483 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
1484 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001485 conn = call.getEarliestConnection();
1486 } else {
1487 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1488 }
1489
1490 return startGetCallerInfo(context, conn, listener, cookie);
1491 }
1492
Chiao Chenge365ba72013-09-26 14:18:12 -07001493 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1494 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1495 return startGetCallerInfo(context, c, listener, cookie, null);
1496 }
1497
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001498 /**
1499 * place a temporary callerinfo object in the hands of the caller and notify
1500 * caller when the actual query is done.
1501 */
1502 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -07001503 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
1504 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001505 CallerInfoToken cit;
1506
1507 if (c == null) {
1508 //TODO: perhaps throw an exception here.
1509 cit = new CallerInfoToken();
1510 cit.asyncQuery = null;
1511 return cit;
1512 }
1513
1514 Object userDataObject = c.getUserData();
1515
1516 // There are now 3 states for the Connection's userData object:
1517 //
1518 // (1) Uri - query has not been executed yet
1519 //
1520 // (2) CallerInfoToken - query is executing, but has not completed.
1521 //
1522 // (3) CallerInfo - query has executed.
1523 //
1524 // In each case we have slightly different behaviour:
1525 // 1. If the query has not been executed yet (Uri or null), we start
1526 // query execution asynchronously, and note it by attaching a
1527 // CallerInfoToken as the userData.
1528 // 2. If the query is executing (CallerInfoToken), we've essentially
1529 // reached a state where we've received multiple requests for the
1530 // same callerInfo. That means that once the query is complete,
1531 // we'll need to execute the additional listener requested.
1532 // 3. If the query has already been executed (CallerInfo), we just
1533 // return the CallerInfo object as expected.
1534 // 4. Regarding isFinal - there are cases where the CallerInfo object
1535 // will not be attached, like when the number is empty (caller id
1536 // blocking). This flag is used to indicate that the
1537 // CallerInfoToken object is going to be permanent since no
1538 // query results will be returned. In the case where a query
1539 // has been completed, this flag is used to indicate to the caller
1540 // that the data will not be updated since it is valid.
1541 //
1542 // Note: For the case where a number is NOT retrievable, we leave
1543 // the CallerInfo as null in the CallerInfoToken. This is
1544 // something of a departure from the original code, since the old
1545 // code manufactured a CallerInfo object regardless of the query
1546 // outcome. From now on, we will append an empty CallerInfo
1547 // object, to mirror previous behaviour, and to avoid Null Pointer
1548 // Exceptions.
1549
1550 if (userDataObject instanceof Uri) {
1551 // State (1): query has not been executed yet
1552
1553 //create a dummy callerinfo, populate with what we know from URI.
1554 cit = new CallerInfoToken();
1555 cit.currentInfo = new CallerInfo();
1556 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1557 (Uri) userDataObject, sCallerInfoQueryListener, c);
1558 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1559 cit.isFinal = false;
1560
1561 c.setUserData(cit);
1562
1563 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1564
1565 } else if (userDataObject == null) {
1566 // No URI, or Existing CallerInfo, so we'll have to make do with
1567 // querying a new CallerInfo using the connection's phone number.
1568 String number = c.getAddress();
1569
Chiao Cheng685dcb62013-10-02 11:51:06 -07001570 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -07001571 // Gateway number, the connection number is actually the gateway number.
1572 // need to lookup via dialed number.
1573 number = info.trueNumber;
1574 }
1575
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001576 if (DBG) {
1577 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
1578 log("- number (address): " + toLogSafePhoneNumber(number));
1579 log("- c: " + c);
1580 log("- phone: " + c.getCall().getPhone());
1581 int phoneType = c.getCall().getPhone().getPhoneType();
1582 log("- phoneType: " + phoneType);
1583 switch (phoneType) {
1584 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
1585 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
1586 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
1587 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001588 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
1589 log(" ==> PHONE_TYPE_THIRD_PARTY");
1590 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001591 default: log(" ==> Unknown phone type"); break;
1592 }
1593 }
1594
1595 cit = new CallerInfoToken();
1596 cit.currentInfo = new CallerInfo();
1597
1598 // Store CNAP information retrieved from the Connection (we want to do this
1599 // here regardless of whether the number is empty or not).
1600 cit.currentInfo.cnapName = c.getCnapName();
1601 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1602 // by ContactInfo later
1603 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1604 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1605
1606 if (VDBG) {
1607 log("startGetCallerInfo: number = " + number);
1608 log("startGetCallerInfo: CNAP Info from FW(1): name="
1609 + cit.currentInfo.cnapName
1610 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1611 }
1612
1613 // handling case where number is null (caller id hidden) as well.
1614 if (!TextUtils.isEmpty(number)) {
1615 // Check for special CNAP cases and modify the CallerInfo accordingly
1616 // to be sure we keep the right information to display/log later
1617 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
1618 cit.currentInfo.numberPresentation);
1619
1620 cit.currentInfo.phoneNumber = number;
1621 // For scenarios where we may receive a valid number from the network but a
1622 // restricted/unavailable presentation, we do not want to perform a contact query
1623 // (see note on isFinal above). So we set isFinal to true here as well.
1624 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1625 cit.isFinal = true;
1626 } else {
1627 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
1628 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1629 number, sCallerInfoQueryListener, c);
1630 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1631 cit.isFinal = false;
1632 }
1633 } else {
1634 // This is the case where we are querying on a number that
1635 // is null or empty, like a caller whose caller id is
1636 // blocked or empty (CLIR). The previous behaviour was to
1637 // throw a null CallerInfo object back to the user, but
1638 // this departure is somewhat cleaner.
1639 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1640 cit.isFinal = true; // please see note on isFinal, above.
1641 }
1642
1643 c.setUserData(cit);
1644
1645 if (DBG) {
1646 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
1647 }
1648
1649 } else if (userDataObject instanceof CallerInfoToken) {
1650 // State (2): query is executing, but has not completed.
1651
1652 // just tack on this listener to the queue.
1653 cit = (CallerInfoToken) userDataObject;
1654
1655 // handling case where number is null (caller id hidden) as well.
1656 if (cit.asyncQuery != null) {
1657 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1658
1659 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1660 listener.getClass().toString());
1661 } else {
1662 // handling case where number/name gets updated later on by the network
1663 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -07001664
1665 if (info != null) {
1666 // Gateway number, the connection number is actually the gateway number.
1667 // need to lookup via dialed number.
1668 updatedNumber = info.trueNumber;
1669 }
1670
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001671 if (DBG) {
1672 log("startGetCallerInfo: updatedNumber initially = "
1673 + toLogSafePhoneNumber(updatedNumber));
1674 }
1675 if (!TextUtils.isEmpty(updatedNumber)) {
1676 // Store CNAP information retrieved from the Connection
1677 cit.currentInfo.cnapName = c.getCnapName();
1678 // This can still get overwritten by ContactInfo
1679 cit.currentInfo.name = cit.currentInfo.cnapName;
1680 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1681 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1682
1683 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1684 updatedNumber, cit.currentInfo.numberPresentation);
1685
1686 cit.currentInfo.phoneNumber = updatedNumber;
1687 if (DBG) {
1688 log("startGetCallerInfo: updatedNumber="
1689 + toLogSafePhoneNumber(updatedNumber));
1690 }
1691 if (VDBG) {
1692 log("startGetCallerInfo: CNAP Info from FW(2): name="
1693 + cit.currentInfo.cnapName
1694 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1695 } else if (DBG) {
1696 log("startGetCallerInfo: CNAP Info from FW(2)");
1697 }
1698 // For scenarios where we may receive a valid number from the network but a
1699 // restricted/unavailable presentation, we do not want to perform a contact query
1700 // (see note on isFinal above). So we set isFinal to true here as well.
1701 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1702 cit.isFinal = true;
1703 } else {
1704 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1705 updatedNumber, sCallerInfoQueryListener, c);
1706 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1707 cit.isFinal = false;
1708 }
1709 } else {
1710 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1711 if (cit.currentInfo == null) {
1712 cit.currentInfo = new CallerInfo();
1713 }
1714 // Store CNAP information retrieved from the Connection
1715 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
1716 // overwritten by ContactInfo
1717 cit.currentInfo.name = cit.currentInfo.cnapName;
1718 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1719 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1720
1721 if (VDBG) {
1722 log("startGetCallerInfo: CNAP Info from FW(3): name="
1723 + cit.currentInfo.cnapName
1724 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1725 } else if (DBG) {
1726 log("startGetCallerInfo: CNAP Info from FW(3)");
1727 }
1728 cit.isFinal = true; // please see note on isFinal, above.
1729 }
1730 }
1731 } else {
1732 // State (3): query is complete.
1733
1734 // The connection's userDataObject is a full-fledged
1735 // CallerInfo instance. Wrap it in a CallerInfoToken and
1736 // return it to the user.
1737
1738 cit = new CallerInfoToken();
1739 cit.currentInfo = (CallerInfo) userDataObject;
1740 cit.asyncQuery = null;
1741 cit.isFinal = true;
1742 // since the query is already done, call the listener.
1743 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1744 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
1745 }
1746 return cit;
1747 }
1748
1749 /**
1750 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
1751 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
1752 */
1753 private static final int QUERY_TOKEN = -1;
1754 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1755 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1756 /**
1757 * When the query completes, we stash the resulting CallerInfo
1758 * object away in the Connection's "userData" (where it will
1759 * later be retrieved by the in-call UI.)
1760 */
1761 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1762 if (DBG) log("query complete, updating connection.userdata");
1763 Connection conn = (Connection) cookie;
1764
1765 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1766 // If no ContactInfo, then we want to use CNAP information coming from network
1767 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1768 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1769 // If the number presentation has not been set by
1770 // the ContactInfo, use the one from the
1771 // connection.
1772
1773 // TODO: Need a new util method to merge the info
1774 // from the Connection in a CallerInfo object.
1775 // Here 'ci' is a new CallerInfo instance read
1776 // from the DB. It has lost all the connection
1777 // info preset before the query (see PhoneUtils
1778 // line 1334). We should have a method to merge
1779 // back into this new instance the info from the
1780 // connection object not set by the DB. If the
1781 // Connection already has a CallerInfo instance in
1782 // userData, then we could use this instance to
1783 // fill 'ci' in. The same routine could be used in
1784 // PhoneUtils.
1785 if (0 == ci.numberPresentation) {
1786 ci.numberPresentation = conn.getNumberPresentation();
1787 }
1788 } else {
1789 // No matching contact was found for this number.
1790 // Return a new CallerInfo based solely on the CNAP
1791 // information from the network.
1792
1793 CallerInfo newCi = getCallerInfo(null, conn);
1794
1795 // ...but copy over the (few) things we care about
1796 // from the original CallerInfo object:
1797 if (newCi != null) {
1798 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1799 newCi.geoDescription = ci.geoDescription; // To get geo description string
1800 ci = newCi;
1801 }
1802 }
1803
1804 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1805 conn.setUserData(ci);
1806 }
1807 };
1808
1809
1810 /**
1811 * Returns a single "name" for the specified given a CallerInfo object.
1812 * If the name is null, return defaultString as the default value, usually
1813 * context.getString(R.string.unknown).
1814 */
1815 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1816 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1817
1818 String compactName = null;
1819 if (ci != null) {
1820 if (TextUtils.isEmpty(ci.name)) {
1821 // Perform any modifications for special CNAP cases to
1822 // the phone number being displayed, if applicable.
1823 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1824 ci.numberPresentation);
1825 } else {
1826 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1827 compactName = ci.name;
1828 }
1829 }
1830
1831 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1832 // If we're still null/empty here, then check if we have a presentation
1833 // string that takes precedence that we could return, otherwise display
1834 // "unknown" string.
1835 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1836 compactName = context.getString(R.string.private_num);
1837 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1838 compactName = context.getString(R.string.payphone);
1839 } else {
1840 compactName = context.getString(R.string.unknown);
1841 }
1842 }
1843 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1844 return compactName;
1845 }
1846
1847 /**
1848 * Returns true if the specified Call is a "conference call", meaning
1849 * that it owns more than one Connection object. This information is
1850 * used to trigger certain UI changes that appear when a conference
1851 * call is active (like displaying the label "Conference call", and
1852 * enabling the "Manage conference" UI.)
1853 *
1854 * Watch out: This method simply checks the number of Connections,
1855 * *not* their states. So if a Call has (for example) one ACTIVE
1856 * connection and one DISCONNECTED connection, this method will return
1857 * true (which is unintuitive, since the Call isn't *really* a
1858 * conference call any more.)
1859 *
1860 * @return true if the specified call has more than one connection (in any state.)
1861 */
1862 static boolean isConferenceCall(Call call) {
1863 // CDMA phones don't have the same concept of "conference call" as
1864 // GSM phones do; there's no special "conference call" state of
1865 // the UI or a "manage conference" function. (Instead, when
1866 // you're in a 3-way call, all we can do is display the "generic"
1867 // state of the UI.) So as far as the in-call UI is concerned,
1868 // Conference corresponds to generic display.
1869 final PhoneGlobals app = PhoneGlobals.getInstance();
1870 int phoneType = call.getPhone().getPhoneType();
1871 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1872 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
1873 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
1874 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1875 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
1876 return true;
1877 }
1878 } else {
1879 List<Connection> connections = call.getConnections();
1880 if (connections != null && connections.size() > 1) {
1881 return true;
1882 }
1883 }
1884 return false;
1885
1886 // TODO: We may still want to change the semantics of this method
1887 // to say that a given call is only really a conference call if
1888 // the number of ACTIVE connections, not the total number of
1889 // connections, is greater than one. (See warning comment in the
1890 // javadoc above.)
1891 // Here's an implementation of that:
1892 // if (connections == null) {
1893 // return false;
1894 // }
1895 // int numActiveConnections = 0;
1896 // for (Connection conn : connections) {
1897 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
1898 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1899 // if (numActiveConnections > 1) {
1900 // return true;
1901 // }
1902 // }
1903 // return false;
1904 }
1905
1906 /**
1907 * Launch the Dialer to start a new call.
1908 * This is just a wrapper around the ACTION_DIAL intent.
1909 */
1910 /* package */ static boolean startNewCall(final CallManager cm) {
1911 final PhoneGlobals app = PhoneGlobals.getInstance();
1912
1913 // Sanity-check that this is OK given the current state of the phone.
1914 if (!okToAddCall(cm)) {
1915 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1916 dumpCallManager();
1917 return false;
1918 }
1919
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001920 Intent intent = new Intent(Intent.ACTION_DIAL);
1921 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1922
1923 // when we request the dialer come up, we also want to inform
1924 // it that we're going through the "add call" option from the
1925 // InCallScreen / PhoneUtils.
1926 intent.putExtra(ADD_CALL_MODE_KEY, true);
1927 try {
1928 app.startActivity(intent);
1929 } catch (ActivityNotFoundException e) {
1930 // This is rather rare but possible.
1931 // Note: this method is used even when the phone is encrypted. At that moment
1932 // the system may not find any Activity which can accept this Intent.
1933 Log.e(LOG_TAG, "Activity for adding calls isn't found.");
1934 return false;
1935 }
1936
1937 return true;
1938 }
1939
1940 /**
1941 * Turns on/off speaker.
1942 *
1943 * @param context Context
1944 * @param flag True when speaker should be on. False otherwise.
1945 * @param store True when the settings should be stored in the device.
1946 */
1947 /* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1948 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
1949 final PhoneGlobals app = PhoneGlobals.getInstance();
1950
1951 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1952 audioManager.setSpeakerphoneOn(flag);
1953
1954 // record the speaker-enable value
1955 if (store) {
1956 sIsSpeakerEnabled = flag;
1957 }
1958
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001959 // We also need to make a fresh call to PhoneApp.updateWakeState()
1960 // any time the speaker state changes, since the screen timeout is
1961 // sometimes different depending on whether or not the speaker is
1962 // in use.
1963 app.updateWakeState();
1964
Hariprasad Jayakumareee6a9e2014-04-25 15:33:13 -07001965 app.mCM.setEchoSuppressionEnabled();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001966 }
1967
1968 /**
1969 * Restore the speaker mode, called after a wired headset disconnect
1970 * event.
1971 */
1972 static void restoreSpeakerMode(Context context) {
1973 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1974
1975 // change the mode if needed.
1976 if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1977 turnOnSpeaker(context, sIsSpeakerEnabled, false);
1978 }
1979 }
1980
1981 static boolean isSpeakerOn(Context context) {
1982 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1983 return audioManager.isSpeakerphoneOn();
1984 }
1985
1986
1987 static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) {
1988 if (DBG) log("turnOnNoiseSuppression: " + flag);
1989 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1990
1991 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1992 return;
1993 }
1994
1995 if (flag) {
1996 audioManager.setParameters("noise_suppression=auto");
1997 } else {
1998 audioManager.setParameters("noise_suppression=off");
1999 }
2000
2001 // record the speaker-enable value
2002 if (store) {
2003 sIsNoiseSuppressionEnabled = flag;
2004 }
2005
2006 // TODO: implement and manage ICON
2007
2008 }
2009
2010 static void restoreNoiseSuppression(Context context) {
2011 if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled);
2012
2013 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
2014 return;
2015 }
2016
2017 // change the mode if needed.
2018 if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) {
2019 turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false);
2020 }
2021 }
2022
2023 static boolean isNoiseSuppressionOn(Context context) {
2024
2025 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
2026 return false;
2027 }
2028
2029 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
2030 String noiseSuppression = audioManager.getParameters("noise_suppression");
2031 if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression);
2032 if (noiseSuppression.contains("off")) {
2033 return false;
2034 } else {
2035 return true;
2036 }
2037 }
2038
2039 /**
2040 *
2041 * Mute / umute the foreground phone, which has the current foreground call
2042 *
2043 * All muting / unmuting from the in-call UI should go through this
2044 * wrapper.
2045 *
2046 * Wrapper around Phone.setMute() and setMicrophoneMute().
2047 * It also updates the connectionMuteTable and mute icon in the status bar.
2048 *
2049 */
2050 static void setMute(boolean muted) {
2051 CallManager cm = PhoneGlobals.getInstance().mCM;
2052
Santos Cordonc264cba2013-09-19 04:55:40 -07002053 // Emergency calls never get muted.
2054 if (isInEmergencyCall(cm)) {
2055 muted = false;
2056 }
2057
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002058 // make the call to mute the audio
2059 setMuteInternal(cm.getFgPhone(), muted);
2060
2061 // update the foreground connections to match. This includes
2062 // all the connections on conference calls.
2063 for (Connection cn : cm.getActiveFgCall().getConnections()) {
2064 if (sConnectionMuteTable.get(cn) == null) {
2065 if (DBG) log("problem retrieving mute value for this connection.");
2066 }
2067 sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
2068 }
Christine Chenbdc2da72013-10-02 18:06:26 -07002069
2070 // update the background connections to match. This includes
2071 // all the connections on conference calls.
2072 if (cm.hasActiveBgCall()) {
2073 for (Connection cn : cm.getFirstActiveBgCall().getConnections()) {
2074 if (sConnectionMuteTable.get(cn) == null) {
2075 if (DBG) log("problem retrieving mute value for this connection.");
2076 }
2077 sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
2078 }
2079 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002080 }
2081
Santos Cordonc264cba2013-09-19 04:55:40 -07002082 static boolean isInEmergencyCall(CallManager cm) {
2083 for (Connection cn : cm.getActiveFgCall().getConnections()) {
Yorke Lee36bb2542014-06-05 08:09:52 -07002084 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
2085 cn.getAddress())) {
Santos Cordonc264cba2013-09-19 04:55:40 -07002086 return true;
2087 }
2088 }
2089 return false;
2090 }
2091
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002092 /**
2093 * Internally used muting function.
2094 */
2095 private static void setMuteInternal(Phone phone, boolean muted) {
2096 final PhoneGlobals app = PhoneGlobals.getInstance();
2097 Context context = phone.getContext();
2098 boolean routeToAudioManager =
2099 context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
2100 if (routeToAudioManager) {
2101 AudioManager audioManager =
2102 (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE);
2103 if (DBG) log("setMuteInternal: using setMicrophoneMute(" + muted + ")...");
2104 audioManager.setMicrophoneMute(muted);
2105 } else {
2106 if (DBG) log("setMuteInternal: using phone.setMute(" + muted + ")...");
2107 phone.setMute(muted);
2108 }
Santos Cordoncd95f622013-08-29 03:38:52 -07002109 app.getAudioRouter().onMuteChange(muted);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002110 }
2111
2112 /**
2113 * Get the mute state of foreground phone, which has the current
2114 * foreground call
2115 */
2116 static boolean getMute() {
2117 final PhoneGlobals app = PhoneGlobals.getInstance();
2118
2119 boolean routeToAudioManager =
2120 app.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
2121 if (routeToAudioManager) {
2122 AudioManager audioManager =
2123 (AudioManager) app.getSystemService(Context.AUDIO_SERVICE);
2124 return audioManager.isMicrophoneMute();
2125 } else {
2126 return app.mCM.getMute();
2127 }
2128 }
2129
2130 /* package */ static void setAudioMode() {
2131 setAudioMode(PhoneGlobals.getInstance().mCM);
2132 }
2133
2134 /**
2135 * Sets the audio mode per current phone state.
2136 */
2137 /* package */ static void setAudioMode(CallManager cm) {
2138 if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState());
2139
2140 Context context = PhoneGlobals.getInstance();
2141 AudioManager audioManager = (AudioManager)
2142 context.getSystemService(Context.AUDIO_SERVICE);
2143 int modeBefore = audioManager.getMode();
2144 cm.setAudioMode();
2145 int modeAfter = audioManager.getMode();
2146
2147 if (modeBefore != modeAfter) {
2148 // Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
2149 if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
2150 } else {
2151 if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: "
2152 + audioModeToString(modeBefore));
2153 }
2154 }
2155 private static String audioModeToString(int mode) {
2156 switch (mode) {
2157 case AudioManager.MODE_INVALID: return "MODE_INVALID";
2158 case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
2159 case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
2160 case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
2161 case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
2162 default: return String.valueOf(mode);
2163 }
2164 }
2165
2166 /**
2167 * Handles the wired headset button while in-call.
2168 *
2169 * This is called from the PhoneApp, not from the InCallScreen,
2170 * since the HEADSETHOOK button means "mute or unmute the current
2171 * call" *any* time a call is active, even if the user isn't actually
2172 * on the in-call screen.
2173 *
2174 * @return true if we consumed the event.
2175 */
2176 /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) {
2177 if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount());
2178 final PhoneGlobals app = PhoneGlobals.getInstance();
2179
2180 // If the phone is totally idle, we ignore HEADSETHOOK events
2181 // (and instead let them fall through to the media player.)
2182 if (phone.getState() == PhoneConstants.State.IDLE) {
2183 return false;
2184 }
2185
2186 // Ok, the phone is in use.
2187 // The headset button button means "Answer" if an incoming call is
2188 // ringing. If not, it toggles the mute / unmute state.
2189 //
2190 // And in any case we *always* consume this event; this means
2191 // that the usual mediaplayer-related behavior of the headset
2192 // button will NEVER happen while the user is on a call.
2193
2194 final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2195 final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2196 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2197
2198 if (hasRingingCall &&
2199 event.getRepeatCount() == 0 &&
2200 event.getAction() == KeyEvent.ACTION_UP) {
2201 // If an incoming call is ringing, answer it (just like with the
2202 // CALL button):
2203 int phoneType = phone.getPhoneType();
2204 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
2205 answerCall(phone.getRingingCall());
2206 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002207 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
2208 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002209 if (hasActiveCall && hasHoldingCall) {
2210 if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
2211 answerAndEndActive(app.mCM, phone.getRingingCall());
2212 } else {
2213 if (DBG) log("handleHeadsetHook: ringing ==> answer!");
2214 // answerCall() will automatically hold the current
2215 // active call, if there is one.
2216 answerCall(phone.getRingingCall());
2217 }
2218 } else {
2219 throw new IllegalStateException("Unexpected phone type: " + phoneType);
2220 }
2221 } else {
2222 // No incoming ringing call.
2223 if (event.isLongPress()) {
2224 if (DBG) log("handleHeadsetHook: longpress -> hangup");
2225 hangup(app.mCM);
2226 }
2227 else if (event.getAction() == KeyEvent.ACTION_UP &&
2228 event.getRepeatCount() == 0) {
2229 Connection c = phone.getForegroundCall().getLatestConnection();
2230 // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook.
Yorke Lee36bb2542014-06-05 08:09:52 -07002231 if (c != null && !PhoneNumberUtils.isLocalEmergencyNumber(
2232 PhoneGlobals.getInstance(), c.getAddress())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002233 if (getMute()) {
2234 if (DBG) log("handleHeadsetHook: UNmuting...");
2235 setMute(false);
2236 } else {
2237 if (DBG) log("handleHeadsetHook: muting...");
2238 setMute(true);
2239 }
2240 }
2241 }
2242 }
2243
2244 // Even if the InCallScreen is the current activity, there's no
2245 // need to force it to update, because (1) if we answered a
2246 // ringing call, the InCallScreen will imminently get a phone
2247 // state change event (causing an update), and (2) if we muted or
2248 // unmuted, the setMute() call automagically updates the status
2249 // bar, and there's no "mute" indication in the InCallScreen
2250 // itself (other than the menu item, which only ever stays
2251 // onscreen for a second anyway.)
2252 // TODO: (2) isn't entirely true anymore. Once we return our result
2253 // to the PhoneApp, we ask InCallScreen to update its control widgets
2254 // in case we changed mute or speaker state and phones with touch-
2255 // screen [toggle] buttons need to update themselves.
2256
2257 return true;
2258 }
2259
2260 /**
2261 * Look for ANY connections on the phone that qualify as being
2262 * disconnected.
2263 *
2264 * @return true if we find a connection that is disconnected over
2265 * all the phone's call objects.
2266 */
2267 /* package */ static boolean hasDisconnectedConnections(Phone phone) {
2268 return hasDisconnectedConnections(phone.getForegroundCall()) ||
2269 hasDisconnectedConnections(phone.getBackgroundCall()) ||
2270 hasDisconnectedConnections(phone.getRingingCall());
2271 }
2272
2273 /**
2274 * Iterate over all connections in a call to see if there are any
2275 * that are not alive (disconnected or idle).
2276 *
2277 * @return true if we find a connection that is disconnected, and
2278 * pending removal via
2279 * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
2280 */
2281 private static final boolean hasDisconnectedConnections(Call call) {
2282 // look through all connections for non-active ones.
2283 for (Connection c : call.getConnections()) {
2284 if (!c.isAlive()) {
2285 return true;
2286 }
2287 }
2288 return false;
2289 }
2290
2291 //
2292 // Misc UI policy helper functions
2293 //
2294
2295 /**
Christine Chenaf2fd0a2013-09-13 16:27:40 -07002296 * @return true if we're allowed to hold calls, given the current
2297 * state of the Phone.
2298 */
2299 /* package */ static boolean okToHoldCall(CallManager cm) {
2300 final Call fgCall = cm.getActiveFgCall();
2301 final boolean hasHoldingCall = cm.hasActiveBgCall();
2302 final Call.State fgCallState = fgCall.getState();
2303
2304 // The "Hold" control is disabled entirely if there's
2305 // no way to either hold or unhold in the current state.
2306 final boolean okToHold = (fgCallState == Call.State.ACTIVE) && !hasHoldingCall;
2307 final boolean okToUnhold = cm.hasActiveBgCall() && (fgCallState == Call.State.IDLE);
2308 final boolean canHold = okToHold || okToUnhold;
2309
2310 return canHold;
2311 }
2312
2313 /**
2314 * @return true if we support holding calls, given the current
2315 * state of the Phone.
2316 */
2317 /* package */ static boolean okToSupportHold(CallManager cm) {
2318 boolean supportsHold = false;
2319
2320 final Call fgCall = cm.getActiveFgCall();
2321 final boolean hasHoldingCall = cm.hasActiveBgCall();
2322 final Call.State fgCallState = fgCall.getState();
2323
2324 if (TelephonyCapabilities.supportsHoldAndUnhold(fgCall.getPhone())) {
2325 // This phone has the concept of explicit "Hold" and "Unhold" actions.
2326 supportsHold = true;
2327 } else if (hasHoldingCall && (fgCallState == Call.State.IDLE)) {
2328 // Even when foreground phone device doesn't support hold/unhold, phone devices
2329 // for background holding calls may do.
2330 final Call bgCall = cm.getFirstActiveBgCall();
2331 if (bgCall != null &&
2332 TelephonyCapabilities.supportsHoldAndUnhold(bgCall.getPhone())) {
2333 supportsHold = true;
2334 }
2335 }
2336 return supportsHold;
2337 }
2338
2339 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002340 * @return true if we're allowed to swap calls, given the current
2341 * state of the Phone.
2342 */
2343 /* package */ static boolean okToSwapCalls(CallManager cm) {
2344 int phoneType = cm.getDefaultPhone().getPhoneType();
2345 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
2346 // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
2347 // state by either accepting a Call Waiting or by merging two calls
2348 PhoneGlobals app = PhoneGlobals.getInstance();
2349 return (app.cdmaPhoneCallState.getCurrentCallState()
2350 == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
2351 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002352 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
2353 || (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)
2413 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002414 // GSM: "Add call" is available only if ALL of the following are true:
2415 // - There's no incoming ringing call
2416 // - There's < 2 lines in use
2417 // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
2418 // (We mainly need to make sure it *isn't* DIALING or ALERTING.)
2419 final boolean hasRingingCall = cm.hasActiveRingingCall();
2420 final boolean hasActiveCall = cm.hasActiveFgCall();
2421 final boolean hasHoldingCall = cm.hasActiveBgCall();
2422 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2423
2424 return !hasRingingCall
2425 && !allLinesTaken
2426 && ((fgCallState == Call.State.ACTIVE)
2427 || (fgCallState == Call.State.IDLE)
2428 || (fgCallState == Call.State.DISCONNECTED));
2429 } else {
2430 throw new IllegalStateException("Unexpected phone type: " + phoneType);
2431 }
2432 }
2433
2434 /**
2435 * Based on the input CNAP number string,
2436 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
2437 * Otherwise, return CNAP_SPECIAL_CASE_NO.
2438 */
2439 private static int checkCnapSpecialCases(String n) {
2440 if (n.equals("PRIVATE") ||
2441 n.equals("P") ||
2442 n.equals("RES")) {
2443 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
2444 return PhoneConstants.PRESENTATION_RESTRICTED;
2445 } else if (n.equals("UNAVAILABLE") ||
2446 n.equals("UNKNOWN") ||
2447 n.equals("UNA") ||
2448 n.equals("U")) {
2449 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
2450 return PhoneConstants.PRESENTATION_UNKNOWN;
2451 } else {
2452 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
2453 return CNAP_SPECIAL_CASE_NO;
2454 }
2455 }
2456
2457 /**
2458 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
2459 * from the network to indicate different number presentations, convert them to
2460 * expected number and presentation values within the CallerInfo object.
2461 * @param number number we use to verify if we are in a corner case
2462 * @param presentation presentation value used to verify if we are in a corner case
2463 * @return the new String that should be used for the phone number
2464 */
2465 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
2466 String number, int presentation) {
2467 // Obviously we return number if ci == null, but still return number if
2468 // number == null, because in these cases the correct string will still be
2469 // displayed/logged after this function returns based on the presentation value.
2470 if (ci == null || number == null) return number;
2471
2472 if (DBG) {
2473 log("modifyForSpecialCnapCases: initially, number="
2474 + toLogSafePhoneNumber(number)
2475 + ", presentation=" + presentation + " ci " + ci);
2476 }
2477
2478 // "ABSENT NUMBER" is a possible value we could get from the network as the
2479 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
2480 // and fix the presentation to be the same.
2481 final String[] absentNumberValues =
2482 context.getResources().getStringArray(R.array.absent_num);
2483 if (Arrays.asList(absentNumberValues).contains(number)
2484 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
2485 number = context.getString(R.string.unknown);
2486 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
2487 }
2488
2489 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
2490 // cases only apply if we received an allowed presentation from the network, so check
2491 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
2492 // match the presentation passed in for verification (meaning we changed it previously
2493 // because it's a corner case and we're being called from a different entry point).
2494 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
2495 || (ci.numberPresentation != presentation
2496 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
2497 int cnapSpecialCase = checkCnapSpecialCases(number);
2498 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
2499 // For all special strings, change number & numberPresentation.
2500 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
2501 number = context.getString(R.string.private_num);
2502 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
2503 number = context.getString(R.string.unknown);
2504 }
2505 if (DBG) {
2506 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
2507 + "; presentation now=" + cnapSpecialCase);
2508 }
2509 ci.numberPresentation = cnapSpecialCase;
2510 }
2511 }
2512 if (DBG) {
2513 log("modifyForSpecialCnapCases: returning number string="
2514 + toLogSafePhoneNumber(number));
2515 }
2516 return number;
2517 }
2518
2519 //
2520 // Support for 3rd party phone service providers.
2521 //
2522
2523 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002524 * Check if a phone number can be route through a 3rd party
2525 * gateway. The number must be a global phone number in numerical
2526 * form (1-800-666-SEXY won't work).
2527 *
2528 * MMI codes and the like cannot be used as a dial number for the
2529 * gateway either.
2530 *
2531 * @param number To be dialed via a 3rd party gateway.
2532 * @return true If the number can be routed through the 3rd party network.
2533 */
Santos Cordon69a69192013-08-22 14:25:42 -07002534 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002535 if (TextUtils.isEmpty(number)) {
2536 return false;
2537 }
2538 number = PhoneNumberUtils.stripSeparators(number);
2539 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
2540 return false;
2541 }
2542 number = PhoneNumberUtils.extractNetworkPortion(number);
2543 return PhoneNumberUtils.isGlobalPhoneNumber(number);
2544 }
2545
2546 /**
2547 * This function is called when phone answers or places a call.
2548 * Check if the phone is in a car dock or desk dock.
2549 * If yes, turn on the speaker, when no wired or BT headsets are connected.
2550 * Otherwise do nothing.
2551 * @return true if activated
2552 */
2553 private static boolean activateSpeakerIfDocked(Phone phone) {
2554 if (DBG) log("activateSpeakerIfDocked()...");
2555
2556 boolean activated = false;
2557 if (PhoneGlobals.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
2558 if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
Santos Cordon593ab382013-08-06 21:58:23 -07002559 final PhoneGlobals app = PhoneGlobals.getInstance();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002560
Christine Chen3e0f0412013-09-18 20:33:49 -07002561 // TODO: This function should move to AudioRouter
Santos Cordon593ab382013-08-06 21:58:23 -07002562 final BluetoothManager btManager = app.getBluetoothManager();
2563 final WiredHeadsetManager wiredHeadset = app.getWiredHeadsetManager();
2564 final AudioRouter audioRouter = app.getAudioRouter();
2565
2566 if (!wiredHeadset.isHeadsetPlugged() && !btManager.isBluetoothHeadsetAudioOn()) {
2567 audioRouter.setSpeaker(true);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002568 activated = true;
2569 }
2570 }
2571 return activated;
2572 }
2573
2574
2575 /**
2576 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
2577 */
2578 /* package */ static boolean isPhoneInEcm(Phone phone) {
2579 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
2580 // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true".
2581 // TODO: There ought to be a better API for this than just
2582 // exposing a system property all the way up to the app layer,
2583 // probably a method like "inEcm()" provided by the telephony
2584 // layer.
2585 String ecmMode =
2586 SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
2587 if (ecmMode != null) {
2588 return ecmMode.equals("true");
2589 }
2590 }
2591 return false;
2592 }
2593
2594 /**
2595 * Returns the most appropriate Phone object to handle a call
2596 * to the specified number.
2597 *
2598 * @param cm the CallManager.
2599 * @param scheme the scheme from the data URI that the number originally came from.
2600 * @param number the phone number, or SIP address.
2601 */
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002602 public static Phone pickPhoneBasedOnNumber(CallManager cm, String scheme, String number,
2603 String primarySipUri, ComponentName thirdPartyCallComponent) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002604 if (DBG) {
2605 log("pickPhoneBasedOnNumber: scheme " + scheme
2606 + ", number " + toLogSafePhoneNumber(number)
2607 + ", sipUri "
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002608 + (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null")
2609 + ", thirdPartyCallComponent: " + thirdPartyCallComponent);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002610 }
2611
2612 if (primarySipUri != null) {
2613 Phone phone = getSipPhoneFromUri(cm, primarySipUri);
2614 if (phone != null) return phone;
2615 }
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002616
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002617 return cm.getDefaultPhone();
2618 }
2619
2620 public static Phone getSipPhoneFromUri(CallManager cm, String target) {
2621 for (Phone phone : cm.getAllPhones()) {
2622 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
2623 String sipUri = ((SipPhone) phone).getSipUri();
2624 if (target.equals(sipUri)) {
2625 if (DBG) log("- pickPhoneBasedOnNumber:" +
2626 "found SipPhone! obj = " + phone + ", "
2627 + phone.getClass());
2628 return phone;
2629 }
2630 }
2631 }
2632 return null;
2633 }
2634
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002635 /**
2636 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
2637 * meaning the call is the first real incoming call the phone is having.
2638 */
2639 public static boolean isRealIncomingCall(Call.State state) {
2640 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
2641 }
2642
2643 private static boolean sVoipSupported = false;
2644 static {
2645 PhoneGlobals app = PhoneGlobals.getInstance();
2646 sVoipSupported = SipManager.isVoipSupported(app)
2647 && app.getResources().getBoolean(com.android.internal.R.bool.config_built_in_sip_phone)
2648 && app.getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
2649 }
2650
2651 /**
2652 * @return true if this device supports voice calls using the built-in SIP stack.
2653 */
Sailesh Nepal6f342d92014-02-22 16:42:59 -08002654 public static boolean isVoipSupported() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002655 return sVoipSupported;
2656 }
2657
2658 public static String getPresentationString(Context context, int presentation) {
2659 String name = context.getString(R.string.unknown);
2660 if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
2661 name = context.getString(R.string.private_num);
2662 } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
2663 name = context.getString(R.string.payphone);
2664 }
2665 return name;
2666 }
2667
2668 public static void sendViewNotificationAsync(Context context, Uri contactUri) {
2669 if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")");
2670 Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri);
2671 intent.setClassName("com.android.contacts",
2672 "com.android.contacts.ViewNotificationService");
2673 context.startService(intent);
2674 }
2675
2676 //
2677 // General phone and call state debugging/testing code
2678 //
2679
2680 /* package */ static void dumpCallState(Phone phone) {
2681 PhoneGlobals app = PhoneGlobals.getInstance();
2682 Log.d(LOG_TAG, "dumpCallState():");
2683 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
2684 + ", state = " + phone.getState());
2685
2686 StringBuilder b = new StringBuilder(128);
2687
2688 Call call = phone.getForegroundCall();
2689 b.setLength(0);
2690 b.append(" - FG call: ").append(call.getState());
2691 b.append(" isAlive ").append(call.getState().isAlive());
2692 b.append(" isRinging ").append(call.getState().isRinging());
2693 b.append(" isDialing ").append(call.getState().isDialing());
2694 b.append(" isIdle ").append(call.isIdle());
2695 b.append(" hasConnections ").append(call.hasConnections());
2696 Log.d(LOG_TAG, b.toString());
2697
2698 call = phone.getBackgroundCall();
2699 b.setLength(0);
2700 b.append(" - BG call: ").append(call.getState());
2701 b.append(" isAlive ").append(call.getState().isAlive());
2702 b.append(" isRinging ").append(call.getState().isRinging());
2703 b.append(" isDialing ").append(call.getState().isDialing());
2704 b.append(" isIdle ").append(call.isIdle());
2705 b.append(" hasConnections ").append(call.hasConnections());
2706 Log.d(LOG_TAG, b.toString());
2707
2708 call = phone.getRingingCall();
2709 b.setLength(0);
2710 b.append(" - RINGING call: ").append(call.getState());
2711 b.append(" isAlive ").append(call.getState().isAlive());
2712 b.append(" isRinging ").append(call.getState().isRinging());
2713 b.append(" isDialing ").append(call.getState().isDialing());
2714 b.append(" isIdle ").append(call.isIdle());
2715 b.append(" hasConnections ").append(call.hasConnections());
2716 Log.d(LOG_TAG, b.toString());
2717
2718
2719 final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2720 final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2721 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2722 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2723 b.setLength(0);
2724 b.append(" - hasRingingCall ").append(hasRingingCall);
2725 b.append(" hasActiveCall ").append(hasActiveCall);
2726 b.append(" hasHoldingCall ").append(hasHoldingCall);
2727 b.append(" allLinesTaken ").append(allLinesTaken);
2728 Log.d(LOG_TAG, b.toString());
2729
2730 // On CDMA phones, dump out the CdmaPhoneCallState too:
2731 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
2732 if (app.cdmaPhoneCallState != null) {
2733 Log.d(LOG_TAG, " - CDMA call state: "
2734 + app.cdmaPhoneCallState.getCurrentCallState());
2735 } else {
2736 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!");
2737 }
2738 }
2739
2740 // Watch out: the isRinging() call below does NOT tell us anything
2741 // about the state of the telephony layer; it merely tells us whether
2742 // the Ringer manager is currently playing the ringtone.
2743 boolean ringing = app.getRinger().isRinging();
2744 Log.d(LOG_TAG, " - Ringer state: " + ringing);
2745 }
2746
2747 private static void log(String msg) {
2748 Log.d(LOG_TAG, msg);
2749 }
2750
2751 static void dumpCallManager() {
2752 Call call;
2753 CallManager cm = PhoneGlobals.getInstance().mCM;
2754 StringBuilder b = new StringBuilder(128);
2755
2756
2757
2758 Log.d(LOG_TAG, "############### dumpCallManager() ##############");
2759 // TODO: Don't log "cm" itself, since CallManager.toString()
2760 // already spews out almost all this same information.
2761 // We should fix CallManager.toString() to be more minimal, and
2762 // use an explicit dumpState() method for the verbose dump.
2763 // Log.d(LOG_TAG, "CallManager: " + cm
2764 // + ", state = " + cm.getState());
2765 Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
2766 b.setLength(0);
2767 call = cm.getActiveFgCall();
2768 b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
2769 b.append(call);
2770 b.append( " State: ").append(cm.getActiveFgCallState());
2771 b.append( " Conn: ").append(cm.getFgCallConnections());
2772 Log.d(LOG_TAG, b.toString());
2773 b.setLength(0);
2774 call = cm.getFirstActiveBgCall();
2775 b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
2776 b.append(call);
2777 b.append( " State: ").append(cm.getFirstActiveBgCall().getState());
2778 b.append( " Conn: ").append(cm.getBgCallConnections());
2779 Log.d(LOG_TAG, b.toString());
2780 b.setLength(0);
2781 call = cm.getFirstActiveRingingCall();
2782 b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
2783 b.append(call);
2784 b.append( " State: ").append(cm.getFirstActiveRingingCall().getState());
2785 Log.d(LOG_TAG, b.toString());
2786
2787
2788
2789 for (Phone phone : CallManager.getInstance().getAllPhones()) {
2790 if (phone != null) {
2791 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
2792 + ", state = " + phone.getState());
2793 b.setLength(0);
2794 call = phone.getForegroundCall();
2795 b.append(" - FG call: ").append(call);
2796 b.append( " State: ").append(call.getState());
2797 b.append( " Conn: ").append(call.hasConnections());
2798 Log.d(LOG_TAG, b.toString());
2799 b.setLength(0);
2800 call = phone.getBackgroundCall();
2801 b.append(" - BG call: ").append(call);
2802 b.append( " State: ").append(call.getState());
2803 b.append( " Conn: ").append(call.hasConnections());
2804 Log.d(LOG_TAG, b.toString());b.setLength(0);
2805 call = phone.getRingingCall();
2806 b.append(" - RINGING call: ").append(call);
2807 b.append( " State: ").append(call.getState());
2808 b.append( " Conn: ").append(call.hasConnections());
2809 Log.d(LOG_TAG, b.toString());
2810 }
2811 }
2812
2813 Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
2814 }
2815
2816 /**
2817 * @return if the context is in landscape orientation.
2818 */
2819 public static boolean isLandscape(Context context) {
2820 return context.getResources().getConfiguration().orientation
2821 == Configuration.ORIENTATION_LANDSCAPE;
2822 }
2823}