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