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