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