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