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