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