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