PhoneUtils.java revision d3744ff481f7d96669740b015a39d7441208152b
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.ActivityManagerNative;
20import android.app.AlertDialog;
21import android.app.Dialog;
22import android.app.KeyguardManager;
23import android.app.ProgressDialog;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
28import android.content.ServiceConnection;
29import android.media.AudioManager;
30import android.net.Uri;
31import android.os.AsyncResult;
32import android.os.Handler;
33import android.os.IBinder;
34import android.os.Message;
35import android.os.RemoteException;
36import android.provider.Contacts;
37import android.telephony.PhoneNumberUtils;
38import android.text.TextUtils;
39import android.util.Log;
40import android.view.KeyEvent;
41import android.view.LayoutInflater;
42import android.view.View;
43import android.view.WindowManager;
44import android.widget.EditText;
45import android.widget.Toast;
46
47import com.android.internal.telephony.Call;
48import com.android.internal.telephony.CallStateException;
49import com.android.internal.telephony.CallerInfo;
50import com.android.internal.telephony.CallerInfoAsyncQuery;
51import com.android.internal.telephony.Connection;
52import com.android.internal.telephony.IExtendedNetworkService;
53import com.android.internal.telephony.MmiCode;
54import com.android.internal.telephony.Phone;
55import com.android.internal.telephony.PhoneFactory;
56
57import java.util.Hashtable;
58import java.util.Iterator;
59import java.util.List;
60
61/**
62 * Misc utilities for the Phone app.
63 */
64public class PhoneUtils {
65    private static final String LOG_TAG = "PhoneUtils";
66    private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2);
67
68    /** Control stack trace for Audio Mode settings */
69    private static final boolean DBG_SETAUDIOMODE_STACK = false;
70
71    /** Identifier for the "Add Call" intent extra. */
72    static final String ADD_CALL_MODE_KEY = "add_call_mode";
73
74    // Return codes from placeCall()
75    static final int CALL_STATUS_DIALED = 0;  // The number was successfully dialed
76    static final int CALL_STATUS_DIALED_MMI = 1;  // The specified number was an MMI code
77    static final int CALL_STATUS_FAILED = 2;  // The call failed
78
79    // State of the Phone's audio modes
80    // Each state can move to the other states, but within the state only certain
81    //  transitions for AudioManager.setMode() are allowed.
82    static final int AUDIO_IDLE = 0;  /** audio behaviour at phone idle */
83    static final int AUDIO_RINGING = 1;  /** audio behaviour while ringing */
84    static final int AUDIO_OFFHOOK = 2;  /** audio behaviour while in call. */
85    private static int sAudioBehaviourState = AUDIO_IDLE;
86
87    /** Speaker state, persisting between wired headset connection events */
88    private static boolean sIsSpeakerEnabled = false;
89
90    /** Hash table to store mute (Boolean) values based upon the connection.*/
91    private static Hashtable<Connection, Boolean> sConnectionMuteTable =
92        new Hashtable<Connection, Boolean>();
93
94    /** Static handler for the connection/mute tracking */
95    private static ConnectionHandler mConnectionHandler;
96
97    /** Phone state changed event*/
98    private static final int PHONE_STATE_CHANGED = -1;
99
100    /** Define for not a special CNAP string */
101    private static final int CNAP_SPECIAL_CASE_NO = -1;
102
103    // Extended network service interface instance
104    private static IExtendedNetworkService mNwService = null;
105    // used to cancel MMI command after 15 seconds timeout for NWService requirement
106    private static Message mMmiTimeoutCbMsg = null;
107
108    /**
109     * Handler that tracks the connections and updates the value of the
110     * Mute settings for each connection as needed.
111     */
112    private static class ConnectionHandler extends Handler {
113        public void handleMessage(Message msg) {
114            AsyncResult ar = (AsyncResult) msg.obj;
115            switch (msg.what) {
116                case PHONE_STATE_CHANGED:
117                    if (DBG) log("ConnectionHandler: updating mute state for each connection");
118
119                    Phone phone = (Phone) ar.userObj;
120
121                    // update the foreground connections, if there are new connections.
122                    List<Connection> fgConnections = phone.getForegroundCall().getConnections();
123                    for (Connection cn : fgConnections) {
124                        if (sConnectionMuteTable.get(cn) == null) {
125                            sConnectionMuteTable.put(cn, Boolean.FALSE);
126                        }
127                    }
128
129                    // update the background connections, if there are new connections.
130                    List<Connection> bgConnections = phone.getBackgroundCall().getConnections();
131                    for (Connection cn : bgConnections) {
132                        if (sConnectionMuteTable.get(cn) == null) {
133                            sConnectionMuteTable.put(cn, Boolean.FALSE);
134                        }
135                    }
136
137                    // Check to see if there are any lingering connections here
138                    // (disconnected connections), use old-school iterators to avoid
139                    // concurrent modification exceptions.
140                    Connection cn;
141                    for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator();
142                            cnlist.hasNext();) {
143                        cn = cnlist.next();
144                        if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) {
145                            if (DBG) log("connection: " + cn + "not accounted for, removing.");
146                            cnlist.remove();
147                        }
148                    }
149
150                    // Restore the mute state of the foreground call if we're not IDLE,
151                    // otherwise just clear the mute state. This is really saying that
152                    // as long as there is one or more connections, we should update
153                    // the mute state with the earliest connection on the foreground
154                    // call, and that with no connections, we should be back to a
155                    // non-mute state.
156                    if (phone.getState() != Phone.State.IDLE) {
157                        restoreMuteState(phone);
158                    } else {
159                        setMuteInternal(phone, false);
160                    }
161
162                    break;
163            }
164        }
165    }
166
167
168    private static ServiceConnection ExtendedNetworkServiceConnection = new ServiceConnection() {
169        public void onServiceConnected(ComponentName name, IBinder iBinder) {
170            if (DBG) log("Extended NW onServiceConnected");
171            mNwService = IExtendedNetworkService.Stub.asInterface(iBinder);
172        }
173
174        public void onServiceDisconnected(ComponentName arg0) {
175            if (DBG) log("Extended NW onServiceDisconnected");
176            mNwService = null;
177        }
178    };
179
180    /**
181     * Register the ConnectionHandler with the phone, to receive connection events
182     */
183    public static void initializeConnectionHandler(Phone phone) {
184        if (mConnectionHandler == null) {
185            mConnectionHandler = new ConnectionHandler();
186        }
187
188        phone.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, phone);
189        // Extended NW service
190        Intent intent = new Intent("com.android.ussd.IExtendedNetworkService");
191        phone.getContext().bindService(intent,
192                ExtendedNetworkServiceConnection, Context.BIND_AUTO_CREATE);
193        if (DBG) log("Extended NW bindService IExtendedNetworkService");
194
195    }
196
197    /** This class is never instantiated. */
198    private PhoneUtils() {
199    }
200
201    //static method to set the audio control state.
202    static void setAudioControlState(int newState) {
203        sAudioBehaviourState = newState;
204    }
205
206    /**
207     * Answer the currently-ringing call.
208     *
209     * @return true if we answered the call, or false if there wasn't
210     *         actually a ringing incoming call, or some other error occurred.
211     *
212     * @see answerAndEndHolding()
213     * @see answerAndEndActive()
214     */
215    static boolean answerCall(Phone phone) {
216        if (DBG) log("answerCall()...");
217
218        // If the ringer is currently ringing and/or vibrating, stop it
219        // right now (before actually answering the call.)
220        PhoneApp.getInstance().getRinger().stopRing();
221
222        PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
223
224        boolean answered = false;
225        Call call = phone.getRingingCall();
226
227        if (phone.getPhoneName().equals("CDMA")) {
228            // Stop any signalInfo tone being played when a Call waiting gets answered
229            if (call.getState() == Call.State.WAITING) {
230                final CallNotifier notifier = PhoneApp.getInstance().notifier;
231                notifier.stopSignalInfoTone();
232            }
233        }
234
235        if (call != null && call.isRinging()) {
236            if (DBG) log("answerCall: call state = " + call.getState());
237            try {
238                //if (DBG) log("sPhone.acceptCall");
239                phone.acceptCall();
240                answered = true;
241                setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL);
242                if (phone.getPhoneName().equals("CDMA")) {
243                    PhoneApp app = PhoneApp.getInstance();
244                    if (app.cdmaPhoneCallState.getCurrentCallState()
245                            == CdmaPhoneCallState.PhoneCallState.IDLE) {
246                        // This is the FIRST incoming call being answered.
247                        // Set the Phone Call State to SINGLE_ACTIVE
248                        app.cdmaPhoneCallState.setCurrentCallState(
249                                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
250                    } else {
251                        // This is the CALL WAITING call being answered.
252                        // Set the Phone Call State to CONF_CALL
253                        app.cdmaPhoneCallState.setCurrentCallState(
254                                CdmaPhoneCallState.PhoneCallState.CONF_CALL);
255
256                        // If a BluetoothHandsfree is valid we need to set the second call state
257                        // so that the Bluetooth client can update the Call state correctly when
258                        // a call waiting is answered from the Phone.
259                        BluetoothHandsfree bthf = PhoneApp.getInstance().getBluetoothHandsfree();
260                        if (bthf != null) {
261                            bthf.cdmaSetSecondCallState(true);
262                        }
263                    }
264                }
265            } catch (CallStateException ex) {
266                Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
267            }
268        }
269        return answered;
270    }
271
272    /**
273     * Smart "hang up" helper method which hangs up exactly one connection,
274     * based on the current Phone state, as follows:
275     * <ul>
276     * <li>If there's a ringing call, hang that up.
277     * <li>Else if there's a foreground call, hang that up.
278     * <li>Else if there's a background call, hang that up.
279     * <li>Otherwise do nothing.
280     * </ul>
281     * @return true if we successfully hung up, or false
282     *              if there were no active calls at all.
283     */
284    static boolean hangup(Phone phone) {
285        boolean hungup = false;
286        Call ringing = phone.getRingingCall();
287        Call fg = phone.getForegroundCall();
288        Call bg = phone.getBackgroundCall();
289
290        if (!ringing.isIdle()) {
291            if (DBG) log("HANGUP ringing call");
292            hungup = hangupRingingCall(phone);
293        } else if (!fg.isIdle()) {
294            if (DBG) log("HANGUP foreground call");
295            hungup = hangup(fg);
296        } else if (!bg.isIdle()) {
297            if (DBG) log("HANGUP background call");
298            hungup = hangup(bg);
299        }
300
301        if (DBG) log("hungup=" + hungup);
302
303        return hungup;
304    }
305
306    static boolean hangupRingingCall(Phone phone) {
307        if (DBG) log("hangup ringing call");
308        Call ringing = phone.getRingingCall();
309
310        if (phone.getPhoneName().equals("CDMA")) {
311            // CDMA: Ringing call and Call waiting hangup is handled differently.
312            // For Call waiting we DO NOT call the conventional hangup(call) function
313            // as in CDMA we just want to hungup the Call waiting connection.
314            Call.State state = ringing.getState();
315            if (state == Call.State.INCOMING) {
316                if (DBG) log("hangup ringing call");
317                return hangup(ringing);
318            } else if (state == Call.State.WAITING) {
319                if (DBG) log("hangup Call waiting call");
320                final CallNotifier notifier = PhoneApp.getInstance().notifier;
321                notifier.onCdmaCallWaitingReject();
322                return true;
323            } else {
324                // This should never happen cause hangupRingingCall should always be called
325                // if the call.isRinging() returns TRUE, which basically means that the call
326                // should either be in INCOMING or WAITING state
327                if (DBG) log("No Ringing call to hangup");
328                return false;
329            }
330        } else {
331            // GSM:  Ringing Call and Call waiting, both are hungup by calling
332            // hangup(call) function.
333            if (DBG) log("hangup ringing call");
334            return hangup(ringing);
335        }
336    }
337
338    static boolean hangupActiveCall(Phone phone) {
339        if (DBG) log("hangup active call");
340        return hangup(phone.getForegroundCall());
341    }
342
343    static boolean hangupHoldingCall(Phone phone) {
344        if (DBG) log("hangup holding call");
345        return hangup(phone.getBackgroundCall());
346    }
347
348    /**
349     * Used in CDMA phones to end the complete Call session
350     * @param phone the Phone object.
351     * @return true if *any* call was successfully hung up
352     */
353    static boolean hangupRingingAndActive(Phone phone) {
354        boolean hungUpRingingCall = false;
355        boolean hungUpFgCall = false;
356        Call ringingCall = phone.getRingingCall();
357        Call fgCall = phone.getForegroundCall();
358
359        // Hang up any Ringing Call
360        if (!ringingCall.isIdle()) {
361            if (DBG) log("endCallInternal: Hang up Ringing Call");
362            hungUpRingingCall = hangupRingingCall(phone);
363        }
364
365        // Hang up any Active Call
366        if (!fgCall.isIdle()) {
367            if (DBG) log("endCallInternal: Hang up Foreground Call");
368            hungUpFgCall = hangupActiveCall(phone);
369        }
370
371        return hungUpRingingCall || hungUpFgCall;
372    }
373
374    /**
375     * Trivial wrapper around Call.hangup(), except that we return a
376     * boolean success code rather than throwing CallStateException on
377     * failure.
378     *
379     * @return true if the call was successfully hung up, or false
380     *         if the call wasn't actually active.
381     */
382    static boolean hangup(Call call) {
383        try {
384            call.hangup();
385            return true;
386        } catch (CallStateException ex) {
387            Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
388        }
389
390        return false;
391    }
392
393    /**
394     * Trivial wrapper around Connection.hangup(), except that we silently
395     * do nothing (rather than throwing CallStateException) if the
396     * connection wasn't actually active.
397     */
398    static void hangup(Connection c) {
399        try {
400            if (c != null) {
401                c.hangup();
402            }
403        } catch (CallStateException ex) {
404            Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
405        }
406    }
407
408    static boolean answerAndEndHolding(Phone phone) {
409        if (DBG) log("end holding & answer waiting: 1");
410        if (!hangupHoldingCall(phone)) {
411            Log.e(LOG_TAG, "end holding failed!");
412            return false;
413        }
414
415        if (DBG) log("end holding & answer waiting: 2");
416        return answerCall(phone);
417
418    }
419
420    static boolean answerAndEndActive(Phone phone) {
421        if (DBG) log("answerAndEndActive()...");
422
423        // Unlike the answerCall() method, we *don't* need to stop the
424        // ringer or change audio modes here since the user is already
425        // in-call, which means that the audio mode is already set
426        // correctly, and that we wouldn't have started the ringer in the
427        // first place.
428
429        // hanging up the active call also accepts the waiting call
430        return hangupActiveCall(phone);
431    }
432
433    /**
434     * Dial the number using the phone passed in.
435     *
436     * @param phone the Phone object.
437     * @param number the number to be dialed.
438     * @return either CALL_STATUS_DIALED, CALL_STATUS_DIALED_MMI, or CALL_STATUS_FAILED
439     */
440    static int placeCall(Phone phone, String number, Uri contactRef) {
441        int status = CALL_STATUS_DIALED;
442        try {
443            if (DBG) log("placeCall: '" + number + "'...");
444
445            Connection cn = phone.dial(number);
446            if (DBG) log("===> phone.dial() returned: " + cn);
447
448            // On GSM phones, null is returned for MMI codes
449            if (cn == null) {
450                if (phone.getPhoneName().equals("GSM")) {
451                    if (DBG) log("dialed MMI code: " + number);
452                    status = CALL_STATUS_DIALED_MMI;
453                    // Set dialed MMI command to service
454                    if (mNwService != null) {
455                        try {
456                            mNwService.setMmiString(number);
457                            if (DBG) log("Extended NW bindService setUssdString (" + number + ")");
458                        } catch (RemoteException e) {
459                            mNwService = null;
460                        }
461                    }
462                } else {
463                    status = PhoneUtils.CALL_STATUS_FAILED;
464                }
465            } else {
466                PhoneApp app = PhoneApp.getInstance();
467
468                if (phone.getPhoneName().equals("CDMA")) {
469                    if (app.cdmaPhoneCallState.getCurrentCallState()
470                            == CdmaPhoneCallState.PhoneCallState.IDLE) {
471                        // This is the first outgoing call. Set the Phone Call State to ACTIVE
472                        app.cdmaPhoneCallState.setCurrentCallState(
473                                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
474                    } else {
475                        // This is the second outgoing call. Set the Phone Call State to 3WAY
476                        app.cdmaPhoneCallState.setCurrentCallState(
477                                CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
478                    }
479                }
480
481                PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
482
483                // phone.dial() succeeded: we're now in a normal phone call.
484                // attach the URI to the CallerInfo Object if it is there,
485                // otherwise just attach the Uri Reference.
486                // if the uri does not have a "content" scheme, then we treat
487                // it as if it does NOT have a unique reference.
488                String content = phone.getContext().getContentResolver().SCHEME_CONTENT;
489                if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
490                    Object userDataObject = cn.getUserData();
491                    if (userDataObject == null) {
492                        cn.setUserData(contactRef);
493                    } else {
494                        if (userDataObject instanceof CallerInfo) {
495                            ((CallerInfo) userDataObject).contactRefUri = contactRef;
496                        } else {
497                            ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
498                                contactRef;
499                        }
500                    }
501                }
502                setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL);
503            }
504        } catch (CallStateException ex) {
505            Log.w(LOG_TAG, "PhoneUtils: Exception from phone.dial()", ex);
506            status = CALL_STATUS_FAILED;
507        }
508
509        return status;
510    }
511
512    static void switchHoldingAndActive(Phone phone) {
513        try {
514            if (DBG) log("switchHoldingAndActive");
515            phone.switchHoldingAndActive();
516        } catch (CallStateException ex) {
517            Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
518        }
519    }
520
521    /**
522     * Restore the mute setting from the earliest connection of the
523     * foreground call.
524     */
525    static Boolean restoreMuteState(Phone phone) {
526        //get the earliest connection
527        Connection c = phone.getForegroundCall().getEarliestConnection();
528
529        // only do this if connection is not null.
530        if (c != null) {
531
532            // retrieve the mute value.
533            Boolean shouldMute;
534            if (phone.getPhoneName().equals("CDMA") &&
535                    PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() ==
536                    CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
537                shouldMute = sConnectionMuteTable.get(
538                        phone.getForegroundCall().getLatestConnection());
539            } else {
540                shouldMute = sConnectionMuteTable.get(
541                        phone.getForegroundCall().getEarliestConnection());
542            }
543            if (shouldMute == null) {
544                if (DBG) log("problem retrieving mute value for this connection.");
545                shouldMute = Boolean.FALSE;
546            }
547
548            // set the mute value and return the result.
549            setMute (phone, shouldMute.booleanValue());
550            return shouldMute;
551        }
552        return Boolean.valueOf(getMute (phone));
553    }
554
555    static void mergeCalls(Phone phone) {
556        if (phone.getPhoneName().equals("GSM")) {
557            try {
558                if (DBG) log("mergeCalls");
559                phone.conference();
560            } catch (CallStateException ex) {
561                Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
562            }
563        } else { // CDMA
564            if (DBG) log("mergeCalls");
565            PhoneApp app = PhoneApp.getInstance();
566            if (app.cdmaPhoneCallState.getCurrentCallState()
567                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
568                // Send flash cmd
569                // TODO(Moto): Need to change the call from switchHoldingAndActive to
570                // something meaningful as we are not actually trying to swap calls but
571                // instead are merging two calls by sending a Flash command.
572                switchHoldingAndActive(phone);
573
574                // Set the Phone Call State to conference
575                app.cdmaPhoneCallState.setCurrentCallState(
576                        CdmaPhoneCallState.PhoneCallState.CONF_CALL);
577            }
578        }
579    }
580
581    static void separateCall(Connection c) {
582        try {
583            if (DBG) log("separateCall: " + c.getAddress());
584            c.separate();
585        } catch (CallStateException ex) {
586            Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
587        }
588    }
589
590    /**
591     * Handle the MMIInitiate message and put up an alert that lets
592     * the user cancel the operation, if applicable.
593     *
594     * @param context context to get strings.
595     * @param mmiCode the MmiCode object being started.
596     * @param buttonCallbackMessage message to post when button is clicked.
597     * @param previousAlert a previous alert used in this activity.
598     * @return the dialog handle
599     */
600    static Dialog displayMMIInitiate(Context context,
601                                          MmiCode mmiCode,
602                                          Message buttonCallbackMessage,
603                                          Dialog previousAlert) {
604        if (DBG) log("displayMMIInitiate: " + mmiCode);
605        if (previousAlert != null) {
606            previousAlert.dismiss();
607        }
608
609        // The UI paradigm we are using now requests that all dialogs have
610        // user interaction, and that any other messages to the user should
611        // be by way of Toasts.
612        //
613        // In adhering to this request, all MMI initiating "OK" dialogs
614        // (non-cancelable MMIs) that end up being closed when the MMI
615        // completes (thereby showing a completion dialog) are being
616        // replaced with Toasts.
617        //
618        // As a side effect, moving to Toasts for the non-cancelable MMIs
619        // also means that buttonCallbackMessage (which was tied into "OK")
620        // is no longer invokable for these dialogs.  This is not a problem
621        // since the only callback messages we supported were for cancelable
622        // MMIs anyway.
623        //
624        // A cancelable MMI is really just a USSD request. The term
625        // "cancelable" here means that we can cancel the request when the
626        // system prompts us for a response, NOT while the network is
627        // processing the MMI request.  Any request to cancel a USSD while
628        // the network is NOT ready for a response may be ignored.
629        //
630        // With this in mind, we replace the cancelable alert dialog with
631        // a progress dialog, displayed until we receive a request from
632        // the the network.  For more information, please see the comments
633        // in the displayMMIComplete() method below.
634        //
635        // Anything that is NOT a USSD request is a normal MMI request,
636        // which will bring up a toast (desribed above).
637        // Optional code for Extended USSD running prompt
638        if (mNwService != null) {
639            if (DBG) log("running USSD code, displaying indeterminate progress.");
640            // create the indeterminate progress dialog and display it.
641            ProgressDialog pd = new ProgressDialog(context);
642            CharSequence textmsg = "";
643            try {
644                textmsg = mNwService.getMmiRunningText();
645
646            } catch (RemoteException e) {
647                mNwService = null;
648                textmsg = context.getText(R.string.ussdRunning);
649            }
650            if (DBG) log("Extended NW displayMMIInitiate (" + textmsg+ ")");
651            pd.setMessage(textmsg);
652            pd.setCancelable(false);
653            pd.setIndeterminate(true);
654            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
655            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
656            pd.show();
657            // trigger a 15 seconds timeout to clear this progress dialog
658            mMmiTimeoutCbMsg = buttonCallbackMessage;
659            try {
660                mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000);
661            } catch(NullPointerException e) {
662                mMmiTimeoutCbMsg = null;
663            }
664            return pd;
665        }
666
667        boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
668
669        if (!isCancelable) {
670            if (DBG) log("not a USSD code, displaying status toast.");
671            CharSequence text = context.getText(R.string.mmiStarted);
672            Toast.makeText(context, text, Toast.LENGTH_SHORT)
673                .show();
674            return null;
675        } else {
676            if (DBG) log("running USSD code, displaying indeterminate progress.");
677
678            // create the indeterminate progress dialog and display it.
679            ProgressDialog pd = new ProgressDialog(context);
680            pd.setMessage(context.getText(R.string.ussdRunning));
681            pd.setCancelable(false);
682            pd.setIndeterminate(true);
683            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
684
685            pd.show();
686
687            return pd;
688        }
689
690    }
691
692    /**
693     * Handle the MMIComplete message and fire off an intent to display
694     * the message.
695     *
696     * @param context context to get strings.
697     * @param mmiCode MMI result.
698     * @param previousAlert a previous alert used in this activity.
699     */
700    static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
701            Message dismissCallbackMessage,
702            AlertDialog previousAlert) {
703        CharSequence text;
704        int title = 0;  // title for the progress dialog, if needed.
705        MmiCode.State state = mmiCode.getState();
706
707        if (DBG) log("displayMMIComplete: state=" + state);
708        // Clear timeout trigger message
709        if(mMmiTimeoutCbMsg != null) {
710            try{
711                mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what);
712                if (DBG) log("Extended NW displayMMIComplete removeMsg");
713            } catch (NullPointerException e) {
714            }
715            mMmiTimeoutCbMsg = null;
716        }
717
718
719        switch (state) {
720            case PENDING:
721                // USSD code asking for feedback from user.
722                text = mmiCode.getMessage();
723                if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
724                break;
725            case CANCELLED:
726                text = context.getText(R.string.mmiCancelled);
727                break;
728            case COMPLETE:
729                if (PhoneApp.getInstance().getPUKEntryActivity() != null) {
730                    // if an attempt to unPUK the device was made, we specify
731                    // the title and the message here.
732                    title = com.android.internal.R.string.PinMmi;
733                    text = context.getText(R.string.puk_unlocked);
734                    break;
735                }
736                // All other conditions for the COMPLETE mmi state will cause
737                // the case to fall through to message logic in common with
738                // the FAILED case.
739
740            case FAILED:
741                text = mmiCode.getMessage();
742                if (DBG) log("- using text from MMI message: '" + text + "'");
743                break;
744            default:
745                throw new IllegalStateException("Unexpected MmiCode state: " + state);
746        }
747
748        if (previousAlert != null) {
749            previousAlert.dismiss();
750        }
751
752        // Check to see if a UI exists for the PUK activation.  If it does
753        // exist, then it indicates that we're trying to unblock the PUK.
754        PhoneApp app = PhoneApp.getInstance();
755        if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
756            if (DBG) log("displaying PUK unblocking progress dialog.");
757
758            // create the progress dialog, make sure the flags and type are
759            // set correctly.
760            ProgressDialog pd = new ProgressDialog(app);
761            pd.setTitle(title);
762            pd.setMessage(text);
763            pd.setCancelable(false);
764            pd.setIndeterminate(true);
765            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
766            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
767
768            // display the dialog
769            pd.show();
770
771            // indicate to the Phone app that the progress dialog has
772            // been assigned for the PUK unlock / SIM READY process.
773            app.setPukEntryProgressDialog(pd);
774
775        } else {
776            // In case of failure to unlock, we'll need to reset the
777            // PUK unlock activity, so that the user may try again.
778            if (app.getPUKEntryActivity() != null) {
779                app.setPukEntryActivity(null);
780            }
781
782            // A USSD in a pending state means that it is still
783            // interacting with the user.
784            if (state != MmiCode.State.PENDING) {
785                if (DBG) log("MMI code has finished running.");
786
787                // Replace response message with Extended Mmi wording
788                if (mNwService != null) {
789                    try {
790                        text = mNwService.getUserMessage(text);
791                    } catch (RemoteException e) {
792                        mNwService = null;
793                    }
794                    if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
795                    if (text == null || text.length() == 0)
796                        return;
797                }
798
799                // displaying system alert dialog on the screen instead of
800                // using another activity to display the message.  This
801                // places the message at the forefront of the UI.
802                AlertDialog newDialog = new AlertDialog.Builder(context)
803                        .setMessage(text)
804                        .setPositiveButton(R.string.ok, null)
805                        .setCancelable(true)
806                        .create();
807
808                newDialog.getWindow().setType(
809                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
810                newDialog.getWindow().addFlags(
811                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
812
813                newDialog.show();
814            } else {
815                if (DBG) log("USSD code has requested user input. Constructing input dialog.");
816
817                // USSD MMI code that is interacting with the user.  The
818                // basic set of steps is this:
819                //   1. User enters a USSD request
820                //   2. We recognize the request and displayMMIInitiate
821                //      (above) creates a progress dialog.
822                //   3. Request returns and we get a PENDING or COMPLETE
823                //      message.
824                //   4. These MMI messages are caught in the PhoneApp
825                //      (onMMIComplete) and the InCallScreen
826                //      (mHandler.handleMessage) which bring up this dialog
827                //      and closes the original progress dialog,
828                //      respectively.
829                //   5. If the message is anything other than PENDING,
830                //      we are done, and the alert dialog (directly above)
831                //      displays the outcome.
832                //   6. If the network is requesting more information from
833                //      the user, the MMI will be in a PENDING state, and
834                //      we display this dialog with the message.
835                //   7. User input, or cancel requests result in a return
836                //      to step 1.  Keep in mind that this is the only
837                //      time that a USSD should be canceled.
838
839                // inflate the layout with the scrolling text area for the dialog.
840                LayoutInflater inflater = (LayoutInflater) context.getSystemService(
841                        Context.LAYOUT_INFLATER_SERVICE);
842                View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
843
844                // get the input field.
845                final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
846
847                // specify the dialog's click listener, with SEND and CANCEL logic.
848                final DialogInterface.OnClickListener mUSSDDialogListener =
849                    new DialogInterface.OnClickListener() {
850                        public void onClick(DialogInterface dialog, int whichButton) {
851                            switch (whichButton) {
852                                case DialogInterface.BUTTON1:
853                                    phone.sendUssdResponse(inputText.getText().toString());
854                                    break;
855                                case DialogInterface.BUTTON2:
856                                    if (mmiCode.isCancelable()) {
857                                        mmiCode.cancel();
858                                    }
859                                    break;
860                            }
861                        }
862                    };
863
864                // build the dialog
865                final AlertDialog newDialog = new AlertDialog.Builder(context)
866                        .setMessage(text)
867                        .setView(dialogView)
868                        .setPositiveButton(R.string.send_button, mUSSDDialogListener)
869                        .setNegativeButton(R.string.cancel, mUSSDDialogListener)
870                        .setCancelable(false)
871                        .create();
872
873                // attach the key listener to the dialog's input field and make
874                // sure focus is set.
875                final View.OnKeyListener mUSSDDialogInputListener =
876                    new View.OnKeyListener() {
877                        public boolean onKey(View v, int keyCode, KeyEvent event) {
878                            switch (keyCode) {
879                                case KeyEvent.KEYCODE_CALL:
880                                case KeyEvent.KEYCODE_ENTER:
881                                    phone.sendUssdResponse(inputText.getText().toString());
882                                    newDialog.dismiss();
883                                    return true;
884                            }
885                            return false;
886                        }
887                    };
888                inputText.setOnKeyListener(mUSSDDialogInputListener);
889                inputText.requestFocus();
890
891                // set the window properties of the dialog
892                newDialog.getWindow().setType(
893                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
894                newDialog.getWindow().addFlags(
895                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
896
897                // now show the dialog!
898                newDialog.show();
899            }
900        }
901    }
902
903    /**
904     * Cancels the current pending MMI operation, if applicable.
905     * @return true if we canceled an MMI operation, or false
906     *         if the current pending MMI wasn't cancelable
907     *         or if there was no current pending MMI at all.
908     *
909     * @see displayMMIInitiate
910     */
911    static boolean cancelMmiCode(Phone phone) {
912        List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
913        int count = pendingMmis.size();
914        if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
915
916        boolean canceled = false;
917        if (count > 0) {
918            // assume that we only have one pending MMI operation active at a time.
919            // I don't think it's possible to enter multiple MMI codes concurrently
920            // in the phone UI, because during the MMI operation, an Alert panel
921            // is displayed, which prevents more MMI code from being entered.
922            MmiCode mmiCode = pendingMmis.get(0);
923            if (mmiCode.isCancelable()) {
924                mmiCode.cancel();
925                canceled = true;
926            }
927        }
928
929        //clear timeout message and pre-set MMI command
930        if (mNwService != null) {
931            try {
932                mNwService.clearMmiString();
933            } catch (RemoteException e) {
934                mNwService = null;
935            }
936        }
937        if (mMmiTimeoutCbMsg != null) {
938            mMmiTimeoutCbMsg = null;
939        }
940        return canceled;
941    }
942
943    public static class VoiceMailNumberMissingException extends Exception {
944        VoiceMailNumberMissingException() {
945            super();
946        }
947
948        VoiceMailNumberMissingException(String msg) {
949            super(msg);
950        }
951    }
952
953    /**
954     * Gets the phone number to be called from an intent.  Requires a Context
955     * to access the contacts database, and a Phone to access the voicemail
956     * number.
957     *
958     * <p>If <code>phone</code> is <code>null</code>, the function will return
959     * <code>null</code> for <code>voicemail:</code> URIs;
960     * if <code>context</code> is <code>null</code>, the function will return
961     * <code>null</code> for person/phone URIs.</p>
962     *
963     * @param context a context to use (or
964     * @param phone the phone on which the number would be called
965     * @param intent the intent
966     *
967     * @throws VoiceMailNumberMissingException if <code>intent</code> contains
968     *         a <code>voicemail:</code> URI, but <code>phone</code> does not
969     *         have a voicemail number set.
970     *
971     * @return the phone number that would be called by the intent,
972     *         or <code>null</code> if the number cannot be found.
973     */
974    static String getNumberFromIntent(Context context, Phone phone, Intent intent)
975            throws VoiceMailNumberMissingException {
976        final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
977
978        // Check for a voicemail-dailing request.  If the voicemail number is
979        // empty, throw a VoiceMailNumberMissingException.
980        if (intent.getData().getScheme().equals("voicemail") &&
981                (number == null || TextUtils.isEmpty(number)))
982            throw new VoiceMailNumberMissingException();
983
984        return number;
985    }
986
987    /**
988     * Returns the caller-id info corresponding to the specified Connection.
989     * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
990     * extract a phone number from the specified Connection, and feed that
991     * number into CallerInfo.getCallerInfo().)
992     *
993     * The returned CallerInfo may be null in certain error cases, like if the
994     * specified Connection was null, or if we weren't able to get a valid
995     * phone number from the Connection.
996     *
997     * Finally, if the getCallerInfo() call did succeed, we save the resulting
998     * CallerInfo object in the "userData" field of the Connection.
999     *
1000     * NOTE: This API should be avoided, with preference given to the
1001     * asynchronous startGetCallerInfo API.
1002     */
1003    static CallerInfo getCallerInfo(Context context, Connection c) {
1004        CallerInfo info = null;
1005
1006        if (c != null) {
1007            //See if there is a URI attached.  If there is, this means
1008            //that there is no CallerInfo queried yet, so we'll need to
1009            //replace the URI with a full CallerInfo object.
1010            Object userDataObject = c.getUserData();
1011            if (userDataObject instanceof Uri) {
1012                info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1013                if (info != null) {
1014                    c.setUserData(info);
1015                }
1016            } else {
1017                if (userDataObject instanceof CallerInfoToken) {
1018                    //temporary result, while query is running
1019                    info = ((CallerInfoToken) userDataObject).currentInfo;
1020                } else {
1021                    //final query result
1022                    info = (CallerInfo) userDataObject;
1023                }
1024                if (info == null) {
1025                    // No URI, or Existing CallerInfo, so we'll have to make do with
1026                    // querying a new CallerInfo using the connection's phone number.
1027                    String number = c.getAddress();
1028
1029                    if (DBG) log("getCallerInfo: number = " + number);
1030
1031                    if (!TextUtils.isEmpty(number)) {
1032                        info = CallerInfo.getCallerInfo(context, number);
1033                        if (info != null) {
1034                            c.setUserData(info);
1035                        }
1036                    }
1037                }
1038            }
1039        }
1040        return info;
1041    }
1042
1043    /**
1044     * Class returned by the startGetCallerInfo call to package a temporary
1045     * CallerInfo Object, to be superceded by the CallerInfo Object passed
1046     * into the listener when the query with token mAsyncQueryToken is complete.
1047     */
1048    public static class CallerInfoToken {
1049        /**indicates that there will no longer be updates to this request.*/
1050        public boolean isFinal;
1051
1052        public CallerInfo currentInfo;
1053        public CallerInfoAsyncQuery asyncQuery;
1054    }
1055
1056    /**
1057     * Start a CallerInfo Query based on the earliest connection in the call.
1058     */
1059    static CallerInfoToken startGetCallerInfo(Context context, Call call,
1060            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1061        PhoneApp app = PhoneApp.getInstance();
1062        Connection conn = null;
1063        if (app.phone.getPhoneName().equals("CDMA")) {
1064            conn = call.getLatestConnection();
1065        } else {
1066            conn = call.getEarliestConnection();
1067        }
1068
1069        return startGetCallerInfo(context, conn, listener, cookie);
1070    }
1071
1072    /**
1073     * place a temporary callerinfo object in the hands of the caller and notify
1074     * caller when the actual query is done.
1075     */
1076    static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1077            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1078        CallerInfoToken cit;
1079
1080        if (c == null) {
1081            //TODO: perhaps throw an exception here.
1082            cit = new CallerInfoToken();
1083            cit.asyncQuery = null;
1084            return cit;
1085        }
1086
1087        // There are now 3 states for the userdata.
1088        //   1. Uri - query has not been executed yet
1089        //   2. CallerInfoToken - query is executing, but has not completed.
1090        //   3. CallerInfo - query has executed.
1091        // In each case we have slightly different behaviour:
1092        //   1. If the query has not been executed yet (Uri or null), we start
1093        //      query execution asynchronously, and note it by attaching a
1094        //      CallerInfoToken as the userData.
1095        //   2. If the query is executing (CallerInfoToken), we've essentially
1096        //      reached a state where we've received multiple requests for the
1097        //      same callerInfo.  That means that once the query is complete,
1098        //      we'll need to execute the additional listener requested.
1099        //   3. If the query has already been executed (CallerInfo), we just
1100        //      return the CallerInfo object as expected.
1101        //   4. Regarding isFinal - there are cases where the CallerInfo object
1102        //      will not be attached, like when the number is empty (caller id
1103        //      blocking).  This flag is used to indicate that the
1104        //      CallerInfoToken object is going to be permanent since no
1105        //      query results will be returned.  In the case where a query
1106        //      has been completed, this flag is used to indicate to the caller
1107        //      that the data will not be updated since it is valid.
1108        //
1109        //      Note: For the case where a number is NOT retrievable, we leave
1110        //      the CallerInfo as null in the CallerInfoToken.  This is
1111        //      something of a departure from the original code, since the old
1112        //      code manufactured a CallerInfo object regardless of the query
1113        //      outcome.  From now on, we will append an empty CallerInfo
1114        //      object, to mirror previous behaviour, and to avoid Null Pointer
1115        //      Exceptions.
1116        Object userDataObject = c.getUserData();
1117        if (userDataObject instanceof Uri) {
1118            //create a dummy callerinfo, populate with what we know from URI.
1119            cit = new CallerInfoToken();
1120            cit.currentInfo = new CallerInfo();
1121            cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1122                    (Uri) userDataObject, sCallerInfoQueryListener, c);
1123            cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1124            cit.isFinal = false;
1125
1126            c.setUserData(cit);
1127
1128            if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1129
1130        } else if (userDataObject == null) {
1131            // No URI, or Existing CallerInfo, so we'll have to make do with
1132            // querying a new CallerInfo using the connection's phone number.
1133            String number = c.getAddress();
1134            int cnapSpecialCase;
1135
1136            cit = new CallerInfoToken();
1137            cit.currentInfo = new CallerInfo();
1138
1139            if (DBG) log("startGetCallerInfo: number = " + number);
1140
1141            // handling case where number is null (caller id hidden) as well.
1142            if (!TextUtils.isEmpty(number)) {
1143                // Store CNAP information retrieved from the Connection
1144                cit.currentInfo.cnapName =  c.getCnapName();
1145                cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1146                                                                 // by ContactInfo later
1147                cit.currentInfo.numberPresentation = c.getNumberPresentation();
1148                cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1149                if (DBG) log("startGetCallerInfo: CNAP Info from FW: name="
1150                        + cit.currentInfo.cnapName
1151                        + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1152                // Only when numberPresentation is ALLOWED, check the special string:
1153                if (cit.currentInfo.numberPresentation == Connection.PRESENTATION_ALLOWED) {
1154                    cnapSpecialCase = checkCnapSpecialCases(number);
1155                    if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
1156                        // For all special strings, change number & numberPresentation.
1157                        if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) {
1158                            number = context.getString(R.string.private_num);
1159                        } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) {
1160                            number = context.getString(R.string.unknown);
1161                        }
1162                        cit.currentInfo.numberPresentation = cnapSpecialCase;
1163                    }
1164                }
1165
1166                cit.currentInfo.phoneNumber = number;
1167                cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1168                        number, sCallerInfoQueryListener, c);
1169                cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1170                cit.isFinal = false;
1171            } else {
1172                // This is the case where we are querying on a number that
1173                // is null or empty, like a caller whose caller id is
1174                // blocked or empty (CLIR).  The previous behaviour was to
1175                // throw a null CallerInfo object back to the user, but
1176                // this departure is somewhat cleaner.
1177                if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1178                cit.isFinal = true; // please see note on isFinal, above.
1179            }
1180
1181            c.setUserData(cit);
1182
1183            if (DBG) log("startGetCallerInfo: query based on number: " + number);
1184
1185        } else if (userDataObject instanceof CallerInfoToken) {
1186            // query is running, just tack on this listener to the queue.
1187            cit = (CallerInfoToken) userDataObject;
1188
1189            // handling case where number is null (caller id hidden) as well.
1190            if (cit.asyncQuery != null) {
1191                cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1192
1193                if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1194                        listener.getClass().toString());
1195            } else {
1196                // handling case where number/name gets updated later on by the network
1197                String updatedNumber = c.getAddress();
1198                if (DBG) log("startGetCallerInfo: updatedNumber = " + updatedNumber);
1199                if (!TextUtils.isEmpty(updatedNumber)) {
1200                    cit.currentInfo.phoneNumber = updatedNumber;
1201
1202                    // Store CNAP information retrieved from the Connection
1203                    cit.currentInfo.cnapName =  c.getCnapName();
1204                    // This can still get overwritten by ContactInfo
1205                    cit.currentInfo.name = cit.currentInfo.cnapName;
1206                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1207                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1208
1209                    if (DBG) log("startGetCallerInfo: CNAP Info from FW: name="
1210                            + cit.currentInfo.cnapName
1211                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1212                    cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1213                            updatedNumber, sCallerInfoQueryListener, c);
1214                    cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1215                    cit.isFinal = false;
1216                } else {
1217                    if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1218                    if (cit.currentInfo == null) {
1219                        cit.currentInfo = new CallerInfo();
1220                    }
1221                    cit.isFinal = true; // please see note on isFinal, above.
1222                }
1223            }
1224        } else {
1225            cit = new CallerInfoToken();
1226            cit.currentInfo = (CallerInfo) userDataObject;
1227            cit.asyncQuery = null;
1228            cit.isFinal = true;
1229            // since the query is already done, call the listener.
1230            if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1231        }
1232        return cit;
1233    }
1234
1235    /**
1236     * Implemented for CallerInfo.OnCallerInfoQueryCompleteListener interface.
1237     * Updates the connection's userData when called.
1238     */
1239    private static final int QUERY_TOKEN = -1;
1240    static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1241        new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1242            public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1243                if (DBG) log("query complete, updating connection.userdata");
1244
1245                // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1246                // If no ContactInfo, then we want to use CNAP information coming from network
1247                if (DBG) log("- onQueryComplete: contactExists=" + ci.contactExists);
1248                if (ci.contactExists) {
1249                    ((Connection) cookie).setUserData(ci);
1250                } else {
1251                    CallerInfo newCi = getCallerInfo(null, (Connection) cookie);
1252                    if (newCi != null) {
1253                        newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1254                        ((Connection) cookie).setUserData(newCi);
1255                    }
1256                    else ((Connection) cookie).setUserData(ci);
1257                }
1258            }
1259        };
1260
1261    static void saveToContact(Context context, String number) {
1262        Intent intent = new Intent(Contacts.Intents.Insert.ACTION,
1263                Contacts.People.CONTENT_URI);
1264        intent.putExtra(Contacts.Intents.Insert.PHONE, number);
1265        context.startActivity(intent);
1266    }
1267
1268    /**
1269     * Returns a single "name" for the specified given a CallerInfo object.
1270     * If the name is null, return defaultString as the default value, usually
1271     * context.getString(R.string.unknown).
1272     */
1273    static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1274        if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1275
1276        String compactName = null;
1277        if (ci != null) {
1278            compactName = ci.name;
1279            if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1280                compactName = ci.phoneNumber;
1281            }
1282        }
1283        // TODO: figure out UNKNOWN, PRIVATE numbers?
1284        if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1285            compactName = context.getString(R.string.unknown);
1286        }
1287        return compactName;
1288    }
1289
1290    /**
1291     * Returns true if the specified Call is a "conference call", meaning
1292     * that it owns more than one Connection object.  This information is
1293     * used to trigger certain UI changes that appear when a conference
1294     * call is active (like displaying the label "Conference call", and
1295     * enabling the "Manage conference" UI.)
1296     *
1297     * Watch out: This method simply checks the number of Connections,
1298     * *not* their states.  So if a Call has (for example) one ACTIVE
1299     * connection and one DISCONNECTED connection, this method will return
1300     * true (which is unintuitive, since the Call isn't *really* a
1301     * conference call any more.)
1302     *
1303     * @return true if the specified call has more than one connection (in any state.)
1304     */
1305    static boolean isConferenceCall(Call call) {
1306        // CDMA phones don't have the same concept of "conference call" as
1307        // GSM phones do; there's no special "conference call" state of
1308        // the UI or a "manage conference" function.  (Instead, when
1309        // you're in a 3-way call, all we can do is display the "generic"
1310        // state of the UI.)  So as far as the in-call UI is concerned,
1311        // Conference corresponds to generic display.
1312        PhoneApp app = PhoneApp.getInstance();
1313        if (app.phone.getPhoneName().equals("CDMA")) {
1314            if (app.cdmaPhoneCallState.getCurrentCallState()
1315                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
1316                return true;
1317            }
1318        } else {
1319            List<Connection> connections = call.getConnections();
1320            if (connections != null && connections.size() > 1) {
1321                return true;
1322            }
1323        }
1324        return false;
1325
1326        // TODO: We may still want to change the semantics of this method
1327        // to say that a given call is only really a conference call if
1328        // the number of ACTIVE connections, not the total number of
1329        // connections, is greater than one.  (See warning comment in the
1330        // javadoc above.)
1331        // Here's an implementation of that:
1332        //        if (connections == null) {
1333        //            return false;
1334        //        }
1335        //        int numActiveConnections = 0;
1336        //        for (Connection conn : connections) {
1337        //            if (DBG) log("  - CONN: " + conn + ", state = " + conn.getState());
1338        //            if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1339        //            if (numActiveConnections > 1) {
1340        //                return true;
1341        //            }
1342        //        }
1343        //        return false;
1344    }
1345
1346    /**
1347     * Launch the Dialer to start a new call.
1348     * This is just a wrapper around the ACTION_DIAL intent.
1349     */
1350    static void startNewCall(final Phone phone) {
1351        final KeyguardManager keyguardManager = PhoneApp.getInstance().getKeyguardManager();
1352        if (!keyguardManager.inKeyguardRestrictedInputMode()) {
1353            internalStartNewCall(phone);
1354        } else {
1355            keyguardManager.exitKeyguardSecurely(new KeyguardManager.OnKeyguardExitResult() {
1356                public void onKeyguardExitResult(boolean success) {
1357                    if (success) {
1358                        internalStartNewCall(phone);
1359                    }
1360                }
1361            });
1362        }
1363    }
1364
1365    private static void internalStartNewCall(Phone phone) {
1366        // Sanity-check that this is OK given the current state of the phone.
1367        if (!okToAddCall(phone)) {
1368            Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1369            dumpCallState(phone);
1370            return;
1371        }
1372
1373        // if applicable, mute the call while we're showing the add call UI.
1374        if (!phone.getForegroundCall().isIdle()) {
1375            setMuteInternal(phone, true);
1376            // Inform the phone app that this mute state was NOT done
1377            // voluntarily by the User.
1378            PhoneApp.getInstance().setRestoreMuteOnInCallResume(true);
1379        }
1380
1381        Intent intent = new Intent(Intent.ACTION_DIAL);
1382        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1383
1384        // when we request the dialer come up, we also want to inform
1385        // it that we're going through the "add call" option from the
1386        // InCallScreen / PhoneUtils.
1387        intent.putExtra(ADD_CALL_MODE_KEY, true);
1388
1389        PhoneApp.getInstance().startActivity(intent);
1390    }
1391
1392    /**
1393     * Brings up the UI used to handle an incoming call.
1394     *
1395     * Originally, this brought up an IncomingCallPanel instance
1396     * (which was a subclass of Dialog) on top of whatever app
1397     * was currently running.  Now, we take you directly to the
1398     * in-call screen, whose CallCard automatically does the right
1399     * thing if there's a Call that's currently ringing.
1400     */
1401    static void showIncomingCallUi() {
1402        if (DBG) log("showIncomingCallUi()...");
1403        PhoneApp app = PhoneApp.getInstance();
1404
1405        // Before bringing up the "incoming call" UI, force any system
1406        // dialogs (like "recent tasks" or the power dialog) to close first.
1407        try {
1408            ActivityManagerNative.getDefault().closeSystemDialogs("call");
1409        } catch (RemoteException e) {
1410        }
1411
1412        // Go directly to the in-call screen.
1413        // (No need to do anything special if we're already on the in-call
1414        // screen; it'll notice the phone state change and update itself.)
1415
1416        // But first, grab a full wake lock.  We do this here, before we
1417        // even fire off the InCallScreen intent, to make sure the
1418        // ActivityManager doesn't try to pause the InCallScreen as soon
1419        // as it comes up.  (See bug 1648751.)
1420        //
1421        // And since the InCallScreen isn't visible yet (we haven't even
1422        // fired off the intent yet), we DON'T want the screen to actually
1423        // come on right now.  So *before* acquiring the wake lock we need
1424        // to call preventScreenOn(), which tells the PowerManager that
1425        // the screen should stay off even if someone's holding a full
1426        // wake lock.  (This prevents any flicker during the "incoming
1427        // call" sequence.  The corresponding preventScreenOn(false) call
1428        // will come from the InCallScreen when it's finally ready to be
1429        // displayed.)
1430        //
1431        // TODO: this is all a temporary workaround.  The real fix is to add
1432        // an Activity attribute saying "this Activity wants to wake up the
1433        // phone when it's displayed"; that way the ActivityManager could
1434        // manage the wake locks *and* arrange for the screen to come on at
1435        // the exact moment that the InCallScreen is ready to be displayed.
1436        // (See bug 1648751.)
1437        app.preventScreenOn(true);
1438        app.requestWakeState(PhoneApp.WakeState.FULL);
1439
1440        // Fire off the InCallScreen intent.
1441        app.displayCallScreen();
1442    }
1443
1444    static void turnOnSpeaker(Context context, boolean flag) {
1445        if (DBG) log("turnOnSpeaker: " + flag);
1446        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1447
1448        audioManager.setSpeakerphoneOn(flag);
1449        // record the speaker-enable value
1450        sIsSpeakerEnabled = flag;
1451        if (flag) {
1452            NotificationMgr.getDefault().notifySpeakerphone();
1453        } else {
1454            NotificationMgr.getDefault().cancelSpeakerphone();
1455        }
1456
1457        // We also need to make a fresh call to PhoneApp.updateWakeState()
1458        // any time the speaker state changes, since the screen timeout is
1459        // sometimes different depending on whether or not the speaker is
1460        // in use.
1461        PhoneApp app = PhoneApp.getInstance();
1462        app.updateWakeState();
1463
1464        // Update the Proximity sensor based on speaker state
1465        app.updateProximitySensorMode(app.phone.getState());
1466    }
1467
1468    /**
1469     * Restore the speaker mode, called after a wired headset disconnect
1470     * event.
1471     */
1472    static void restoreSpeakerMode(Context context) {
1473        if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1474
1475        // change the mode if needed.
1476        if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1477            turnOnSpeaker(context, sIsSpeakerEnabled);
1478        }
1479    }
1480
1481    static boolean isSpeakerOn(Context context) {
1482        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1483        return audioManager.isSpeakerphoneOn();
1484    }
1485
1486    /**
1487     * Wrapper around Phone.setMute() that also updates the mute icon in
1488     * the status bar.
1489     *
1490     * All muting / unmuting from the in-call UI should go through this
1491     * wrapper.
1492     */
1493    static void setMute(Phone phone, boolean muted) {
1494        // make the call to mute the audio
1495        setMuteInternal(phone, muted);
1496
1497        // update the foreground connections to match.  This includes
1498        // all the connections on conference calls.
1499        for (Connection cn : phone.getForegroundCall().getConnections()) {
1500            if (sConnectionMuteTable.get(cn) == null) {
1501                if (DBG) log("problem retrieving mute value for this connection.");
1502            }
1503            sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
1504        }
1505    }
1506
1507    /**
1508     * Internally used muting function.  All UI calls should use {@link setMute}
1509     */
1510    static void setMuteInternal(Phone phone, boolean muted) {
1511        if (DBG) log("setMute: " + muted);
1512        phone.setMute(muted);
1513        if (muted) {
1514            NotificationMgr.getDefault().notifyMute();
1515        } else {
1516            NotificationMgr.getDefault().cancelMute();
1517        }
1518    }
1519
1520    static boolean getMute(Phone phone) {
1521        return phone.getMute();
1522    }
1523
1524    /**
1525     * A really simple wrapper around AudioManager.setMode(),
1526     * with a bit of extra logging to help debug the exact
1527     * timing (and call stacks) for all our setMode() calls.
1528     *
1529     * Also, add additional state monitoring to determine
1530     * whether or not certain calls to change the audio mode
1531     * are ignored.
1532     */
1533    /* package */ static void setAudioMode(Context context, int mode) {
1534        if (DBG) Log.d(LOG_TAG, "PhoneUtils.setAudioMode(" + audioModeToString(mode) + ")...");
1535
1536        //decide whether or not to ignore the audio setting
1537        boolean ignore = false;
1538
1539        switch (sAudioBehaviourState) {
1540            case AUDIO_RINGING:
1541                ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_IN_CALL));
1542                break;
1543            case AUDIO_OFFHOOK:
1544                ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_RINGTONE));
1545                break;
1546            case AUDIO_IDLE:
1547            default:
1548                ignore = (mode == AudioManager.MODE_IN_CALL);
1549                break;
1550        }
1551
1552        if (!ignore) {
1553            AudioManager audioManager =
1554                    (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1555            // Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
1556            if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
1557            audioManager.setMode(mode);
1558        } else {
1559            if (DBG) Log.d(LOG_TAG, "PhoneUtils.setAudioMode(), state is " + sAudioBehaviourState +
1560                    " ignoring " + audioModeToString(mode) + " request");
1561        }
1562    }
1563    private static String audioModeToString(int mode) {
1564        switch (mode) {
1565            case AudioManager.MODE_INVALID: return "MODE_INVALID";
1566            case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
1567            case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
1568            case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
1569            case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
1570            default: return String.valueOf(mode);
1571        }
1572    }
1573
1574    /**
1575     * Handles the wired headset button while in-call.
1576     *
1577     * This is called from the PhoneApp, not from the InCallScreen,
1578     * since the HEADSETHOOK button means "mute or unmute the current
1579     * call" *any* time a call is active, even if the user isn't actually
1580     * on the in-call screen.
1581     *
1582     * @return true if we consumed the event.
1583     */
1584    /* package */ static boolean handleHeadsetHook(Phone phone) {
1585        if (DBG) log("handleHeadsetHook()...");
1586
1587        // If the phone is totally idle, we ignore HEADSETHOOK events
1588        // (and instead let them fall through to the media player.)
1589        if (phone.getState() == Phone.State.IDLE) {
1590            return false;
1591        }
1592
1593        // Ok, the phone is in use.
1594        // The headset button button means "Answer" if an incoming call is
1595        // ringing.  If not, it toggles the mute / unmute state.
1596        //
1597        // And in any case we *always* consume this event; this means
1598        // that the usual mediaplayer-related behavior of the headset
1599        // button will NEVER happen while the user is on a call.
1600
1601        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1602        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1603        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1604
1605        if (phone.getPhoneName().equals("CDMA")) {
1606            PhoneApp app = PhoneApp.getInstance();
1607            if (hasRingingCall) {
1608                answerCall(phone);
1609            } else {
1610                if (app.cdmaPhoneCallState.getCurrentCallState()
1611                        == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE) {
1612                    // Send a flash command to CDMA network for putting the other
1613                    // party on hold.
1614                    // For CDMA networks which do not support this the user would just
1615                    // hear a beep from the network.
1616                    // For CDMA networks which do support it it will put the other
1617                    // party on hold.
1618                    switchHoldingAndActive(phone);
1619                }
1620
1621                // No incoming ringing call.  Toggle the mute state.
1622                if (getMute(phone)) {
1623                    if (DBG) log("handleHeadsetHook: UNmuting...");
1624                    setMute(phone, false);
1625                } else {
1626                    if (DBG) log("handleHeadsetHook: muting...");
1627                    setMute(phone, true);
1628                }
1629            }
1630        } else { // GSM
1631            if (hasRingingCall) {
1632                // If an incoming call is ringing, answer it (just like with the
1633                // CALL button):
1634                if (hasActiveCall && hasHoldingCall) {
1635                    if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
1636                    answerAndEndActive(phone);
1637                } else {
1638                    if (DBG) log("handleHeadsetHook: ringing ==> answer!");
1639                    answerCall(phone);  // Automatically holds the current active call,
1640                                     // if there is one
1641                }
1642            } else {
1643                // No incoming ringing call.  Toggle the mute state.
1644                if (getMute(phone)) {
1645                    if (DBG) log("handleHeadsetHook: UNmuting...");
1646                    setMute(phone, false);
1647                } else {
1648                    if (DBG) log("handleHeadsetHook: muting...");
1649                    setMute(phone, true);
1650                }
1651            }
1652        }
1653
1654        // Even if the InCallScreen is the current activity, there's no
1655        // need to force it to update, because (1) if we answered a
1656        // ringing call, the InCallScreen will imminently get a phone
1657        // state change event (causing an update), and (2) if we muted or
1658        // unmuted, the setMute() call automagically updates the status
1659        // bar, and there's no "mute" indication in the InCallScreen
1660        // itself (other than the menu item, which only ever stays
1661        // onscreen for a second anyway.)
1662
1663        return true;
1664    }
1665
1666    /**
1667     * Look for ANY connections on the phone that qualify as being
1668     * disconnected.
1669     *
1670     * @return true if we find a connection that is disconnected over
1671     * all the phone's call objects.
1672     */
1673    /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1674        return hasDisconnectedConnections(phone.getForegroundCall()) ||
1675                hasDisconnectedConnections(phone.getBackgroundCall()) ||
1676                hasDisconnectedConnections(phone.getRingingCall());
1677    }
1678
1679    /**
1680     * Iterate over all connections in a call to see if there are any
1681     * that are not alive (disconnected or idle).
1682     *
1683     * @return true if we find a connection that is disconnected, and
1684     * pending removal via
1685     * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
1686     */
1687    private static final boolean hasDisconnectedConnections(Call call) {
1688        // look through all connections for non-active ones.
1689        for (Connection c : call.getConnections()) {
1690            if (!c.isAlive()) {
1691                return true;
1692            }
1693        }
1694        return false;
1695    }
1696
1697    //
1698    // Misc UI policy helper functions
1699    //
1700
1701    /**
1702     * @return true if we're allowed to swap calls, given the current
1703     * state of the Phone.
1704     */
1705    /* package */ static boolean okToSwapCalls(Phone phone) {
1706        if (phone.getPhoneName().equals("CDMA")) {
1707            // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
1708            // state by either accepting a Call Waiting or by merging two calls
1709            PhoneApp app = PhoneApp.getInstance();
1710            return (app.cdmaPhoneCallState.getCurrentCallState()
1711                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
1712        } else {
1713            // GSM: "Swap" is available if both lines are in use and there's no
1714            // incoming call.  (Actually we need to verify that the active
1715            // call really is in the ACTIVE state and the holding call really
1716            // is in the HOLDING state, since you *can't* actually swap calls
1717            // when the foreground call is DIALING or ALERTING.)
1718            return phone.getRingingCall().isIdle()
1719                    && (phone.getForegroundCall().getState() == Call.State.ACTIVE)
1720                    && (phone.getBackgroundCall().getState() == Call.State.HOLDING);
1721        }
1722    }
1723
1724    /**
1725     * @return true if we're allowed to merge calls, given the current
1726     * state of the Phone.
1727     */
1728    /* package */ static boolean okToMergeCalls(Phone phone) {
1729        if (phone.getPhoneName().equals("CDMA")) {
1730            // CDMA: "Merge" is enabled only when the user is in a 3Way call.
1731            PhoneApp app = PhoneApp.getInstance();
1732            return (app.cdmaPhoneCallState.getCurrentCallState()
1733                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
1734        } else { //GSM.
1735            // GSM: "Merge" is available if both lines are in use and there's no
1736            // incoming call, *and* the current conference isn't already
1737            // "full".
1738            return phone.getRingingCall().isIdle() && phone.canConference();
1739        }
1740    }
1741
1742    /**
1743     * @return true if the UI should let you add a new call, given the current
1744     * state of the Phone.
1745     */
1746    /* package */ static boolean okToAddCall(Phone phone) {
1747       if (phone.getPhoneName().equals("CDMA")) {
1748           // CDMA: "Add call" menu item is only enabled when the call is in
1749           // - SINGLE_ACTIVE state
1750           // - After 60 seconds of user Ignoring/Missing a Call Waiting call.
1751            PhoneApp app = PhoneApp.getInstance();
1752            return ((app.cdmaPhoneCallState.getCurrentCallState()
1753                    == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE)
1754                    && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
1755        } else {
1756            // GSM: "Add call" is available only if ALL of the following are true:
1757            // - There's no incoming ringing call
1758            // - There's < 2 lines in use
1759            // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
1760            //   (We mainly need to make sure it *isn't* DIALING or ALERTING.)
1761            final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1762            final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1763            final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1764            final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1765            final Call.State fgCallState = phone.getForegroundCall().getState();
1766
1767            return !hasRingingCall
1768                    && !allLinesTaken
1769                    && ((fgCallState == Call.State.ACTIVE)
1770                        || (fgCallState == Call.State.IDLE)
1771                        || (fgCallState == Call.State.DISCONNECTED));
1772        }
1773    }
1774
1775    /**
1776     * Based on the input CNAP number string,
1777     * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1778     * Otherwise, return CNAP_SPECIAL_CASE_NO.
1779     */
1780    private static int checkCnapSpecialCases(String n) {
1781        if (n.equals("PRIVATE") ||
1782                n.equals("P") ||
1783                n.equals("RES")) {
1784            if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1785            return Connection.PRESENTATION_RESTRICTED;
1786        } else if (n.equals("UNAVAILABLE") ||
1787                n.equals("UNKNOWN") ||
1788                n.equals("UNA") ||
1789                n.equals("U")) {
1790            if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1791            return Connection.PRESENTATION_UNKNOWN;
1792        } else {
1793            if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1794            return CNAP_SPECIAL_CASE_NO;
1795        }
1796    }
1797
1798    //
1799    // General phone and call state debugging/testing code
1800    //
1801
1802    /* package */ static void dumpCallState(Phone phone) {
1803        Log.d(LOG_TAG, "##### dumpCallState()");
1804        Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
1805              + ", state = " + phone.getState());
1806        Log.d(LOG_TAG, "-");
1807
1808        Call fgCall = phone.getForegroundCall();
1809        Log.d(LOG_TAG, "- FG call: " + fgCall);
1810        Log.d(LOG_TAG, "-  state: " + fgCall.getState());
1811        Log.d(LOG_TAG, "-  isAlive(): " + fgCall.getState().isAlive());
1812        Log.d(LOG_TAG, "-  isRinging(): " + fgCall.getState().isRinging());
1813        Log.d(LOG_TAG, "-  isDialing(): " + fgCall.getState().isDialing());
1814        Log.d(LOG_TAG, "-  isIdle(): " + fgCall.isIdle());
1815        Log.d(LOG_TAG, "-  hasConnections: " + fgCall.hasConnections());
1816        Log.d(LOG_TAG, "-");
1817
1818        Call bgCall = phone.getBackgroundCall();
1819        Log.d(LOG_TAG, "- BG call: " + bgCall);
1820        Log.d(LOG_TAG, "-  state: " + bgCall.getState());
1821        Log.d(LOG_TAG, "-  isAlive(): " + bgCall.getState().isAlive());
1822        Log.d(LOG_TAG, "-  isRinging(): " + bgCall.getState().isRinging());
1823        Log.d(LOG_TAG, "-  isDialing(): " + bgCall.getState().isDialing());
1824        Log.d(LOG_TAG, "-  isIdle(): " + bgCall.isIdle());
1825        Log.d(LOG_TAG, "-  hasConnections: " + bgCall.hasConnections());
1826        Log.d(LOG_TAG, "-");
1827
1828        Call ringingCall = phone.getRingingCall();
1829        Log.d(LOG_TAG, "- RINGING call: " + ringingCall);
1830        Log.d(LOG_TAG, "-  state: " + ringingCall.getState());
1831        Log.d(LOG_TAG, "-  isAlive(): " + ringingCall.getState().isAlive());
1832        Log.d(LOG_TAG, "-  isRinging(): " + ringingCall.getState().isRinging());
1833        Log.d(LOG_TAG, "-  isDialing(): " + ringingCall.getState().isDialing());
1834        Log.d(LOG_TAG, "-  isIdle(): " + ringingCall.isIdle());
1835        Log.d(LOG_TAG, "-  hasConnections: " + ringingCall.hasConnections());
1836        Log.d(LOG_TAG, "-");
1837
1838        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1839        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1840        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1841        final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1842        Log.d(LOG_TAG, "- hasRingingCall: " + hasRingingCall);
1843        Log.d(LOG_TAG, "- hasActiveCall: " + hasActiveCall);
1844        Log.d(LOG_TAG, "- hasHoldingCall: " + hasHoldingCall);
1845        Log.d(LOG_TAG, "- allLinesTaken: " + allLinesTaken);
1846
1847        // Watch out: the isRinging() call below does NOT tell us anything
1848        // about the state of the telephony layer; it merely tells us whether
1849        // the Ringer manager is currently playing the ringtone.
1850        boolean ringing = PhoneApp.getInstance().getRinger().isRinging();
1851        Log.d(LOG_TAG, "- ringing (Ringer manager state): " + ringing);
1852        Log.d(LOG_TAG, "-----");
1853    }
1854
1855    private static void log(String msg) {
1856        Log.d(LOG_TAG, msg);
1857    }
1858}
1859