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