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