PhoneUtils.java revision 84952328a62bd2e04e64155ea9284df2c74a5657
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                shouldMute = sConnectionMuteTable.get(c);
722            }
723            if (shouldMute == null) {
724                if (DBG) log("problem retrieving mute value for this connection.");
725                shouldMute = Boolean.FALSE;
726            }
727
728            // set the mute value and return the result.
729            setMute (shouldMute.booleanValue());
730            return shouldMute;
731        }
732        return Boolean.valueOf(getMute());
733    }
734
735    static void mergeCalls() {
736        mergeCalls(PhoneApp.getInstance().mCM);
737    }
738
739    static void mergeCalls(CallManager cm) {
740        int phoneType = cm.getFgPhone().getPhoneType();
741        if (phoneType == Phone.PHONE_TYPE_CDMA) {
742            if (DBG) log("mergeCalls");
743            PhoneApp app = PhoneApp.getInstance();
744            if (app.cdmaPhoneCallState.getCurrentCallState()
745                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
746                // Set the Phone Call State to conference
747                app.cdmaPhoneCallState.setCurrentCallState(
748                        CdmaPhoneCallState.PhoneCallState.CONF_CALL);
749
750                // Send flash cmd
751                // TODO: Need to change the call from switchHoldingAndActive to
752                // something meaningful as we are not actually trying to swap calls but
753                // instead are merging two calls by sending a Flash command.
754                switchHoldingAndActive(cm.getFirstActiveBgCall());
755            }
756        } else {
757            try {
758                if (DBG) log("mergeCalls");
759                cm.conference(cm.getFirstActiveBgCall());
760            } catch (CallStateException ex) {
761                Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
762            }
763        }
764    }
765
766    static void separateCall(Connection c) {
767        try {
768            if (DBG) log("separateCall: " + c.getAddress());
769            c.separate();
770        } catch (CallStateException ex) {
771            Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
772        }
773    }
774
775    /**
776     * Handle the MMIInitiate message and put up an alert that lets
777     * the user cancel the operation, if applicable.
778     *
779     * @param context context to get strings.
780     * @param mmiCode the MmiCode object being started.
781     * @param buttonCallbackMessage message to post when button is clicked.
782     * @param previousAlert a previous alert used in this activity.
783     * @return the dialog handle
784     */
785    static Dialog displayMMIInitiate(Context context,
786                                          MmiCode mmiCode,
787                                          Message buttonCallbackMessage,
788                                          Dialog previousAlert) {
789        if (DBG) log("displayMMIInitiate: " + mmiCode);
790        if (previousAlert != null) {
791            previousAlert.dismiss();
792        }
793
794        // The UI paradigm we are using now requests that all dialogs have
795        // user interaction, and that any other messages to the user should
796        // be by way of Toasts.
797        //
798        // In adhering to this request, all MMI initiating "OK" dialogs
799        // (non-cancelable MMIs) that end up being closed when the MMI
800        // completes (thereby showing a completion dialog) are being
801        // replaced with Toasts.
802        //
803        // As a side effect, moving to Toasts for the non-cancelable MMIs
804        // also means that buttonCallbackMessage (which was tied into "OK")
805        // is no longer invokable for these dialogs.  This is not a problem
806        // since the only callback messages we supported were for cancelable
807        // MMIs anyway.
808        //
809        // A cancelable MMI is really just a USSD request. The term
810        // "cancelable" here means that we can cancel the request when the
811        // system prompts us for a response, NOT while the network is
812        // processing the MMI request.  Any request to cancel a USSD while
813        // the network is NOT ready for a response may be ignored.
814        //
815        // With this in mind, we replace the cancelable alert dialog with
816        // a progress dialog, displayed until we receive a request from
817        // the the network.  For more information, please see the comments
818        // in the displayMMIComplete() method below.
819        //
820        // Anything that is NOT a USSD request is a normal MMI request,
821        // which will bring up a toast (desribed above).
822        // Optional code for Extended USSD running prompt
823        if (mNwService != null) {
824            if (DBG) log("running USSD code, displaying indeterminate progress.");
825            // create the indeterminate progress dialog and display it.
826            ProgressDialog pd = new ProgressDialog(context);
827            CharSequence textmsg = "";
828            try {
829                textmsg = mNwService.getMmiRunningText();
830
831            } catch (RemoteException e) {
832                mNwService = null;
833                textmsg = context.getText(R.string.ussdRunning);
834            }
835            if (DBG) log("Extended NW displayMMIInitiate (" + textmsg+ ")");
836            pd.setMessage(textmsg);
837            pd.setCancelable(false);
838            pd.setIndeterminate(true);
839            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
840            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
841            pd.show();
842            // trigger a 15 seconds timeout to clear this progress dialog
843            mMmiTimeoutCbMsg = buttonCallbackMessage;
844            try {
845                mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000);
846            } catch(NullPointerException e) {
847                mMmiTimeoutCbMsg = null;
848            }
849            return pd;
850        }
851
852        boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
853
854        if (!isCancelable) {
855            if (DBG) log("not a USSD code, displaying status toast.");
856            CharSequence text = context.getText(R.string.mmiStarted);
857            Toast.makeText(context, text, Toast.LENGTH_SHORT)
858                .show();
859            return null;
860        } else {
861            if (DBG) log("running USSD code, displaying indeterminate progress.");
862
863            // create the indeterminate progress dialog and display it.
864            ProgressDialog pd = new ProgressDialog(context);
865            pd.setMessage(context.getText(R.string.ussdRunning));
866            pd.setCancelable(false);
867            pd.setIndeterminate(true);
868            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
869
870            pd.show();
871
872            return pd;
873        }
874
875    }
876
877    /**
878     * Handle the MMIComplete message and fire off an intent to display
879     * the message.
880     *
881     * @param context context to get strings.
882     * @param mmiCode MMI result.
883     * @param previousAlert a previous alert used in this activity.
884     */
885    static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
886            Message dismissCallbackMessage,
887            AlertDialog previousAlert) {
888        CharSequence text;
889        int title = 0;  // title for the progress dialog, if needed.
890        MmiCode.State state = mmiCode.getState();
891
892        if (DBG) log("displayMMIComplete: state=" + state);
893        // Clear timeout trigger message
894        if(mMmiTimeoutCbMsg != null) {
895            try{
896                mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what);
897                if (DBG) log("Extended NW displayMMIComplete removeMsg");
898            } catch (NullPointerException e) {
899            }
900            mMmiTimeoutCbMsg = null;
901        }
902
903
904        switch (state) {
905            case PENDING:
906                // USSD code asking for feedback from user.
907                text = mmiCode.getMessage();
908                if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
909                break;
910            case CANCELLED:
911                text = context.getText(R.string.mmiCancelled);
912                break;
913            case COMPLETE:
914                if (PhoneApp.getInstance().getPUKEntryActivity() != null) {
915                    // if an attempt to unPUK the device was made, we specify
916                    // the title and the message here.
917                    title = com.android.internal.R.string.PinMmi;
918                    text = context.getText(R.string.puk_unlocked);
919                    break;
920                }
921                // All other conditions for the COMPLETE mmi state will cause
922                // the case to fall through to message logic in common with
923                // the FAILED case.
924
925            case FAILED:
926                text = mmiCode.getMessage();
927                if (DBG) log("- using text from MMI message: '" + text + "'");
928                break;
929            default:
930                throw new IllegalStateException("Unexpected MmiCode state: " + state);
931        }
932
933        if (previousAlert != null) {
934            previousAlert.dismiss();
935        }
936
937        // Check to see if a UI exists for the PUK activation.  If it does
938        // exist, then it indicates that we're trying to unblock the PUK.
939        PhoneApp app = PhoneApp.getInstance();
940        if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
941            if (DBG) log("displaying PUK unblocking progress dialog.");
942
943            // create the progress dialog, make sure the flags and type are
944            // set correctly.
945            ProgressDialog pd = new ProgressDialog(app);
946            pd.setTitle(title);
947            pd.setMessage(text);
948            pd.setCancelable(false);
949            pd.setIndeterminate(true);
950            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
951            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
952
953            // display the dialog
954            pd.show();
955
956            // indicate to the Phone app that the progress dialog has
957            // been assigned for the PUK unlock / SIM READY process.
958            app.setPukEntryProgressDialog(pd);
959
960        } else {
961            // In case of failure to unlock, we'll need to reset the
962            // PUK unlock activity, so that the user may try again.
963            if (app.getPUKEntryActivity() != null) {
964                app.setPukEntryActivity(null);
965            }
966
967            // A USSD in a pending state means that it is still
968            // interacting with the user.
969            if (state != MmiCode.State.PENDING) {
970                if (DBG) log("MMI code has finished running.");
971
972                // Replace response message with Extended Mmi wording
973                if (mNwService != null) {
974                    try {
975                        text = mNwService.getUserMessage(text);
976                    } catch (RemoteException e) {
977                        mNwService = null;
978                    }
979                    if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
980                    if (text == null || text.length() == 0)
981                        return;
982                }
983
984                // displaying system alert dialog on the screen instead of
985                // using another activity to display the message.  This
986                // places the message at the forefront of the UI.
987                AlertDialog newDialog = new AlertDialog.Builder(context)
988                        .setMessage(text)
989                        .setPositiveButton(R.string.ok, null)
990                        .setCancelable(true)
991                        .create();
992
993                newDialog.getWindow().setType(
994                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
995                newDialog.getWindow().addFlags(
996                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
997
998                newDialog.show();
999            } else {
1000                if (DBG) log("USSD code has requested user input. Constructing input dialog.");
1001
1002                // USSD MMI code that is interacting with the user.  The
1003                // basic set of steps is this:
1004                //   1. User enters a USSD request
1005                //   2. We recognize the request and displayMMIInitiate
1006                //      (above) creates a progress dialog.
1007                //   3. Request returns and we get a PENDING or COMPLETE
1008                //      message.
1009                //   4. These MMI messages are caught in the PhoneApp
1010                //      (onMMIComplete) and the InCallScreen
1011                //      (mHandler.handleMessage) which bring up this dialog
1012                //      and closes the original progress dialog,
1013                //      respectively.
1014                //   5. If the message is anything other than PENDING,
1015                //      we are done, and the alert dialog (directly above)
1016                //      displays the outcome.
1017                //   6. If the network is requesting more information from
1018                //      the user, the MMI will be in a PENDING state, and
1019                //      we display this dialog with the message.
1020                //   7. User input, or cancel requests result in a return
1021                //      to step 1.  Keep in mind that this is the only
1022                //      time that a USSD should be canceled.
1023
1024                // inflate the layout with the scrolling text area for the dialog.
1025                LayoutInflater inflater = (LayoutInflater) context.getSystemService(
1026                        Context.LAYOUT_INFLATER_SERVICE);
1027                View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
1028
1029                // get the input field.
1030                final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
1031
1032                // specify the dialog's click listener, with SEND and CANCEL logic.
1033                final DialogInterface.OnClickListener mUSSDDialogListener =
1034                    new DialogInterface.OnClickListener() {
1035                        public void onClick(DialogInterface dialog, int whichButton) {
1036                            switch (whichButton) {
1037                                case DialogInterface.BUTTON_POSITIVE:
1038                                    phone.sendUssdResponse(inputText.getText().toString());
1039                                    break;
1040                                case DialogInterface.BUTTON_NEGATIVE:
1041                                    if (mmiCode.isCancelable()) {
1042                                        mmiCode.cancel();
1043                                    }
1044                                    break;
1045                            }
1046                        }
1047                    };
1048
1049                // build the dialog
1050                final AlertDialog newDialog = new AlertDialog.Builder(context)
1051                        .setMessage(text)
1052                        .setView(dialogView)
1053                        .setPositiveButton(R.string.send_button, mUSSDDialogListener)
1054                        .setNegativeButton(R.string.cancel, mUSSDDialogListener)
1055                        .setCancelable(false)
1056                        .create();
1057
1058                // attach the key listener to the dialog's input field and make
1059                // sure focus is set.
1060                final View.OnKeyListener mUSSDDialogInputListener =
1061                    new View.OnKeyListener() {
1062                        public boolean onKey(View v, int keyCode, KeyEvent event) {
1063                            switch (keyCode) {
1064                                case KeyEvent.KEYCODE_CALL:
1065                                case KeyEvent.KEYCODE_ENTER:
1066                                    phone.sendUssdResponse(inputText.getText().toString());
1067                                    newDialog.dismiss();
1068                                    return true;
1069                            }
1070                            return false;
1071                        }
1072                    };
1073                inputText.setOnKeyListener(mUSSDDialogInputListener);
1074                inputText.requestFocus();
1075
1076                // set the window properties of the dialog
1077                newDialog.getWindow().setType(
1078                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1079                newDialog.getWindow().addFlags(
1080                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1081
1082                // now show the dialog!
1083                newDialog.show();
1084            }
1085        }
1086    }
1087
1088    /**
1089     * Cancels the current pending MMI operation, if applicable.
1090     * @return true if we canceled an MMI operation, or false
1091     *         if the current pending MMI wasn't cancelable
1092     *         or if there was no current pending MMI at all.
1093     *
1094     * @see displayMMIInitiate
1095     */
1096    static boolean cancelMmiCode(Phone phone) {
1097        List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
1098        int count = pendingMmis.size();
1099        if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
1100
1101        boolean canceled = false;
1102        if (count > 0) {
1103            // assume that we only have one pending MMI operation active at a time.
1104            // I don't think it's possible to enter multiple MMI codes concurrently
1105            // in the phone UI, because during the MMI operation, an Alert panel
1106            // is displayed, which prevents more MMI code from being entered.
1107            MmiCode mmiCode = pendingMmis.get(0);
1108            if (mmiCode.isCancelable()) {
1109                mmiCode.cancel();
1110                canceled = true;
1111            }
1112        }
1113
1114        //clear timeout message and pre-set MMI command
1115        if (mNwService != null) {
1116            try {
1117                mNwService.clearMmiString();
1118            } catch (RemoteException e) {
1119                mNwService = null;
1120            }
1121        }
1122        if (mMmiTimeoutCbMsg != null) {
1123            mMmiTimeoutCbMsg = null;
1124        }
1125        return canceled;
1126    }
1127
1128    public static class VoiceMailNumberMissingException extends Exception {
1129        VoiceMailNumberMissingException() {
1130            super();
1131        }
1132
1133        VoiceMailNumberMissingException(String msg) {
1134            super(msg);
1135        }
1136    }
1137
1138    /**
1139     * Gets the phone number to be called from an intent.  Requires a Context
1140     * to access the contacts database, and a Phone to access the voicemail
1141     * number.
1142     *
1143     * <p>If <code>phone</code> is <code>null</code>, the function will return
1144     * <code>null</code> for <code>voicemail:</code> URIs;
1145     * if <code>context</code> is <code>null</code>, the function will return
1146     * <code>null</code> for person/phone URIs.</p>
1147     *
1148     * <p>If the intent contains a <code>sip:</code> URI, the returned
1149     * "number" is actually the SIP address.
1150     *
1151     * @param context a context to use (or
1152     * @param intent the intent
1153     *
1154     * @throws VoiceMailNumberMissingException if <code>intent</code> contains
1155     *         a <code>voicemail:</code> URI, but <code>phone</code> does not
1156     *         have a voicemail number set.
1157     *
1158     * @return the phone number (or SIP address) that would be called by the intent,
1159     *         or <code>null</code> if the number cannot be found.
1160     */
1161    static String getNumberFromIntent(Context context, Intent intent)
1162            throws VoiceMailNumberMissingException {
1163        Uri uri = intent.getData();
1164        String scheme = uri.getScheme();
1165
1166        // The sip: scheme is simple: just treat the rest of the URI as a
1167        // SIP address.
1168        if (scheme.equals("sip")) {
1169            return uri.getSchemeSpecificPart();
1170        }
1171
1172        // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
1173        // the other cases (i.e. tel: and voicemail: and contact: URIs.)
1174
1175        final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
1176
1177        // Check for a voicemail-dialing request.  If the voicemail number is
1178        // empty, throw a VoiceMailNumberMissingException.
1179        if (scheme.equals("voicemail") &&
1180                (number == null || TextUtils.isEmpty(number)))
1181            throw new VoiceMailNumberMissingException();
1182
1183        return number;
1184    }
1185
1186    /**
1187     * Returns the caller-id info corresponding to the specified Connection.
1188     * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
1189     * extract a phone number from the specified Connection, and feed that
1190     * number into CallerInfo.getCallerInfo().)
1191     *
1192     * The returned CallerInfo may be null in certain error cases, like if the
1193     * specified Connection was null, or if we weren't able to get a valid
1194     * phone number from the Connection.
1195     *
1196     * Finally, if the getCallerInfo() call did succeed, we save the resulting
1197     * CallerInfo object in the "userData" field of the Connection.
1198     *
1199     * NOTE: This API should be avoided, with preference given to the
1200     * asynchronous startGetCallerInfo API.
1201     */
1202    static CallerInfo getCallerInfo(Context context, Connection c) {
1203        CallerInfo info = null;
1204
1205        if (c != null) {
1206            //See if there is a URI attached.  If there is, this means
1207            //that there is no CallerInfo queried yet, so we'll need to
1208            //replace the URI with a full CallerInfo object.
1209            Object userDataObject = c.getUserData();
1210            if (userDataObject instanceof Uri) {
1211                info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1212                if (info != null) {
1213                    c.setUserData(info);
1214                }
1215            } else {
1216                if (userDataObject instanceof CallerInfoToken) {
1217                    //temporary result, while query is running
1218                    info = ((CallerInfoToken) userDataObject).currentInfo;
1219                } else {
1220                    //final query result
1221                    info = (CallerInfo) userDataObject;
1222                }
1223                if (info == null) {
1224                    // No URI, or Existing CallerInfo, so we'll have to make do with
1225                    // querying a new CallerInfo using the connection's phone number.
1226                    String number = c.getAddress();
1227
1228                    if (DBG) log("getCallerInfo: number = " + number);
1229
1230                    if (!TextUtils.isEmpty(number)) {
1231                        info = CallerInfo.getCallerInfo(context, number);
1232                        if (info != null) {
1233                            c.setUserData(info);
1234                        }
1235                    }
1236                }
1237            }
1238        }
1239        return info;
1240    }
1241
1242    /**
1243     * Class returned by the startGetCallerInfo call to package a temporary
1244     * CallerInfo Object, to be superceded by the CallerInfo Object passed
1245     * into the listener when the query with token mAsyncQueryToken is complete.
1246     */
1247    public static class CallerInfoToken {
1248        /**indicates that there will no longer be updates to this request.*/
1249        public boolean isFinal;
1250
1251        public CallerInfo currentInfo;
1252        public CallerInfoAsyncQuery asyncQuery;
1253    }
1254
1255    /**
1256     * Start a CallerInfo Query based on the earliest connection in the call.
1257     */
1258    static CallerInfoToken startGetCallerInfo(Context context, Call call,
1259            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1260        PhoneApp app = PhoneApp.getInstance();
1261        Connection conn = null;
1262        int phoneType = app.phone.getPhoneType();
1263        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1264            conn = call.getLatestConnection();
1265        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1266            conn = call.getEarliestConnection();
1267        } else {
1268            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1269        }
1270
1271        return startGetCallerInfo(context, conn, listener, cookie);
1272    }
1273
1274    /**
1275     * place a temporary callerinfo object in the hands of the caller and notify
1276     * caller when the actual query is done.
1277     */
1278    static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1279            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1280        CallerInfoToken cit;
1281
1282        if (c == null) {
1283            //TODO: perhaps throw an exception here.
1284            cit = new CallerInfoToken();
1285            cit.asyncQuery = null;
1286            return cit;
1287        }
1288
1289        // There are now 3 states for the userdata.
1290        //   1. Uri - query has not been executed yet
1291        //   2. CallerInfoToken - query is executing, but has not completed.
1292        //   3. CallerInfo - query has executed.
1293        // In each case we have slightly different behaviour:
1294        //   1. If the query has not been executed yet (Uri or null), we start
1295        //      query execution asynchronously, and note it by attaching a
1296        //      CallerInfoToken as the userData.
1297        //   2. If the query is executing (CallerInfoToken), we've essentially
1298        //      reached a state where we've received multiple requests for the
1299        //      same callerInfo.  That means that once the query is complete,
1300        //      we'll need to execute the additional listener requested.
1301        //   3. If the query has already been executed (CallerInfo), we just
1302        //      return the CallerInfo object as expected.
1303        //   4. Regarding isFinal - there are cases where the CallerInfo object
1304        //      will not be attached, like when the number is empty (caller id
1305        //      blocking).  This flag is used to indicate that the
1306        //      CallerInfoToken object is going to be permanent since no
1307        //      query results will be returned.  In the case where a query
1308        //      has been completed, this flag is used to indicate to the caller
1309        //      that the data will not be updated since it is valid.
1310        //
1311        //      Note: For the case where a number is NOT retrievable, we leave
1312        //      the CallerInfo as null in the CallerInfoToken.  This is
1313        //      something of a departure from the original code, since the old
1314        //      code manufactured a CallerInfo object regardless of the query
1315        //      outcome.  From now on, we will append an empty CallerInfo
1316        //      object, to mirror previous behaviour, and to avoid Null Pointer
1317        //      Exceptions.
1318        Object userDataObject = c.getUserData();
1319        if (userDataObject instanceof Uri) {
1320            //create a dummy callerinfo, populate with what we know from URI.
1321            cit = new CallerInfoToken();
1322            cit.currentInfo = new CallerInfo();
1323            cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1324                    (Uri) userDataObject, sCallerInfoQueryListener, c);
1325            cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1326            cit.isFinal = false;
1327
1328            c.setUserData(cit);
1329
1330            if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1331
1332        } else if (userDataObject == null) {
1333            // No URI, or Existing CallerInfo, so we'll have to make do with
1334            // querying a new CallerInfo using the connection's phone number.
1335            String number = c.getAddress();
1336
1337            cit = new CallerInfoToken();
1338            cit.currentInfo = new CallerInfo();
1339
1340            // Store CNAP information retrieved from the Connection (we want to do this
1341            // here regardless of whether the number is empty or not).
1342            cit.currentInfo.cnapName =  c.getCnapName();
1343            cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1344                                                             // by ContactInfo later
1345            cit.currentInfo.numberPresentation = c.getNumberPresentation();
1346            cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1347
1348            if (DBG) {
1349                log("startGetCallerInfo: number = " + number);
1350                log("startGetCallerInfo: CNAP Info from FW(1): name="
1351                    + cit.currentInfo.cnapName
1352                    + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1353            }
1354
1355            // handling case where number is null (caller id hidden) as well.
1356            if (!TextUtils.isEmpty(number)) {
1357                // Check for special CNAP cases and modify the CallerInfo accordingly
1358                // to be sure we keep the right information to display/log later
1359                number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
1360                        cit.currentInfo.numberPresentation);
1361
1362                cit.currentInfo.phoneNumber = number;
1363                // For scenarios where we may receive a valid number from the network but a
1364                // restricted/unavailable presentation, we do not want to perform a contact query
1365                // (see note on isFinal above). So we set isFinal to true here as well.
1366                if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) {
1367                    cit.isFinal = true;
1368                } else {
1369                    cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1370                            number, sCallerInfoQueryListener, c);
1371                    cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1372                    cit.isFinal = false;
1373                }
1374            } else {
1375                // This is the case where we are querying on a number that
1376                // is null or empty, like a caller whose caller id is
1377                // blocked or empty (CLIR).  The previous behaviour was to
1378                // throw a null CallerInfo object back to the user, but
1379                // this departure is somewhat cleaner.
1380                if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1381                cit.isFinal = true; // please see note on isFinal, above.
1382            }
1383
1384            c.setUserData(cit);
1385
1386            if (DBG) log("startGetCallerInfo: query based on number: " + number);
1387
1388        } else if (userDataObject instanceof CallerInfoToken) {
1389            // query is running, just tack on this listener to the queue.
1390            cit = (CallerInfoToken) userDataObject;
1391
1392            // handling case where number is null (caller id hidden) as well.
1393            if (cit.asyncQuery != null) {
1394                cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1395
1396                if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1397                        listener.getClass().toString());
1398            } else {
1399                // handling case where number/name gets updated later on by the network
1400                String updatedNumber = c.getAddress();
1401                if (DBG) log("startGetCallerInfo: updatedNumber initially = " + updatedNumber);
1402                if (!TextUtils.isEmpty(updatedNumber)) {
1403                    // Store CNAP information retrieved from the Connection
1404                    cit.currentInfo.cnapName =  c.getCnapName();
1405                    // This can still get overwritten by ContactInfo
1406                    cit.currentInfo.name = cit.currentInfo.cnapName;
1407                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1408                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1409
1410                    updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1411                            updatedNumber, cit.currentInfo.numberPresentation);
1412
1413                    cit.currentInfo.phoneNumber = updatedNumber;
1414                    if (DBG) log("startGetCallerInfo: updatedNumber=" + updatedNumber);
1415                    if (DBG) log("startGetCallerInfo: CNAP Info from FW(2): name="
1416                            + cit.currentInfo.cnapName
1417                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1418                    // For scenarios where we may receive a valid number from the network but a
1419                    // restricted/unavailable presentation, we do not want to perform a contact query
1420                    // (see note on isFinal above). So we set isFinal to true here as well.
1421                    if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) {
1422                        cit.isFinal = true;
1423                    } else {
1424                        cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1425                                updatedNumber, sCallerInfoQueryListener, c);
1426                        cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1427                        cit.isFinal = false;
1428                    }
1429                } else {
1430                    if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1431                    if (cit.currentInfo == null) {
1432                        cit.currentInfo = new CallerInfo();
1433                    }
1434                    // Store CNAP information retrieved from the Connection
1435                    cit.currentInfo.cnapName = c.getCnapName();  // This can still get
1436                                                                 // overwritten by ContactInfo
1437                    cit.currentInfo.name = cit.currentInfo.cnapName;
1438                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1439                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1440
1441                    if (DBG) log("startGetCallerInfo: CNAP Info from FW(3): name="
1442                            + cit.currentInfo.cnapName
1443                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1444                    cit.isFinal = true; // please see note on isFinal, above.
1445                }
1446            }
1447        } else {
1448            cit = new CallerInfoToken();
1449            cit.currentInfo = (CallerInfo) userDataObject;
1450            cit.asyncQuery = null;
1451            cit.isFinal = true;
1452            // since the query is already done, call the listener.
1453            if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1454        }
1455        return cit;
1456    }
1457
1458    /**
1459     * Implemented for CallerInfo.OnCallerInfoQueryCompleteListener interface.
1460     * Updates the connection's userData when called.
1461     */
1462    private static final int QUERY_TOKEN = -1;
1463    static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1464        new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1465            public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1466                if (DBG) log("query complete, updating connection.userdata");
1467                Connection conn = (Connection) cookie;
1468
1469                // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1470                // If no ContactInfo, then we want to use CNAP information coming from network
1471                if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1472                if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1473                    // If the number presentation has not been set by
1474                    // the ContactInfo, use the one from the
1475                    // connection.
1476
1477                    // TODO: Need a new util method to merge the info
1478                    // from the Connection in a CallerInfo object.
1479                    // Here 'ci' is a new CallerInfo instance read
1480                    // from the DB. It has lost all the connection
1481                    // info preset before the query (see PhoneUtils
1482                    // line 1334). We should have a method to merge
1483                    // back into this new instance the info from the
1484                    // connection object not set by the DB. If the
1485                    // Connection already has a CallerInfo instance in
1486                    // userData, then we could use this instance to
1487                    // fill 'ci' in. The same routine could be used in
1488                    // PhoneUtils.
1489                    if (0 == ci.numberPresentation) {
1490                        ci.numberPresentation = conn.getNumberPresentation();
1491                    }
1492                } else {
1493                    CallerInfo newCi = getCallerInfo(null, conn);
1494                    if (newCi != null) {
1495                        newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1496                        ci = newCi;
1497                    }
1498                }
1499                conn.setUserData(ci);
1500            }
1501        };
1502
1503
1504    /**
1505     * Returns a single "name" for the specified given a CallerInfo object.
1506     * If the name is null, return defaultString as the default value, usually
1507     * context.getString(R.string.unknown).
1508     */
1509    static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1510        if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1511
1512        String compactName = null;
1513        if (ci != null) {
1514            if (TextUtils.isEmpty(ci.name)) {
1515                // Perform any modifications for special CNAP cases to
1516                // the phone number being displayed, if applicable.
1517                compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1518                                                        ci.numberPresentation);
1519            } else {
1520                // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1521                compactName = ci.name;
1522            }
1523        }
1524
1525        if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1526            // If we're still null/empty here, then check if we have a presentation
1527            // string that takes precedence that we could return, otherwise display
1528            // "unknown" string.
1529            if (ci != null && ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) {
1530                compactName = context.getString(R.string.private_num);
1531            } else if (ci != null && ci.numberPresentation == Connection.PRESENTATION_PAYPHONE) {
1532                compactName = context.getString(R.string.payphone);
1533            } else {
1534                compactName = context.getString(R.string.unknown);
1535            }
1536        }
1537        if (DBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1538        return compactName;
1539    }
1540
1541    /**
1542     * Returns true if the specified Call is a "conference call", meaning
1543     * that it owns more than one Connection object.  This information is
1544     * used to trigger certain UI changes that appear when a conference
1545     * call is active (like displaying the label "Conference call", and
1546     * enabling the "Manage conference" UI.)
1547     *
1548     * Watch out: This method simply checks the number of Connections,
1549     * *not* their states.  So if a Call has (for example) one ACTIVE
1550     * connection and one DISCONNECTED connection, this method will return
1551     * true (which is unintuitive, since the Call isn't *really* a
1552     * conference call any more.)
1553     *
1554     * @return true if the specified call has more than one connection (in any state.)
1555     */
1556    static boolean isConferenceCall(Call call) {
1557        // CDMA phones don't have the same concept of "conference call" as
1558        // GSM phones do; there's no special "conference call" state of
1559        // the UI or a "manage conference" function.  (Instead, when
1560        // you're in a 3-way call, all we can do is display the "generic"
1561        // state of the UI.)  So as far as the in-call UI is concerned,
1562        // Conference corresponds to generic display.
1563        PhoneApp app = PhoneApp.getInstance();
1564        int phoneType = call.getPhone().getPhoneType();
1565        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1566            CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
1567            if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
1568                    || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1569                    && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
1570                return true;
1571            }
1572        } else {
1573            List<Connection> connections = call.getConnections();
1574            if (connections != null && connections.size() > 1) {
1575                return true;
1576            }
1577        }
1578        return false;
1579
1580        // TODO: We may still want to change the semantics of this method
1581        // to say that a given call is only really a conference call if
1582        // the number of ACTIVE connections, not the total number of
1583        // connections, is greater than one.  (See warning comment in the
1584        // javadoc above.)
1585        // Here's an implementation of that:
1586        //        if (connections == null) {
1587        //            return false;
1588        //        }
1589        //        int numActiveConnections = 0;
1590        //        for (Connection conn : connections) {
1591        //            if (DBG) log("  - CONN: " + conn + ", state = " + conn.getState());
1592        //            if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1593        //            if (numActiveConnections > 1) {
1594        //                return true;
1595        //            }
1596        //        }
1597        //        return false;
1598    }
1599
1600    /**
1601     * Launch the Dialer to start a new call.
1602     * This is just a wrapper around the ACTION_DIAL intent.
1603     */
1604    static void startNewCall(final CallManager cm) {
1605        // Sanity-check that this is OK given the current state of the phone.
1606        if (!okToAddCall(cm)) {
1607            Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1608            dumpCallManager();
1609            return;
1610        }
1611
1612        // if applicable, mute the call while we're showing the add call UI.
1613        if (cm.hasActiveFgCall()) {
1614            setMuteInternal(cm.getActiveFgCall().getPhone(), true);
1615            // Inform the phone app that this mute state was NOT done
1616            // voluntarily by the User.
1617            PhoneApp.getInstance().setRestoreMuteOnInCallResume(true);
1618        }
1619
1620        Intent intent = new Intent(Intent.ACTION_DIAL);
1621        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1622
1623        // when we request the dialer come up, we also want to inform
1624        // it that we're going through the "add call" option from the
1625        // InCallScreen / PhoneUtils.
1626        intent.putExtra(ADD_CALL_MODE_KEY, true);
1627
1628        PhoneApp.getInstance().startActivity(intent);
1629    }
1630
1631    static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1632        if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
1633        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1634
1635        audioManager.setSpeakerphoneOn(flag);
1636        // record the speaker-enable value
1637        if (store) {
1638            sIsSpeakerEnabled = flag;
1639        }
1640        if (flag) {
1641            NotificationMgr.getDefault().notifySpeakerphone();
1642        } else {
1643            NotificationMgr.getDefault().cancelSpeakerphone();
1644        }
1645
1646        // We also need to make a fresh call to PhoneApp.updateWakeState()
1647        // any time the speaker state changes, since the screen timeout is
1648        // sometimes different depending on whether or not the speaker is
1649        // in use.
1650        PhoneApp app = PhoneApp.getInstance();
1651        app.updateWakeState();
1652
1653        // Update the Proximity sensor based on speaker state
1654        app.updateProximitySensorMode(app.phone.getState());
1655    }
1656
1657    /**
1658     * Restore the speaker mode, called after a wired headset disconnect
1659     * event.
1660     */
1661    static void restoreSpeakerMode(Context context) {
1662        if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1663
1664        // change the mode if needed.
1665        if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1666            turnOnSpeaker(context, sIsSpeakerEnabled, false);
1667        }
1668    }
1669
1670    static boolean isSpeakerOn(Context context) {
1671        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1672        return audioManager.isSpeakerphoneOn();
1673    }
1674
1675
1676    static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) {
1677        if (DBG) log("turnOnNoiseSuppression: " + flag);
1678        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1679
1680        if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1681            return;
1682        }
1683
1684        if (flag) {
1685            audioManager.setParameters("noise_suppression=auto");
1686        } else {
1687            audioManager.setParameters("noise_suppression=off");
1688        }
1689
1690        // record the speaker-enable value
1691        if (store) {
1692            sIsNoiseSuppressionEnabled = flag;
1693        }
1694
1695        // TODO: implement and manage ICON
1696
1697    }
1698
1699    static void restoreNoiseSuppression(Context context) {
1700        if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled);
1701
1702        if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1703            return;
1704        }
1705
1706        // change the mode if needed.
1707        if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) {
1708            turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false);
1709        }
1710    }
1711
1712    static boolean isNoiseSuppressionOn(Context context) {
1713
1714        if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1715            return false;
1716        }
1717
1718        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1719        String noiseSuppression = audioManager.getParameters("noise_suppression");
1720        if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression);
1721        if (noiseSuppression.contains("off")) {
1722            return false;
1723        } else {
1724            return true;
1725        }
1726    }
1727
1728    /**
1729     *
1730     * Mute / umute the foreground phone, which has the current foreground call
1731     *
1732     * All muting / unmuting from the in-call UI should go through this
1733     * wrapper.
1734     *
1735     * Wrapper around Phone.setMute() and setMicrophoneMute().
1736     * It also updates the connectionMuteTable and mute icon in the status bar.
1737     *
1738     */
1739    static void setMute(boolean muted) {
1740        CallManager cm = PhoneApp.getInstance().mCM;
1741
1742        // make the call to mute the audio
1743        setMuteInternal(cm.getFgPhone(), muted);
1744
1745
1746        // update the foreground connections to match.  This includes
1747        // all the connections on conference calls.
1748        for (Connection cn : cm.getActiveFgCall().getConnections()) {
1749            if (sConnectionMuteTable.get(cn) == null) {
1750                if (DBG) log("problem retrieving mute value for this connection.");
1751            }
1752            sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
1753        }
1754    }
1755
1756    /**
1757     * Internally used muting function.
1758     */
1759    private static void setMuteInternal(Phone phone, boolean muted) {
1760        if (DBG) log("setMuteInternal: " + muted);
1761        Context context = phone.getContext();
1762        boolean routeToAudioManager =
1763            context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
1764        if (routeToAudioManager) {
1765            AudioManager audioManager =
1766                (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE);
1767            if (DBG) log("setMicrophoneMute: " + muted);
1768            audioManager.setMicrophoneMute(muted);
1769        } else {
1770            phone.setMute(muted);
1771        }
1772        NotificationMgr.getDefault().updateMuteNotification();
1773    }
1774
1775    /**
1776     * Get the mute state of foreground phone, which has the current
1777     * foreground call
1778     */
1779    static boolean getMute() {
1780        Phone phone = PhoneApp.getInstance().mCM.getFgPhone();
1781
1782        Context context = phone.getContext();
1783        boolean routeToAudioManager =
1784            context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
1785        if (routeToAudioManager) {
1786            AudioManager audioManager =
1787                (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE);
1788            return audioManager.isMicrophoneMute();
1789        } else {
1790            return phone.getMute();
1791        }
1792    }
1793
1794    /* package */ static void setAudioMode() {
1795        setAudioMode(PhoneApp.getInstance().mCM);
1796    }
1797
1798    /**
1799     * Sets the audio mode per current phone state.
1800     */
1801    /* package */ static void setAudioMode(CallManager cm) {
1802        if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState());
1803
1804        Context context = PhoneApp.getInstance();
1805        AudioManager audioManager = (AudioManager)
1806                context.getSystemService(Context.AUDIO_SERVICE);
1807        int modeBefore = audioManager.getMode();
1808        cm.setAudioMode();
1809        int modeAfter = audioManager.getMode();
1810
1811        if (modeBefore != modeAfter) {
1812            // Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
1813            if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
1814        } else {
1815            if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: "
1816                    + audioModeToString(modeBefore));
1817        }
1818    }
1819    private static String audioModeToString(int mode) {
1820        switch (mode) {
1821            case AudioManager.MODE_INVALID: return "MODE_INVALID";
1822            case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
1823            case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
1824            case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
1825            case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
1826            default: return String.valueOf(mode);
1827        }
1828    }
1829
1830    /**
1831     * Handles the wired headset button while in-call.
1832     *
1833     * This is called from the PhoneApp, not from the InCallScreen,
1834     * since the HEADSETHOOK button means "mute or unmute the current
1835     * call" *any* time a call is active, even if the user isn't actually
1836     * on the in-call screen.
1837     *
1838     * @return true if we consumed the event.
1839     */
1840    /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) {
1841        if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount());
1842
1843        // If the phone is totally idle, we ignore HEADSETHOOK events
1844        // (and instead let them fall through to the media player.)
1845        if (phone.getState() == Phone.State.IDLE) {
1846            return false;
1847        }
1848
1849        // Ok, the phone is in use.
1850        // The headset button button means "Answer" if an incoming call is
1851        // ringing.  If not, it toggles the mute / unmute state.
1852        //
1853        // And in any case we *always* consume this event; this means
1854        // that the usual mediaplayer-related behavior of the headset
1855        // button will NEVER happen while the user is on a call.
1856
1857        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1858        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1859        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1860
1861        if (hasRingingCall &&
1862            event.getRepeatCount() == 0 &&
1863            event.getAction() == KeyEvent.ACTION_UP) {
1864            // If an incoming call is ringing, answer it (just like with the
1865            // CALL button):
1866            int phoneType = phone.getPhoneType();
1867            if (phoneType == Phone.PHONE_TYPE_CDMA) {
1868                answerCall(phone.getRingingCall());
1869            } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1870                if (hasActiveCall && hasHoldingCall) {
1871                    if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
1872                    answerAndEndActive(PhoneApp.getInstance().mCM, phone.getRingingCall());
1873                } else {
1874                    if (DBG) log("handleHeadsetHook: ringing ==> answer!");
1875                    answerCall(phone.getRingingCall());  // Automatically holds the current active call,
1876                                        // if there is one
1877                }
1878            } else {
1879                throw new IllegalStateException("Unexpected phone type: " + phoneType);
1880            }
1881        } else {
1882            // No incoming ringing call.
1883            if (event.isLongPress()) {
1884                if (DBG) log("handleHeadsetHook: longpress -> hangup");
1885                hangup(phone.getRingingCall());
1886            }
1887            else if (event.getAction() == KeyEvent.ACTION_UP &&
1888                     event.getRepeatCount() == 0) {
1889                Connection c = phone.getForegroundCall().getLatestConnection();
1890                // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook.
1891                if (c != null && !PhoneNumberUtils.isEmergencyNumber(c.getAddress())) {
1892                    if (getMute()) {
1893                        if (DBG) log("handleHeadsetHook: UNmuting...");
1894                        setMute(false);
1895                    } else {
1896                        if (DBG) log("handleHeadsetHook: muting...");
1897                        setMute(true);
1898                    }
1899                }
1900            }
1901        }
1902
1903        // Even if the InCallScreen is the current activity, there's no
1904        // need to force it to update, because (1) if we answered a
1905        // ringing call, the InCallScreen will imminently get a phone
1906        // state change event (causing an update), and (2) if we muted or
1907        // unmuted, the setMute() call automagically updates the status
1908        // bar, and there's no "mute" indication in the InCallScreen
1909        // itself (other than the menu item, which only ever stays
1910        // onscreen for a second anyway.)
1911        // TODO: (2) isn't entirely true anymore. Once we return our result
1912        // to the PhoneApp, we ask InCallScreen to update its control widgets
1913        // in case we changed mute or speaker state and phones with touch-
1914        // screen [toggle] buttons need to update themselves.
1915
1916        return true;
1917    }
1918
1919    /**
1920     * Look for ANY connections on the phone that qualify as being
1921     * disconnected.
1922     *
1923     * @return true if we find a connection that is disconnected over
1924     * all the phone's call objects.
1925     */
1926    /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1927        return hasDisconnectedConnections(phone.getForegroundCall()) ||
1928                hasDisconnectedConnections(phone.getBackgroundCall()) ||
1929                hasDisconnectedConnections(phone.getRingingCall());
1930    }
1931
1932    /**
1933     * Iterate over all connections in a call to see if there are any
1934     * that are not alive (disconnected or idle).
1935     *
1936     * @return true if we find a connection that is disconnected, and
1937     * pending removal via
1938     * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
1939     */
1940    private static final boolean hasDisconnectedConnections(Call call) {
1941        // look through all connections for non-active ones.
1942        for (Connection c : call.getConnections()) {
1943            if (!c.isAlive()) {
1944                return true;
1945            }
1946        }
1947        return false;
1948    }
1949
1950    //
1951    // Misc UI policy helper functions
1952    //
1953
1954    /**
1955     * @return true if we're allowed to swap calls, given the current
1956     * state of the Phone.
1957     */
1958    /* package */ static boolean okToSwapCalls(CallManager cm) {
1959        int phoneType = cm.getDefaultPhone().getPhoneType();
1960        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1961            // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
1962            // state by either accepting a Call Waiting or by merging two calls
1963            PhoneApp app = PhoneApp.getInstance();
1964            return (app.cdmaPhoneCallState.getCurrentCallState()
1965                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
1966        } else if (phoneType == Phone.PHONE_TYPE_GSM ||
1967                phoneType == Phone.PHONE_TYPE_SIP) {
1968            // GSM: "Swap" is available if both lines are in use and there's no
1969            // incoming call.  (Actually we need to verify that the active
1970            // call really is in the ACTIVE state and the holding call really
1971            // is in the HOLDING state, since you *can't* actually swap calls
1972            // when the foreground call is DIALING or ALERTING.)
1973            return !cm.hasActiveRingingCall()
1974                    && (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
1975                    && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
1976        } else {
1977            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1978        }
1979    }
1980
1981    /**
1982     * @return true if we're allowed to merge calls, given the current
1983     * state of the Phone.
1984     */
1985    /* package */ static boolean okToMergeCalls(CallManager cm) {
1986        int phoneType = cm.getFgPhone().getPhoneType();
1987        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1988            // CDMA: "Merge" is enabled only when the user is in a 3Way call.
1989            PhoneApp app = PhoneApp.getInstance();
1990            return ((app.cdmaPhoneCallState.getCurrentCallState()
1991                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1992                    && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
1993        } else {
1994            // GSM: "Merge" is available if both lines are in use and there's no
1995            // incoming call, *and* the current conference isn't already
1996            // "full".
1997            // TODO: shall move all okToMerge logic to CallManager
1998            return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
1999                    && cm.hasActiveBgCall()
2000                    && cm.canConference(cm.getFirstActiveBgCall());
2001        }
2002    }
2003
2004    /**
2005     * @return true if the UI should let you add a new call, given the current
2006     * state of the Phone.
2007     */
2008    /* package */ static boolean okToAddCall(CallManager cm) {
2009        Phone phone = cm.getActiveFgCall().getPhone();
2010
2011        int phoneType = phone.getPhoneType();
2012        final Call.State fgCallState = cm.getActiveFgCall().getState();
2013        if (phoneType == Phone.PHONE_TYPE_CDMA) {
2014           // CDMA: "Add call" menu item is only enabled when the call is in
2015           // - ForegroundCall is in ACTIVE state
2016           // - After 30 seconds of user Ignoring/Missing a Call Waiting call.
2017            PhoneApp app = PhoneApp.getInstance();
2018            return ((fgCallState == Call.State.ACTIVE)
2019                    && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
2020        } else if (phoneType == Phone.PHONE_TYPE_GSM
2021                || phoneType == Phone.PHONE_TYPE_SIP) {
2022            // GSM: "Add call" is available only if ALL of the following are true:
2023            // - There's no incoming ringing call
2024            // - There's < 2 lines in use
2025            // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
2026            //   (We mainly need to make sure it *isn't* DIALING or ALERTING.)
2027            final boolean hasRingingCall = cm.hasActiveRingingCall();
2028            final boolean hasActiveCall = cm.hasActiveFgCall();
2029            final boolean hasHoldingCall = cm.hasActiveBgCall();
2030            final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2031
2032            return !hasRingingCall
2033                    && !allLinesTaken
2034                    && ((fgCallState == Call.State.ACTIVE)
2035                        || (fgCallState == Call.State.IDLE)
2036                        || (fgCallState == Call.State.DISCONNECTED));
2037        } else {
2038            throw new IllegalStateException("Unexpected phone type: " + phoneType);
2039        }
2040    }
2041
2042    /**
2043     * Based on the input CNAP number string,
2044     * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
2045     * Otherwise, return CNAP_SPECIAL_CASE_NO.
2046     */
2047    private static int checkCnapSpecialCases(String n) {
2048        if (n.equals("PRIVATE") ||
2049                n.equals("P") ||
2050                n.equals("RES")) {
2051            if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
2052            return Connection.PRESENTATION_RESTRICTED;
2053        } else if (n.equals("UNAVAILABLE") ||
2054                n.equals("UNKNOWN") ||
2055                n.equals("UNA") ||
2056                n.equals("U")) {
2057            if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
2058            return Connection.PRESENTATION_UNKNOWN;
2059        } else {
2060            if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
2061            return CNAP_SPECIAL_CASE_NO;
2062        }
2063    }
2064
2065    /**
2066     * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
2067     * from the network to indicate different number presentations, convert them to
2068     * expected number and presentation values within the CallerInfo object.
2069     * @param number number we use to verify if we are in a corner case
2070     * @param presentation presentation value used to verify if we are in a corner case
2071     * @return the new String that should be used for the phone number
2072     */
2073    /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
2074            String number, int presentation) {
2075        // Obviously we return number if ci == null, but still return number if
2076        // number == null, because in these cases the correct string will still be
2077        // displayed/logged after this function returns based on the presentation value.
2078        if (ci == null || number == null) return number;
2079
2080        if (DBG) log("modifyForSpecialCnapCases: initially, number=" + number
2081                + ", presentation=" + presentation + " ci " + ci);
2082
2083        // "ABSENT NUMBER" is a possible value we could get from the network as the
2084        // phone number, so if this happens, change it to "Unknown" in the CallerInfo
2085        // and fix the presentation to be the same.
2086        if (number.equals(context.getString(R.string.absent_num))
2087                && presentation == Connection.PRESENTATION_ALLOWED) {
2088            number = context.getString(R.string.unknown);
2089            ci.numberPresentation = Connection.PRESENTATION_UNKNOWN;
2090        }
2091
2092        // Check for other special "corner cases" for CNAP and fix them similarly. Corner
2093        // cases only apply if we received an allowed presentation from the network, so check
2094        // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
2095        // match the presentation passed in for verification (meaning we changed it previously
2096        // because it's a corner case and we're being called from a different entry point).
2097        if (ci.numberPresentation == Connection.PRESENTATION_ALLOWED
2098                || (ci.numberPresentation != presentation
2099                        && presentation == Connection.PRESENTATION_ALLOWED)) {
2100            int cnapSpecialCase = checkCnapSpecialCases(number);
2101            if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
2102                // For all special strings, change number & numberPresentation.
2103                if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) {
2104                    number = context.getString(R.string.private_num);
2105                } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) {
2106                    number = context.getString(R.string.unknown);
2107                }
2108                if (DBG) log("SpecialCnap: number=" + number
2109                        + "; presentation now=" + cnapSpecialCase);
2110                ci.numberPresentation = cnapSpecialCase;
2111            }
2112        }
2113        if (DBG) log("modifyForSpecialCnapCases: returning number string=" + number);
2114        return number;
2115    }
2116
2117    //
2118    // Support for 3rd party phone service providers.
2119    //
2120
2121    /**
2122     * Check if all the provider's info is present in the intent.
2123     * @param intent Expected to have the provider's extra.
2124     * @return true if the intent has all the extras to build the
2125     * in-call screen's provider info overlay.
2126     */
2127    /* package */ static boolean hasPhoneProviderExtras(Intent intent) {
2128        if (null == intent) {
2129            return false;
2130        }
2131        final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2132        final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
2133
2134        return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri);
2135    }
2136
2137    /**
2138     * Copy all the expected extras set when a 3rd party provider is
2139     * used from the source intent to the destination one.  Checks all
2140     * the required extras are present, if any is missing, none will
2141     * be copied.
2142     * @param src Intent which may contain the provider's extras.
2143     * @param dst Intent where a copy of the extras will be added if applicable.
2144     */
2145    /* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) {
2146        if (!hasPhoneProviderExtras(src)) {
2147            Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing.");
2148            return;
2149        }
2150
2151        dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE,
2152                     src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE));
2153        dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI,
2154                     src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI));
2155    }
2156
2157    /**
2158     * Get the provider's label from the intent.
2159     * @param context to lookup the provider's package name.
2160     * @param intent with an extra set to the provider's package name.
2161     * @return The provider's application label. null if an error
2162     * occurred during the lookup of the package name or the label.
2163     */
2164    /* package */ static CharSequence getProviderLabel(Context context, Intent intent) {
2165        String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2166        PackageManager pm = context.getPackageManager();
2167
2168        try {
2169            ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
2170
2171            return pm.getApplicationLabel(info);
2172        } catch (PackageManager.NameNotFoundException e) {
2173            return null;
2174        }
2175    }
2176
2177    /**
2178     * Get the provider's icon.
2179     * @param context to lookup the provider's icon.
2180     * @param intent with an extra set to the provider's package name.
2181     * @return The provider's application icon. null if an error occured during the icon lookup.
2182     */
2183    /* package */ static Drawable getProviderIcon(Context context, Intent intent) {
2184        String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2185        PackageManager pm = context.getPackageManager();
2186
2187        try {
2188            return pm.getApplicationIcon(packageName);
2189        } catch (PackageManager.NameNotFoundException e) {
2190            return null;
2191        }
2192    }
2193
2194    /**
2195     * Return the gateway uri from the intent.
2196     * @param intent With the gateway uri extra.
2197     * @return The gateway URI or null if not found.
2198     */
2199    /* package */ static Uri getProviderGatewayUri(Intent intent) {
2200        String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
2201        return TextUtils.isEmpty(uri) ? null : Uri.parse(uri);
2202    }
2203
2204    /**
2205     * Return a formatted version of the uri's scheme specific
2206     * part. E.g for 'tel:12345678', return '1-234-5678'.
2207     * @param uri A 'tel:' URI with the gateway phone number.
2208     * @return the provider's address (from the gateway uri) formatted
2209     * for user display. null if uri was null or its scheme was not 'tel:'.
2210     */
2211    /* package */ static String formatProviderUri(Uri uri) {
2212        if (null != uri) {
2213            if ("tel".equals(uri.getScheme())) {
2214                return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart());
2215            } else {
2216                return uri.toString();
2217            }
2218        }
2219        return null;
2220    }
2221
2222    /**
2223     * Check if a phone number can be route through a 3rd party
2224     * gateway. The number must be a global phone number in numerical
2225     * form (1-800-666-SEXY won't work).
2226     *
2227     * MMI codes and the like cannot be used as a dial number for the
2228     * gateway either.
2229     *
2230     * @param number To be dialed via a 3rd party gateway.
2231     * @return true If the number can be routed through the 3rd party network.
2232     */
2233    /* package */ static boolean isRoutableViaGateway(String number) {
2234        if (TextUtils.isEmpty(number)) {
2235            return false;
2236        }
2237        number = PhoneNumberUtils.stripSeparators(number);
2238        if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
2239            return false;
2240        }
2241        number = PhoneNumberUtils.extractNetworkPortion(number);
2242        return PhoneNumberUtils.isGlobalPhoneNumber(number);
2243    }
2244
2245   /**
2246    * This function is called when phone answers or places a call.
2247    * Check if the phone is in a car dock or desk dock.
2248    * If yes, turn on the speaker, when no wired or BT headsets are connected.
2249    * Otherwise do nothing.
2250    */
2251    private static void activateSpeakerIfDocked(Phone phone) {
2252        if (DBG) log("activateSpeakerIfDocked()...");
2253
2254        if (PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_DESK ||
2255                PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_CAR) {
2256            if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
2257            PhoneApp app = PhoneApp.getInstance();
2258            BluetoothHandsfree bthf = app.getBluetoothHandsfree();
2259
2260            if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) {
2261                turnOnSpeaker(phone.getContext(), true, true);
2262            }
2263        }
2264    }
2265
2266
2267    /**
2268     * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
2269     */
2270    /* package */ static boolean isPhoneInEcm(Phone phone) {
2271        if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
2272            // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true".
2273            // TODO: There ought to be a better API for this than just
2274            // exposing a system property all the way up to the app layer,
2275            // probably a method like "inEcm()" provided by the telephony
2276            // layer.
2277            String ecmMode =
2278                    SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
2279            if (ecmMode != null) {
2280                return ecmMode.equals("true");
2281            }
2282        }
2283        return false;
2284    }
2285
2286    /**
2287     * Returns the most appropriate Phone object to handle a call
2288     * to the specified number.
2289     *
2290     * @param cm the CallManager.
2291     * @param scheme the scheme from the data URI that the number originally came from.
2292     * @param number the phone number, or SIP address.
2293     */
2294    public static Phone pickPhoneBasedOnNumber(CallManager cm,
2295            String scheme, String number, String primarySipUri) {
2296        if (DBG) log("pickPhoneBasedOnNumber: scheme " + scheme
2297                + ", number " + number + ", sipUri " + primarySipUri);
2298
2299        if (primarySipUri != null) {
2300            Phone phone = getSipPhoneFromUri(cm, primarySipUri);
2301            if (phone != null) return phone;
2302        }
2303        return cm.getDefaultPhone();
2304    }
2305
2306    public static Phone getSipPhoneFromUri(CallManager cm, String target) {
2307        for (Object obj : cm.getAllPhones()) {
2308            if (obj instanceof SipPhone) {
2309                String sipUri = ((SipPhone)obj).getSipUri();
2310                if (target.equals(sipUri)) {
2311                    if (DBG) log("- pickPhoneBasedOnNumber:" +
2312                            "found SipPhone! obj = " + obj + ", "
2313                            + obj.getClass());
2314                    return (Phone)obj;
2315                }
2316            }
2317        }
2318        return null;
2319    }
2320    public static boolean isRealIncomingCall(Call.State state) {
2321        return (state == Call.State.INCOMING && !PhoneApp.getInstance().mCM.hasActiveFgCall());
2322
2323    }
2324
2325    //
2326    // General phone and call state debugging/testing code
2327    //
2328
2329    /* package */ static void dumpCallState(Phone phone) {
2330        PhoneApp app = PhoneApp.getInstance();
2331        Log.d(LOG_TAG, "dumpCallState():");
2332        Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
2333              + ", state = " + phone.getState());
2334
2335        StringBuilder b = new StringBuilder(128);
2336
2337        Call call = phone.getForegroundCall();
2338        b.setLength(0);
2339        b.append("  - FG call: ").append(call.getState());
2340        b.append(" isAlive ").append(call.getState().isAlive());
2341        b.append(" isRinging ").append(call.getState().isRinging());
2342        b.append(" isDialing ").append(call.getState().isDialing());
2343        b.append(" isIdle ").append(call.isIdle());
2344        b.append(" hasConnections ").append(call.hasConnections());
2345        Log.d(LOG_TAG, b.toString());
2346
2347        call = phone.getBackgroundCall();
2348        b.setLength(0);
2349        b.append("  - BG call: ").append(call.getState());
2350        b.append(" isAlive ").append(call.getState().isAlive());
2351        b.append(" isRinging ").append(call.getState().isRinging());
2352        b.append(" isDialing ").append(call.getState().isDialing());
2353        b.append(" isIdle ").append(call.isIdle());
2354        b.append(" hasConnections ").append(call.hasConnections());
2355        Log.d(LOG_TAG, b.toString());
2356
2357        call = phone.getRingingCall();
2358        b.setLength(0);
2359        b.append("  - RINGING call: ").append(call.getState());
2360        b.append(" isAlive ").append(call.getState().isAlive());
2361        b.append(" isRinging ").append(call.getState().isRinging());
2362        b.append(" isDialing ").append(call.getState().isDialing());
2363        b.append(" isIdle ").append(call.isIdle());
2364        b.append(" hasConnections ").append(call.hasConnections());
2365        Log.d(LOG_TAG, b.toString());
2366
2367
2368        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2369        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2370        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2371        final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2372        b.setLength(0);
2373        b.append("  - hasRingingCall ").append(hasRingingCall);
2374        b.append(" hasActiveCall ").append(hasActiveCall);
2375        b.append(" hasHoldingCall ").append(hasHoldingCall);
2376        b.append(" allLinesTaken ").append(allLinesTaken);
2377        Log.d(LOG_TAG, b.toString());
2378
2379        // On CDMA phones, dump out the CdmaPhoneCallState too:
2380        if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
2381            if (app.cdmaPhoneCallState != null) {
2382                Log.d(LOG_TAG, "  - CDMA call state: "
2383                      + app.cdmaPhoneCallState.getCurrentCallState());
2384            } else {
2385                Log.d(LOG_TAG, "  - CDMA device, but null cdmaPhoneCallState!");
2386            }
2387        }
2388
2389        // Watch out: the isRinging() call below does NOT tell us anything
2390        // about the state of the telephony layer; it merely tells us whether
2391        // the Ringer manager is currently playing the ringtone.
2392        boolean ringing = app.getRinger().isRinging();
2393        Log.d(LOG_TAG, "  - Ringer state: " + ringing);
2394    }
2395
2396    private static void log(String msg) {
2397        Log.d(LOG_TAG, msg);
2398    }
2399
2400    static void dumpCallManager() {
2401        Call call;
2402        CallManager cm = PhoneApp.getInstance().mCM;
2403        StringBuilder b = new StringBuilder(128);
2404
2405        Log.d(LOG_TAG, "############### dumpCallManager() ##############");
2406        Log.d(LOG_TAG, "CallManager: " + cm
2407                + ", state = " + cm.getState());
2408        b.setLength(0);
2409        call = cm.getActiveFgCall();
2410        b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
2411        b.append(call);
2412        b.append( "  State: ").append(cm.getActiveFgCallState());
2413        b.append( "  Conn: ").append(cm.getFgCallConnections());
2414        Log.d(LOG_TAG, b.toString());
2415        b.setLength(0);
2416        call = cm.getFirstActiveBgCall();
2417        b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
2418        b.append(call);
2419        b.append( "  State: ").append(cm.getFirstActiveBgCall().getState());
2420        b.append( "  Conn: ").append(cm.getBgCallConnections());
2421        Log.d(LOG_TAG, b.toString());
2422        b.setLength(0);
2423        call = cm.getFirstActiveRingingCall();
2424        b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
2425        b.append(call);
2426        b.append( "  State: ").append(cm.getFirstActiveRingingCall().getState());
2427        Log.d(LOG_TAG, b.toString());
2428
2429
2430
2431        for (Phone phone : CallManager.getInstance().getAllPhones()) {
2432            if (phone != null) {
2433                Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
2434                        + ", state = " + phone.getState());
2435                b.setLength(0);
2436                call = phone.getForegroundCall();
2437                b.append(" - FG call: ").append(call);
2438                b.append( "  State: ").append(call.getState());
2439                b.append( "  Conn: ").append(call.hasConnections());
2440                Log.d(LOG_TAG, b.toString());
2441                b.setLength(0);
2442                call = phone.getBackgroundCall();
2443                b.append(" - BG call: ").append(call);
2444                b.append( "  State: ").append(call.getState());
2445                b.append( "  Conn: ").append(call.hasConnections());
2446                Log.d(LOG_TAG, b.toString());b.setLength(0);
2447                call = phone.getRingingCall();
2448                b.append(" - RINGING call: ").append(call);
2449                b.append( "  State: ").append(call.getState());
2450                b.append( "  Conn: ").append(call.hasConnections());
2451                Log.d(LOG_TAG, b.toString());
2452            }
2453        }
2454
2455        Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
2456    }
2457
2458}
2459