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