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