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