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