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