ImsPhoneCallTracker.java revision 4be56374921b52d54b80889540d982f39d26e3ab
1/*
2 * Copyright (C) 2013 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.internal.telephony.imsphone;
18
19import java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
22import java.util.List;
23
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.SharedPreferences;
30import android.os.AsyncResult;
31import android.os.Handler;
32import android.os.Message;
33import android.os.Registrant;
34import android.os.RegistrantList;
35import android.os.RemoteException;
36import android.os.SystemProperties;
37import android.provider.Settings;
38import android.preference.PreferenceManager;
39import android.telecom.ConferenceParticipant;
40import android.telecom.VideoProfile;
41import android.telephony.DisconnectCause;
42import android.telephony.PhoneNumberUtils;
43import android.telephony.Rlog;
44import android.telephony.ServiceState;
45
46import com.android.ims.ImsCall;
47import com.android.ims.ImsCallProfile;
48import com.android.ims.ImsConfig;
49import com.android.ims.ImsConnectionStateListener;
50import com.android.ims.ImsEcbm;
51import com.android.ims.ImsException;
52import com.android.ims.ImsManager;
53import com.android.ims.ImsReasonInfo;
54import com.android.ims.ImsServiceClass;
55import com.android.ims.ImsUtInterface;
56import com.android.ims.internal.IImsVideoCallProvider;
57import com.android.ims.internal.ImsVideoCallProviderWrapper;
58import com.android.internal.telephony.Call;
59import com.android.internal.telephony.CallStateException;
60import com.android.internal.telephony.CallTracker;
61import com.android.internal.telephony.CommandException;
62import com.android.internal.telephony.CommandsInterface;
63import com.android.internal.telephony.Connection;
64import com.android.internal.telephony.Phone;
65import com.android.internal.telephony.PhoneBase;
66import com.android.internal.telephony.PhoneConstants;
67import com.android.internal.telephony.TelephonyProperties;
68
69/**
70 * {@hide}
71 */
72public final class ImsPhoneCallTracker extends CallTracker {
73    static final String LOG_TAG = "ImsPhoneCallTracker";
74
75    private static final boolean DBG = true;
76
77    private boolean mIsVolteEnabled = false;
78    private boolean mIsVtEnabled = false;
79
80    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
81        @Override
82        public void onReceive(Context context, Intent intent) {
83            if (intent.getAction().equals(ImsManager.ACTION_IMS_INCOMING_CALL)) {
84                if (DBG) log("onReceive : incoming call intent");
85
86                if (mImsManager == null) return;
87
88                if (mServiceId < 0) return;
89
90                try {
91                    // Network initiated USSD will be treated by mImsUssdListener
92                    boolean isUssd = intent.getBooleanExtra(ImsManager.EXTRA_USSD, false);
93                    if (isUssd) {
94                        if (DBG) log("onReceive : USSD");
95                        mUssdSession = mImsManager.takeCall(mServiceId, intent, mImsUssdListener);
96                        if (mUssdSession != null) {
97                            mUssdSession.accept(ImsCallProfile.CALL_TYPE_VOICE);
98                        }
99                        return;
100                    }
101
102                    // Normal MT call
103                    ImsCall imsCall = mImsManager.takeCall(mServiceId, intent, mImsCallListener);
104                    ImsPhoneConnection conn = new ImsPhoneConnection(mPhone.getContext(), imsCall,
105                            ImsPhoneCallTracker.this, mRingingCall);
106                    addConnection(conn);
107
108                    IImsVideoCallProvider imsVideoCallProvider =
109                            imsCall.getCallSession().getVideoCallProvider();
110                    if (imsVideoCallProvider != null) {
111                        ImsVideoCallProviderWrapper imsVideoCallProviderWrapper =
112                                new ImsVideoCallProviderWrapper(imsVideoCallProvider);
113                        conn.setVideoProvider(imsVideoCallProviderWrapper);
114                    }
115
116                    if ((mForegroundCall.getState() != ImsPhoneCall.State.IDLE) ||
117                            (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE)) {
118                        conn.update(imsCall, ImsPhoneCall.State.WAITING);
119                    }
120
121                    mPhone.notifyNewRingingConnection(conn);
122                    mPhone.notifyIncomingRing();
123
124                    updatePhoneState();
125                    mPhone.notifyPreciseCallStateChanged();
126                } catch (ImsException e) {
127                    loge("onReceive : exception " + e);
128                } catch (RemoteException e) {
129                }
130            }
131        }
132    };
133
134    //***** Constants
135
136    static final int MAX_CONNECTIONS = 7;
137    static final int MAX_CONNECTIONS_PER_CALL = 5;
138
139    private static final int EVENT_HANGUP_PENDINGMO = 18;
140    private static final int EVENT_RESUME_BACKGROUND = 19;
141    private static final int EVENT_DIAL_PENDINGMO = 20;
142
143    private static final int TIMEOUT_HANGUP_PENDINGMO = 500;
144
145    //***** Instance Variables
146    private ArrayList<ImsPhoneConnection> mConnections = new ArrayList<ImsPhoneConnection>();
147    private RegistrantList mVoiceCallEndedRegistrants = new RegistrantList();
148    private RegistrantList mVoiceCallStartedRegistrants = new RegistrantList();
149
150    ImsPhoneCall mRingingCall = new ImsPhoneCall(this);
151    ImsPhoneCall mForegroundCall = new ImsPhoneCall(this);
152    ImsPhoneCall mBackgroundCall = new ImsPhoneCall(this);
153    ImsPhoneCall mHandoverCall = new ImsPhoneCall(this);
154
155    private ImsPhoneConnection mPendingMO;
156    private int mClirMode = CommandsInterface.CLIR_DEFAULT;
157    private Object mSyncHold = new Object();
158
159    private ImsCall mUssdSession = null;
160    private Message mPendingUssd = null;
161
162    ImsPhone mPhone;
163
164    private boolean mDesiredMute = false;    // false = mute off
165    private boolean mOnHoldToneStarted = false;
166
167    PhoneConstants.State mState = PhoneConstants.State.IDLE;
168
169    private ImsManager mImsManager;
170    private int mServiceId = -1;
171
172    private Call.SrvccState mSrvccState = Call.SrvccState.NONE;
173
174    private boolean mIsInEmergencyCall = false;
175
176    private int pendingCallClirMode;
177    private int pendingCallVideoState;
178    private boolean pendingCallInEcm = false;
179    private boolean mSwitchingFgAndBgCalls = false;
180    private ImsCall mCallExpectedToResume = null;
181
182    //***** Events
183
184
185    //***** Constructors
186
187    ImsPhoneCallTracker(ImsPhone phone) {
188        this.mPhone = phone;
189
190        IntentFilter intentfilter = new IntentFilter();
191        intentfilter.addAction(ImsManager.ACTION_IMS_INCOMING_CALL);
192        mPhone.getContext().registerReceiver(mReceiver, intentfilter);
193
194        Thread t = new Thread() {
195            public void run() {
196                getImsService();
197            }
198        };
199        t.start();
200    }
201
202    private PendingIntent createIncomingCallPendingIntent() {
203        Intent intent = new Intent(ImsManager.ACTION_IMS_INCOMING_CALL);
204        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
205        return PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
206                PendingIntent.FLAG_UPDATE_CURRENT);
207    }
208
209    private void getImsService() {
210        if (DBG) log("getImsService");
211        mImsManager = ImsManager.getInstance(mPhone.getContext(), mPhone.getPhoneId());
212        try {
213            mServiceId = mImsManager.open(ImsServiceClass.MMTEL,
214                    createIncomingCallPendingIntent(),
215                    mImsConnectionStateListener);
216
217            // Get the ECBM interface and set IMSPhone's listener object for notifications
218            getEcbmInterface().setEcbmStateListener(mPhone.mImsEcbmStateListener);
219            if (mPhone.isInEcm()) {
220                // Call exit ECBM which will invoke onECBMExited
221                mPhone.exitEmergencyCallbackMode();
222            }
223            int mPreferredTtyMode = Settings.Secure.getInt(
224                mPhone.getContext().getContentResolver(),
225                Settings.Secure.PREFERRED_TTY_MODE,
226                Phone.TTY_MODE_OFF);
227           mImsManager.setUiTTYMode(mServiceId, mPreferredTtyMode, null);
228
229        } catch (ImsException e) {
230            loge("getImsService: " + e);
231            //Leave mImsManager as null, then CallStateException will be thrown when dialing
232            mImsManager = null;
233        }
234    }
235
236    public void dispose() {
237        if (DBG) log("dispose");
238        mRingingCall.dispose();
239        mBackgroundCall.dispose();
240        mForegroundCall.dispose();
241        mHandoverCall.dispose();
242
243        clearDisconnected();
244        mPhone.getContext().unregisterReceiver(mReceiver);
245    }
246
247    @Override
248    protected void finalize() {
249        log("ImsPhoneCallTracker finalized");
250    }
251
252    //***** Instance Methods
253
254    //***** Public Methods
255    @Override
256    public void registerForVoiceCallStarted(Handler h, int what, Object obj) {
257        Registrant r = new Registrant(h, what, obj);
258        mVoiceCallStartedRegistrants.add(r);
259    }
260
261    @Override
262    public void unregisterForVoiceCallStarted(Handler h) {
263        mVoiceCallStartedRegistrants.remove(h);
264    }
265
266    @Override
267    public void registerForVoiceCallEnded(Handler h, int what, Object obj) {
268        Registrant r = new Registrant(h, what, obj);
269        mVoiceCallEndedRegistrants.add(r);
270    }
271
272    @Override
273    public void unregisterForVoiceCallEnded(Handler h) {
274        mVoiceCallEndedRegistrants.remove(h);
275    }
276
277    Connection
278    dial(String dialString, int videoState) throws CallStateException {
279        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
280        int oirMode = sp.getInt(PhoneBase.CLIR_KEY, CommandsInterface.CLIR_DEFAULT);
281        return dial(dialString, oirMode, videoState);
282    }
283
284    /**
285     * oirMode is one of the CLIR_ constants
286     */
287    synchronized Connection
288    dial(String dialString, int clirMode, int videoState) throws CallStateException {
289        boolean isPhoneInEcmMode = SystemProperties.getBoolean(
290                TelephonyProperties.PROPERTY_INECM_MODE, false);
291        boolean isEmergencyNumber = PhoneNumberUtils.isEmergencyNumber(dialString);
292
293        if (DBG) log("dial clirMode=" + clirMode);
294
295        // note that this triggers call state changed notif
296        clearDisconnected();
297
298        if (mImsManager == null) {
299            throw new CallStateException("service not available");
300        }
301
302        if (!canDial()) {
303            throw new CallStateException("cannot dial in current state");
304        }
305
306        if (isPhoneInEcmMode && isEmergencyNumber) {
307            handleEcmTimer(ImsPhone.CANCEL_ECM_TIMER);
308        }
309
310        boolean holdBeforeDial = false;
311
312        // The new call must be assigned to the foreground call.
313        // That call must be idle, so place anything that's
314        // there on hold
315        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
316            if (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE) {
317                //we should have failed in !canDial() above before we get here
318                throw new CallStateException("cannot dial in current state");
319            }
320            // foreground call is empty for the newly dialed connection
321            holdBeforeDial = true;
322            switchWaitingOrHoldingAndActive();
323        }
324
325        ImsPhoneCall.State fgState = ImsPhoneCall.State.IDLE;
326        ImsPhoneCall.State bgState = ImsPhoneCall.State.IDLE;
327
328        mClirMode = clirMode;
329
330        synchronized (mSyncHold) {
331            if (holdBeforeDial) {
332                fgState = mForegroundCall.getState();
333                bgState = mBackgroundCall.getState();
334
335                //holding foreground call failed
336                if (fgState == ImsPhoneCall.State.ACTIVE) {
337                    throw new CallStateException("cannot dial in current state");
338                }
339
340                //holding foreground call succeeded
341                if (bgState == ImsPhoneCall.State.HOLDING) {
342                    holdBeforeDial = false;
343                }
344            }
345
346            mPendingMO = new ImsPhoneConnection(mPhone.getContext(),
347                    checkForTestEmergencyNumber(dialString), this, mForegroundCall);
348        }
349        addConnection(mPendingMO);
350
351        if (!holdBeforeDial) {
352            if ((!isPhoneInEcmMode) || (isPhoneInEcmMode && isEmergencyNumber)) {
353                dialInternal(mPendingMO, clirMode, videoState);
354            } else {
355                try {
356                    getEcbmInterface().exitEmergencyCallbackMode();
357                } catch (ImsException e) {
358                    e.printStackTrace();
359                    throw new CallStateException("service not available");
360                }
361                mPhone.setOnEcbModeExitResponse(this, EVENT_EXIT_ECM_RESPONSE_CDMA, null);
362                pendingCallClirMode = clirMode;
363                pendingCallVideoState = videoState;
364                pendingCallInEcm = true;
365            }
366        }
367
368        updatePhoneState();
369        mPhone.notifyPreciseCallStateChanged();
370
371        return mPendingMO;
372    }
373
374    private void handleEcmTimer(int action) {
375        mPhone.handleTimerInEmergencyCallbackMode(action);
376        switch (action) {
377            case ImsPhone.CANCEL_ECM_TIMER:
378                break;
379            case ImsPhone.RESTART_ECM_TIMER:
380                break;
381            default:
382                log("handleEcmTimer, unsupported action " + action);
383        }
384    }
385
386    private void dialInternal(ImsPhoneConnection conn, int clirMode, int videoState) {
387        if (conn == null) {
388            return;
389        }
390
391        if (conn.getAddress()== null || conn.getAddress().length() == 0
392                || conn.getAddress().indexOf(PhoneNumberUtils.WILD) >= 0) {
393            // Phone number is invalid
394            conn.setDisconnectCause(DisconnectCause.INVALID_NUMBER);
395            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
396            return;
397        }
398
399        // Always unmute when initiating a new call
400        setMute(false);
401        int serviceType = PhoneNumberUtils.isEmergencyNumber(conn.getAddress()) ?
402                ImsCallProfile.SERVICE_TYPE_EMERGENCY : ImsCallProfile.SERVICE_TYPE_NORMAL;
403        int callType = ImsCallProfile.getCallTypeFromVideoState(videoState);
404        //TODO(vt): Is this sufficient?  At what point do we know the video state of the call?
405        conn.setVideoState(videoState);
406
407        try {
408            String[] callees = new String[] { conn.getAddress() };
409            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
410                    serviceType, callType);
411            profile.setCallExtraInt(ImsCallProfile.EXTRA_OIR, clirMode);
412
413            ImsCall imsCall = mImsManager.makeCall(mServiceId, profile,
414                    callees, mImsCallListener);
415            conn.setImsCall(imsCall);
416
417            IImsVideoCallProvider imsVideoCallProvider =
418                    imsCall.getCallSession().getVideoCallProvider();
419            if (imsVideoCallProvider != null) {
420                ImsVideoCallProviderWrapper imsVideoCallProviderWrapper =
421                        new ImsVideoCallProviderWrapper(imsVideoCallProvider);
422                conn.setVideoProvider(imsVideoCallProviderWrapper);
423            }
424        } catch (ImsException e) {
425            loge("dialInternal : " + e);
426            conn.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
427            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
428        } catch (RemoteException e) {
429        }
430    }
431
432    /**
433     * Accepts a call with the specified video state.  The video state is the video state that the
434     * user has agreed upon in the InCall UI.
435     *
436     * @param videoState The video State
437     * @throws CallStateException
438     */
439    void acceptCall (int videoState) throws CallStateException {
440        if (DBG) log("acceptCall");
441
442        if (mForegroundCall.getState().isAlive()
443                && mBackgroundCall.getState().isAlive()) {
444            throw new CallStateException("cannot accept call");
445        }
446
447        if ((mRingingCall.getState() == ImsPhoneCall.State.WAITING)
448                && mForegroundCall.getState().isAlive()) {
449            setMute(false);
450            switchWaitingOrHoldingAndActive();
451        } else if (mRingingCall.getState().isRinging()) {
452            if (DBG) log("acceptCall: incoming...");
453            // Always unmute when answering a new call
454            setMute(false);
455            try {
456                ImsCall imsCall = mRingingCall.getImsCall();
457                if (imsCall != null) {
458                    imsCall.accept(ImsCallProfile.getCallTypeFromVideoState(videoState));
459                } else {
460                    throw new CallStateException("no valid ims call");
461                }
462            } catch (ImsException e) {
463                throw new CallStateException("cannot accept call");
464            }
465        } else {
466            throw new CallStateException("phone not ringing");
467        }
468    }
469
470    void
471    rejectCall () throws CallStateException {
472        if (DBG) log("rejectCall");
473
474        if (mRingingCall.getState().isRinging()) {
475            hangup(mRingingCall);
476        } else {
477            throw new CallStateException("phone not ringing");
478        }
479    }
480
481    void
482    switchWaitingOrHoldingAndActive() throws CallStateException {
483        if (DBG) log("switchWaitingOrHoldingAndActive");
484
485        if (mRingingCall.getState() == ImsPhoneCall.State.INCOMING) {
486            throw new CallStateException("cannot be in the incoming state");
487        }
488
489        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
490            ImsCall imsCall = mForegroundCall.getImsCall();
491            if (imsCall == null) {
492                throw new CallStateException("no ims call");
493            }
494
495            // Swap the ImsCalls pointed to by the foreground and background ImsPhoneCalls.
496            // If hold or resume later fails, we will swap them back.
497            mSwitchingFgAndBgCalls = true;
498            mCallExpectedToResume = mBackgroundCall.getImsCall();
499            mForegroundCall.switchWith(mBackgroundCall);
500
501            // Hold the foreground call; once the foreground call is held, the background call will
502            // be resumed.
503            try {
504                imsCall.hold();
505            } catch (ImsException e) {
506                mForegroundCall.switchWith(mBackgroundCall);
507                throw new CallStateException(e.getMessage());
508            }
509        } else if (mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING) {
510            resumeWaitingOrHolding();
511        }
512    }
513
514    void
515    conference() {
516        if (DBG) log("conference");
517
518        ImsCall fgImsCall = mForegroundCall.getImsCall();
519        if (fgImsCall == null) {
520            log("conference no foreground ims call");
521            return;
522        }
523
524        ImsCall bgImsCall = mBackgroundCall.getImsCall();
525        if (bgImsCall == null) {
526            log("conference no background ims call");
527            return;
528        }
529
530        try {
531            fgImsCall.merge(bgImsCall);
532        } catch (ImsException e) {
533            log("conference " + e.getMessage());
534        }
535    }
536
537    void
538    explicitCallTransfer() {
539        //TODO : implement
540    }
541
542    void
543    clearDisconnected() {
544        if (DBG) log("clearDisconnected");
545
546        internalClearDisconnected();
547
548        updatePhoneState();
549        mPhone.notifyPreciseCallStateChanged();
550    }
551
552    boolean
553    canConference() {
554        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
555            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING
556            && !mBackgroundCall.isFull()
557            && !mForegroundCall.isFull();
558    }
559
560    boolean
561    canDial() {
562        boolean ret;
563        int serviceState = mPhone.getServiceState().getState();
564        String disableCall = SystemProperties.get(
565                TelephonyProperties.PROPERTY_DISABLE_CALL, "false");
566
567        ret = (serviceState != ServiceState.STATE_POWER_OFF)
568            && mPendingMO == null
569            && !mRingingCall.isRinging()
570            && !disableCall.equals("true")
571            && (!mForegroundCall.getState().isAlive()
572                    || !mBackgroundCall.getState().isAlive());
573
574        return ret;
575    }
576
577    boolean
578    canTransfer() {
579        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
580            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING;
581    }
582
583    //***** Private Instance Methods
584
585    private void
586    internalClearDisconnected() {
587        mRingingCall.clearDisconnected();
588        mForegroundCall.clearDisconnected();
589        mBackgroundCall.clearDisconnected();
590        mHandoverCall.clearDisconnected();
591    }
592
593    private void
594    updatePhoneState() {
595        PhoneConstants.State oldState = mState;
596
597        if (mRingingCall.isRinging()) {
598            mState = PhoneConstants.State.RINGING;
599        } else if (mPendingMO != null ||
600                !(mForegroundCall.isIdle() && mBackgroundCall.isIdle())) {
601            mState = PhoneConstants.State.OFFHOOK;
602        } else {
603            mState = PhoneConstants.State.IDLE;
604        }
605
606        if (mState == PhoneConstants.State.IDLE && oldState != mState) {
607            mVoiceCallEndedRegistrants.notifyRegistrants(
608                    new AsyncResult(null, null, null));
609        } else if (oldState == PhoneConstants.State.IDLE && oldState != mState) {
610            mVoiceCallStartedRegistrants.notifyRegistrants (
611                    new AsyncResult(null, null, null));
612        }
613
614        if (DBG) log("updatePhoneState oldState=" + oldState + ", newState=" + mState);
615
616        if (mState != oldState) {
617            mPhone.notifyPhoneStateChanged();
618        }
619    }
620
621    private void
622    handleRadioNotAvailable() {
623        // handlePollCalls will clear out its
624        // call list when it gets the CommandException
625        // error result from this
626        pollCallsWhenSafe();
627    }
628
629    private void
630    dumpState() {
631        List l;
632
633        log("Phone State:" + mState);
634
635        log("Ringing call: " + mRingingCall.toString());
636
637        l = mRingingCall.getConnections();
638        for (int i = 0, s = l.size(); i < s; i++) {
639            log(l.get(i).toString());
640        }
641
642        log("Foreground call: " + mForegroundCall.toString());
643
644        l = mForegroundCall.getConnections();
645        for (int i = 0, s = l.size(); i < s; i++) {
646            log(l.get(i).toString());
647        }
648
649        log("Background call: " + mBackgroundCall.toString());
650
651        l = mBackgroundCall.getConnections();
652        for (int i = 0, s = l.size(); i < s; i++) {
653            log(l.get(i).toString());
654        }
655
656    }
657
658    //***** Called from ImsPhone
659
660    void setUiTTYMode(int uiTtyMode, Message onComplete) {
661        try {
662            mImsManager.setUiTTYMode(mServiceId, uiTtyMode, onComplete);
663        } catch (ImsException e) {
664            loge("setTTYMode : " + e);
665            mPhone.sendErrorResponse(onComplete, e);
666        }
667    }
668
669    /*package*/ void
670    setMute(boolean mute) {
671        mDesiredMute = mute;
672        mForegroundCall.setMute(mute);
673    }
674
675    /*package*/ boolean
676    getMute() {
677        return mDesiredMute;
678    }
679
680    /*package*/ void
681    sendDtmf(char c) {
682        if (DBG) log("sendDtmf");
683
684        ImsCall imscall = mForegroundCall.getImsCall();
685        if (imscall != null) {
686            imscall.sendDtmf(c);
687        }
688    }
689
690    /*package*/ void
691    startDtmf(char c) {
692        if (DBG) log("startDtmf");
693
694        ImsCall imscall = mForegroundCall.getImsCall();
695        if (imscall != null) {
696            imscall.startDtmf(c);
697        } else {
698            loge("startDtmf : no foreground call");
699        }
700    }
701
702    /*package*/ void
703    stopDtmf() {
704        if (DBG) log("stopDtmf");
705
706        ImsCall imscall = mForegroundCall.getImsCall();
707        if (imscall != null) {
708            imscall.stopDtmf();
709        } else {
710            loge("stopDtmf : no foreground call");
711        }
712    }
713
714    //***** Called from ImsPhoneConnection
715
716    /*package*/ void
717    hangup (ImsPhoneConnection conn) throws CallStateException {
718        if (DBG) log("hangup connection");
719
720        if (conn.getOwner() != this) {
721            throw new CallStateException ("ImsPhoneConnection " + conn
722                    + "does not belong to ImsPhoneCallTracker " + this);
723        }
724
725        hangup(conn.getCall());
726    }
727
728    //***** Called from ImsPhoneCall
729
730    /* package */ void
731    hangup (ImsPhoneCall call) throws CallStateException {
732        if (DBG) log("hangup call");
733
734        if (call.getConnections().size() == 0) {
735            throw new CallStateException("no connections");
736        }
737
738        ImsCall imsCall = call.getImsCall();
739        boolean rejectCall = false;
740
741        if (call == mRingingCall) {
742            if (Phone.DEBUG_PHONE) log("(ringing) hangup incoming");
743            rejectCall = true;
744        } else if (call == mForegroundCall) {
745            if (call.isDialingOrAlerting()) {
746                if (Phone.DEBUG_PHONE) {
747                    log("(foregnd) hangup dialing or alerting...");
748                }
749            } else {
750                if (Phone.DEBUG_PHONE) {
751                    log("(foregnd) hangup foreground");
752                }
753                //held call will be resumed by onCallTerminated
754            }
755        } else if (call == mBackgroundCall) {
756            if (Phone.DEBUG_PHONE) {
757                log("(backgnd) hangup waiting or background");
758            }
759        } else {
760            throw new CallStateException ("ImsPhoneCall " + call +
761                    "does not belong to ImsPhoneCallTracker " + this);
762        }
763
764        call.onHangupLocal();
765
766        try {
767            if (imsCall != null) {
768                if (rejectCall) imsCall.reject(ImsReasonInfo.CODE_USER_DECLINE);
769                else imsCall.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
770            } else if (mPendingMO != null && call == mForegroundCall) {
771                // is holding a foreground call
772                mPendingMO.update(null, ImsPhoneCall.State.DISCONNECTED);
773                mPendingMO.onDisconnect();
774                removeConnection(mPendingMO);
775                mPendingMO = null;
776                updatePhoneState();
777                removeMessages(EVENT_DIAL_PENDINGMO);
778            }
779        } catch (ImsException e) {
780            throw new CallStateException(e.getMessage());
781        }
782
783        mPhone.notifyPreciseCallStateChanged();
784    }
785
786    /* package */
787    void resumeWaitingOrHolding() throws CallStateException {
788        if (DBG) log("resumeWaitingOrHolding");
789
790        try {
791            if (mForegroundCall.getState().isAlive()) {
792                //resume foreground call after holding background call
793                //they were switched before holding
794                ImsCall imsCall = mForegroundCall.getImsCall();
795                if (imsCall != null) imsCall.resume();
796            } else if (mRingingCall.getState() == ImsPhoneCall.State.WAITING) {
797                //accept waiting call after holding background call
798                ImsCall imsCall = mRingingCall.getImsCall();
799                if (imsCall != null) imsCall.accept(ImsCallProfile.CALL_TYPE_VOICE);
800            } else {
801                //Just resume background call.
802                //To distinguish resuming call with swapping calls
803                //we do not switch calls.here
804                //ImsPhoneConnection.update will chnage the parent when completed
805                ImsCall imsCall = mBackgroundCall.getImsCall();
806                if (imsCall != null) imsCall.resume();
807            }
808        } catch (ImsException e) {
809            throw new CallStateException(e.getMessage());
810        }
811    }
812
813    /* package */
814    void sendUSSD (String ussdString, Message response) {
815        if (DBG) log("sendUSSD");
816
817        try {
818            if (mUssdSession != null) {
819                mUssdSession.sendUssd(ussdString);
820                AsyncResult.forMessage(response, null, null);
821                response.sendToTarget();
822                return;
823            }
824
825            String[] callees = new String[] { ussdString };
826            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
827                    ImsCallProfile.SERVICE_TYPE_NORMAL, ImsCallProfile.CALL_TYPE_VOICE);
828            profile.setCallExtraInt(ImsCallProfile.EXTRA_DIALSTRING,
829                    ImsCallProfile.DIALSTRING_USSD);
830
831            mUssdSession = mImsManager.makeCall(mServiceId, profile,
832                    callees, mImsUssdListener);
833        } catch (ImsException e) {
834            loge("sendUSSD : " + e);
835            mPhone.sendErrorResponse(response, e);
836        }
837    }
838
839    /* package */
840    void cancelUSSD() {
841        if (mUssdSession == null) return;
842
843        try {
844            mUssdSession.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
845        } catch (ImsException e) {
846        }
847
848    }
849
850    private synchronized ImsPhoneConnection findConnection(ImsCall imsCall) {
851        for (ImsPhoneConnection conn : mConnections) {
852            if (conn.getImsCall() == imsCall) {
853                return conn;
854            }
855        }
856        return null;
857    }
858
859    private synchronized void removeConnection(ImsPhoneConnection conn) {
860        mConnections.remove(conn);
861    }
862
863    private synchronized void addConnection(ImsPhoneConnection conn) {
864        mConnections.add(conn);
865    }
866
867    private void processCallStateChange(ImsCall imsCall, ImsPhoneCall.State state, int cause) {
868        if (DBG) log("processCallStateChange " + imsCall + " state=" + state + " cause=" + cause);
869
870        if (imsCall == null) return;
871
872        boolean changed = false;
873        ImsPhoneConnection conn = findConnection(imsCall);
874
875        if (conn == null) {
876            // TODO : what should be done?
877            return;
878        }
879
880        changed = conn.update(imsCall, state);
881
882        if (state == ImsPhoneCall.State.DISCONNECTED) {
883            changed = conn.onDisconnect(cause) || changed;
884            removeConnection(conn);
885        }
886
887        if (changed) {
888            if (conn.getCall() == mHandoverCall) return;
889            updatePhoneState();
890            mPhone.notifyPreciseCallStateChanged();
891        }
892    }
893
894    private int getDisconnectCauseFromReasonInfo(ImsReasonInfo reasonInfo) {
895        int cause = DisconnectCause.ERROR_UNSPECIFIED;
896
897        //int type = reasonInfo.getReasonType();
898        int code = reasonInfo.getCode();
899        switch (code) {
900            case ImsReasonInfo.CODE_SIP_BAD_ADDRESS:
901            case ImsReasonInfo.CODE_SIP_NOT_REACHABLE:
902                return DisconnectCause.NUMBER_UNREACHABLE;
903
904            case ImsReasonInfo.CODE_SIP_BUSY:
905                return DisconnectCause.BUSY;
906
907            case ImsReasonInfo.CODE_USER_TERMINATED:
908                return DisconnectCause.LOCAL;
909
910            case ImsReasonInfo.CODE_LOCAL_CALL_DECLINE:
911                return DisconnectCause.INCOMING_REJECTED;
912
913            case ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE:
914                return DisconnectCause.NORMAL;
915
916            case ImsReasonInfo.CODE_SIP_REDIRECTED:
917            case ImsReasonInfo.CODE_SIP_BAD_REQUEST:
918            case ImsReasonInfo.CODE_SIP_FORBIDDEN:
919            case ImsReasonInfo.CODE_SIP_NOT_ACCEPTABLE:
920            case ImsReasonInfo.CODE_SIP_USER_REJECTED:
921            case ImsReasonInfo.CODE_SIP_GLOBAL_ERROR:
922                return DisconnectCause.SERVER_ERROR;
923
924            case ImsReasonInfo.CODE_SIP_SERVICE_UNAVAILABLE:
925            case ImsReasonInfo.CODE_SIP_NOT_FOUND:
926            case ImsReasonInfo.CODE_SIP_SERVER_ERROR:
927                return DisconnectCause.SERVER_UNREACHABLE;
928
929            case ImsReasonInfo.CODE_LOCAL_NETWORK_ROAMING:
930            case ImsReasonInfo.CODE_LOCAL_NETWORK_IP_CHANGED:
931            case ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN:
932            case ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE:
933            case ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED:
934            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_LTE_COVERAGE:
935            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_SERVICE:
936            case ImsReasonInfo.CODE_LOCAL_CALL_VCC_ON_PROGRESSING:
937                return DisconnectCause.OUT_OF_SERVICE;
938
939            case ImsReasonInfo.CODE_SIP_REQUEST_TIMEOUT:
940            case ImsReasonInfo.CODE_TIMEOUT_1XX_WAITING:
941            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER:
942            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER_CALL_UPDATE:
943                return DisconnectCause.TIMED_OUT;
944
945            case ImsReasonInfo.CODE_LOCAL_LOW_BATTERY:
946            case ImsReasonInfo.CODE_LOCAL_POWER_OFF:
947                return DisconnectCause.POWER_OFF;
948
949            default:
950        }
951
952        return cause;
953    }
954
955    /**
956     * Listen to the IMS call state change
957     */
958    private ImsCall.Listener mImsCallListener = new ImsCall.Listener() {
959        @Override
960        public void onCallProgressing(ImsCall imsCall) {
961            if (DBG) log("onCallProgressing");
962
963            mPendingMO = null;
964            processCallStateChange(imsCall, ImsPhoneCall.State.ALERTING,
965                    DisconnectCause.NOT_DISCONNECTED);
966        }
967
968        @Override
969        public void onCallStarted(ImsCall imsCall) {
970            if (DBG) log("onCallStarted");
971
972            mPendingMO = null;
973            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
974                    DisconnectCause.NOT_DISCONNECTED);
975        }
976
977        /**
978         * onCallStartFailed will be invoked when:
979         * case 1) Dialing fails
980         * case 2) Ringing call is disconnected by local or remote user
981         */
982        @Override
983        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
984            if (DBG) log("onCallStartFailed reasonCode=" + reasonInfo.getCode());
985
986            if (mPendingMO != null) {
987                // To initiate dialing circuit-switched call
988                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_CS_RETRY_REQUIRED
989                        && mBackgroundCall.getState() == ImsPhoneCall.State.IDLE
990                        && mRingingCall.getState() == ImsPhoneCall.State.IDLE) {
991                    mForegroundCall.detach(mPendingMO);
992                    removeConnection(mPendingMO);
993                    mPendingMO.finalize();
994                    mPendingMO = null;
995                    mPhone.initiateSilentRedial();
996                    return;
997                }
998                mPendingMO = null;
999            }
1000        }
1001
1002        @Override
1003        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1004            if (DBG) log("onCallTerminated reasonCode=" + reasonInfo.getCode());
1005
1006            ImsPhoneCall.State oldState = mForegroundCall.getState();
1007            int cause = getDisconnectCauseFromReasonInfo(reasonInfo);
1008            ImsPhoneConnection conn = findConnection(imsCall);
1009            if (DBG) log("cause = " + cause + " conn = " + conn);
1010
1011            if (conn != null && conn.isIncoming() && conn.getConnectTime() == 0) {
1012                // Missed
1013                if (cause == DisconnectCause.NORMAL) {
1014                    cause = DisconnectCause.INCOMING_MISSED;
1015                }
1016                if (DBG) log("Incoming connection of 0 connect time detected - translated cause = "
1017                        + cause);
1018
1019            }
1020
1021            if (cause == DisconnectCause.NORMAL && conn != null && conn.getImsCall().isMerged()) {
1022                // Call was terminated while it is merged instead of a remote disconnect.
1023                cause = DisconnectCause.IMS_MERGED_SUCCESSFULLY;
1024            }
1025
1026            processCallStateChange(imsCall, ImsPhoneCall.State.DISCONNECTED, cause);
1027        }
1028
1029        @Override
1030        public void onCallHeld(ImsCall imsCall) {
1031            if (DBG) log("onCallHeld");
1032
1033            synchronized (mSyncHold) {
1034                ImsPhoneCall.State oldState = mBackgroundCall.getState();
1035                processCallStateChange(imsCall, ImsPhoneCall.State.HOLDING,
1036                        DisconnectCause.NOT_DISCONNECTED);
1037                if (oldState == ImsPhoneCall.State.ACTIVE) {
1038                    // Note: This case comes up when we have just held a call in response to a
1039                    // switchWaitingOrHoldingAndActive.  We now need to resume the background call.
1040                    // The EVENT_RESUME_BACKGROUND causes resumeWaitingOrHolding to be called.
1041                    if ((mForegroundCall.getState() == ImsPhoneCall.State.HOLDING)
1042                            || (mRingingCall.getState() == ImsPhoneCall.State.WAITING)) {
1043
1044                            sendEmptyMessage(EVENT_RESUME_BACKGROUND);
1045                    } else {
1046                        //when multiple connections belong to background call,
1047                        //only the first callback reaches here
1048                        //otherwise the oldState is already HOLDING
1049                        if (mPendingMO != null) {
1050                            sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1051                        }
1052                    }
1053                }
1054            }
1055        }
1056
1057        @Override
1058        public void onCallHoldFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1059            if (DBG) log("onCallHoldFailed reasonCode=" + reasonInfo.getCode());
1060
1061            synchronized (mSyncHold) {
1062                ImsPhoneCall.State bgState = mBackgroundCall.getState();
1063                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_TERMINATED) {
1064                    // disconnected while processing hold
1065                    if (mPendingMO != null) {
1066                        sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1067                    }
1068                } else if (bgState == ImsPhoneCall.State.ACTIVE) {
1069                    mForegroundCall.switchWith(mBackgroundCall);
1070
1071                    if (mPendingMO != null) {
1072                        mPendingMO.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
1073                        sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
1074                    }
1075                }
1076            }
1077        }
1078
1079        @Override
1080        public void onCallResumed(ImsCall imsCall) {
1081            if (DBG) log("onCallResumed");
1082
1083            // If we are the in midst of swapping FG and BG calls and the call we end up resuming
1084            // is not the one we expected, we likely had a resume failure and we need to swap the
1085            // FG and BG calls back.
1086            if (mSwitchingFgAndBgCalls && imsCall != mCallExpectedToResume) {
1087                mForegroundCall.switchWith(mBackgroundCall);
1088                mSwitchingFgAndBgCalls = false;
1089                mCallExpectedToResume = null;
1090            }
1091            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
1092                    DisconnectCause.NOT_DISCONNECTED);
1093        }
1094
1095        @Override
1096        public void onCallResumeFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1097            // TODO : What should be done?
1098            // If we are in the midst of swapping the FG and BG calls and we got a resume fail, we
1099            // need to swap back the FG and BG calls.
1100            if (mSwitchingFgAndBgCalls && imsCall == mCallExpectedToResume) {
1101                mForegroundCall.switchWith(mBackgroundCall);
1102                mCallExpectedToResume = null;
1103                mSwitchingFgAndBgCalls = false;
1104            }
1105            mPhone.notifySuppServiceFailed(Phone.SuppService.RESUME);
1106        }
1107
1108        @Override
1109        public void onCallResumeReceived(ImsCall imsCall) {
1110            if (DBG) log("onCallResumeReceived");
1111
1112            if (mOnHoldToneStarted) {
1113                mPhone.stopOnHoldTone();
1114                mOnHoldToneStarted = false;
1115            }
1116        }
1117
1118        @Override
1119        public void onCallHoldReceived(ImsCall imsCall) {
1120            if (DBG) log("onCallHoldReceived");
1121
1122            ImsPhoneConnection conn = findConnection(imsCall);
1123            if (conn != null && conn.getState() == ImsPhoneCall.State.ACTIVE) {
1124                if (!mOnHoldToneStarted && ImsPhoneCall.isLocalTone(imsCall)) {
1125                    mPhone.startOnHoldTone();
1126                    mOnHoldToneStarted = true;
1127                }
1128            }
1129        }
1130
1131        @Override
1132        public void onCallMerged(ImsCall call) {
1133            if (DBG) log("onCallMerged");
1134
1135            mForegroundCall.merge(mBackgroundCall, mForegroundCall.getState());
1136            updatePhoneState();
1137            mPhone.notifyPreciseCallStateChanged();
1138        }
1139
1140        @Override
1141        public void onCallMergeFailed(ImsCall call, ImsReasonInfo reasonInfo) {
1142            if (DBG) log("onCallMergeFailed reasonInfo=" + reasonInfo);
1143            mPhone.notifySuppServiceFailed(Phone.SuppService.CONFERENCE);
1144        }
1145
1146        /**
1147         * Called when the state of IMS conference participant(s) has changed.
1148         *
1149         * @param call the call object that carries out the IMS call.
1150         * @param participants the participant(s) and their new state information.
1151         */
1152        @Override
1153        public void onConferenceParticipantsStateChanged(ImsCall call,
1154                List<ConferenceParticipant> participants) {
1155            if (DBG) log("onConferenceParticipantsStateChanged");
1156
1157            ImsPhoneConnection conn = findConnection(call);
1158            if (conn != null) {
1159                conn.updateConferenceParticipants(participants);
1160            }
1161        }
1162    };
1163
1164    /**
1165     * Listen to the IMS call state change
1166     */
1167    private ImsCall.Listener mImsUssdListener = new ImsCall.Listener() {
1168        @Override
1169        public void onCallStarted(ImsCall imsCall) {
1170            if (DBG) log("mImsUssdListener onCallStarted");
1171
1172            if (imsCall == mUssdSession) {
1173                if (mPendingUssd != null) {
1174                    AsyncResult.forMessage(mPendingUssd);
1175                    mPendingUssd.sendToTarget();
1176                    mPendingUssd = null;
1177                }
1178            }
1179        }
1180
1181        @Override
1182        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1183            if (DBG) log("mImsUssdListener onCallStartFailed reasonCode=" + reasonInfo.getCode());
1184
1185            onCallTerminated(imsCall, reasonInfo);
1186        }
1187
1188        @Override
1189        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1190            if (DBG) log("mImsUssdListener onCallTerminated reasonCode=" + reasonInfo.getCode());
1191
1192            if (imsCall == mUssdSession) {
1193                mUssdSession = null;
1194                if (mPendingUssd != null) {
1195                    CommandException ex =
1196                            new CommandException(CommandException.Error.GENERIC_FAILURE);
1197                    AsyncResult.forMessage(mPendingUssd, null, ex);
1198                    mPendingUssd.sendToTarget();
1199                    mPendingUssd = null;
1200                }
1201            }
1202            imsCall.close();
1203        }
1204
1205        @Override
1206        public void onCallUssdMessageReceived(ImsCall call,
1207                int mode, String ussdMessage) {
1208            if (DBG) log("mImsUssdListener onCallUssdMessageReceived mode=" + mode);
1209
1210            int ussdMode = -1;
1211
1212            switch(mode) {
1213                case ImsCall.USSD_MODE_REQUEST:
1214                    ussdMode = CommandsInterface.USSD_MODE_REQUEST;
1215                    break;
1216
1217                case ImsCall.USSD_MODE_NOTIFY:
1218                    ussdMode = CommandsInterface.USSD_MODE_NOTIFY;
1219                    break;
1220            }
1221
1222            mPhone.onIncomingUSSD(ussdMode, ussdMessage);
1223        }
1224    };
1225
1226    /**
1227     * Listen to the IMS service state change
1228     *
1229     */
1230    private ImsConnectionStateListener mImsConnectionStateListener =
1231        new ImsConnectionStateListener() {
1232        @Override
1233        public void onImsConnected() {
1234            if (DBG) log("onImsConnected");
1235            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1236        }
1237
1238        @Override
1239        public void onImsDisconnected() {
1240            if (DBG) log("onImsDisconnected");
1241            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1242        }
1243
1244        @Override
1245        public void onImsResumed() {
1246            if (DBG) log("onImsResumed");
1247            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1248        }
1249
1250        @Override
1251        public void onImsSuspended() {
1252            if (DBG) log("onImsSuspended");
1253            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1254        }
1255
1256        @Override
1257        public void onFeatureCapabilityChanged(int serviceClass,
1258                int[] enabledFeatures, int[] disabledFeatures) {
1259            if (serviceClass == ImsServiceClass.MMTEL) {
1260                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1261                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1262                    mIsVolteEnabled = true;
1263                }
1264                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1265                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1266                    mIsVtEnabled = true;
1267                }
1268                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1269                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1270                    mIsVolteEnabled = false;
1271                }
1272                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1273                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1274                    mIsVtEnabled = false;
1275                }
1276            }
1277            if (DBG) log("onFeatureCapabilityChanged, mIsVolteEnabled = " +  mIsVolteEnabled
1278                    + " mIsVtEnabled = " + mIsVtEnabled);
1279        }
1280    };
1281
1282    /* package */
1283    ImsUtInterface getUtInterface() throws ImsException {
1284        if (mImsManager == null) {
1285            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1286        }
1287
1288        ImsUtInterface ut = mImsManager.getSupplementaryServiceConfiguration(mServiceId);
1289        return ut;
1290    }
1291
1292    private void transferHandoverConnections(ImsPhoneCall call) {
1293        if (call.mConnections != null) {
1294            for (Connection c : call.mConnections) {
1295                c.mPreHandoverState = call.mState;
1296                log ("Connection state before handover is " + c.getStateBeforeHandover());
1297            }
1298        }
1299        if (mHandoverCall.mConnections == null ) {
1300            mHandoverCall.mConnections = call.mConnections;
1301        } else { // Multi-call SRVCC
1302            mHandoverCall.mConnections.addAll(call.mConnections);
1303        }
1304        if (mHandoverCall.mConnections != null) {
1305            if (call.getImsCall() != null) {
1306                call.getImsCall().close();
1307            }
1308            for (Connection c : mHandoverCall.mConnections) {
1309                ((ImsPhoneConnection)c).changeParent(mHandoverCall);
1310            }
1311        }
1312        if (call.getState().isAlive()) {
1313            log ("Call is alive and state is " + call.mState);
1314            mHandoverCall.mState = call.mState;
1315        }
1316        call.mConnections.clear();
1317        call.mState = ImsPhoneCall.State.IDLE;
1318    }
1319
1320    /* package */
1321    void notifySrvccState(Call.SrvccState state) {
1322        if (DBG) log("notifySrvccState state=" + state);
1323
1324        mSrvccState = state;
1325
1326        if (mSrvccState == Call.SrvccState.COMPLETED) {
1327            transferHandoverConnections(mForegroundCall);
1328            transferHandoverConnections(mBackgroundCall);
1329            transferHandoverConnections(mRingingCall);
1330            // release wake lock hold
1331            ImsPhoneConnection con = mHandoverCall.getHandoverConnection();
1332            if (con != null) {
1333                con.releaseWakeLock();
1334            }
1335        }
1336    }
1337
1338    //****** Overridden from Handler
1339
1340    @Override
1341    public void
1342    handleMessage (Message msg) {
1343        AsyncResult ar;
1344        if (DBG) log("handleMessage what=" + msg.what);
1345
1346        switch (msg.what) {
1347            case EVENT_HANGUP_PENDINGMO:
1348                if (mPendingMO != null) {
1349                    mPendingMO.onDisconnect();
1350                    removeConnection(mPendingMO);
1351                    mPendingMO = null;
1352                }
1353
1354                updatePhoneState();
1355                mPhone.notifyPreciseCallStateChanged();
1356                break;
1357            case EVENT_RESUME_BACKGROUND:
1358                try {
1359                    resumeWaitingOrHolding();
1360                } catch (CallStateException e) {
1361                    if (Phone.DEBUG_PHONE) {
1362                        loge("handleMessage EVENT_RESUME_BACKGROUND exception=" + e);
1363                    }
1364                }
1365                break;
1366            case EVENT_DIAL_PENDINGMO:
1367                dialInternal(mPendingMO, mClirMode, VideoProfile.VideoState.AUDIO_ONLY);
1368                break;
1369
1370            case EVENT_EXIT_ECM_RESPONSE_CDMA:
1371                // no matter the result, we still do the same here
1372                if (pendingCallInEcm) {
1373                    dialInternal(mPendingMO, pendingCallClirMode, pendingCallVideoState);
1374                    pendingCallInEcm = false;
1375                }
1376                mPhone.unsetOnEcbModeExitResponse(this);
1377                break;
1378        }
1379    }
1380
1381    @Override
1382    protected void log(String msg) {
1383        Rlog.d(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1384    }
1385
1386    protected void loge(String msg) {
1387        Rlog.e(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1388    }
1389
1390    @Override
1391    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1392        pw.println("ImsPhoneCallTracker extends:");
1393        super.dump(fd, pw, args);
1394        pw.println(" mVoiceCallEndedRegistrants=" + mVoiceCallEndedRegistrants);
1395        pw.println(" mVoiceCallStartedRegistrants=" + mVoiceCallStartedRegistrants);
1396        pw.println(" mRingingCall=" + mRingingCall);
1397        pw.println(" mForegroundCall=" + mForegroundCall);
1398        pw.println(" mBackgroundCall=" + mBackgroundCall);
1399        pw.println(" mHandoverCall=" + mHandoverCall);
1400        pw.println(" mPendingMO=" + mPendingMO);
1401        //pw.println(" mHangupPendingMO=" + mHangupPendingMO);
1402        pw.println(" mPhone=" + mPhone);
1403        pw.println(" mDesiredMute=" + mDesiredMute);
1404        pw.println(" mState=" + mState);
1405    }
1406
1407    @Override
1408    protected void handlePollCalls(AsyncResult ar) {
1409    }
1410
1411    /* package */
1412    ImsEcbm getEcbmInterface() throws ImsException {
1413        if (mImsManager == null) {
1414            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1415        }
1416
1417        ImsEcbm ecbm = mImsManager.getEcbmInterface(mServiceId);
1418        return ecbm;
1419    }
1420
1421    public boolean isInEmergencyCall() {
1422        return mIsInEmergencyCall;
1423    }
1424
1425    public boolean isVolteEnabled() {
1426        return mIsVolteEnabled;
1427    }
1428
1429    public boolean isVtEnabled() {
1430        return mIsVtEnabled;
1431    }
1432}
1433