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