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