InCallPresenter.java revision 9044e6296320cac2ee7c49465fdbb4a55912058a
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.incallui;
18
19import android.content.Context;
20import android.content.Intent;
21import android.telecomm.CallCapabilities;
22import android.telecomm.Phone;
23import android.telecomm.PhoneAccount;
24import android.telecomm.VideoCallProfile;
25
26import com.google.common.base.Preconditions;
27import com.google.common.collect.Sets;
28import com.google.common.collect.Lists;
29
30import java.util.ArrayList;
31import java.util.Set;
32
33/**
34 * Takes updates from the CallList and notifies the InCallActivity (UI)
35 * of the changes.
36 * Responsible for starting the activity for a new call and finishing the activity when all calls
37 * are disconnected.
38 * Creates and manages the in-call state and provides a listener pattern for the presenters
39 * that want to listen in on the in-call state changes.
40 * TODO: This class has become more of a state machine at this point.  Consider renaming.
41 */
42public class InCallPresenter implements CallList.Listener, InCallPhoneListener {
43
44    private static InCallPresenter sInCallPresenter;
45
46    private final Set<InCallStateListener> mListeners = Sets.newHashSet();
47    private final ArrayList<IncomingCallListener> mIncomingCallListeners = Lists.newArrayList();
48
49    private AudioModeProvider mAudioModeProvider;
50    private StatusBarNotifier mStatusBarNotifier;
51    private ContactInfoCache mContactInfoCache;
52    private Context mContext;
53    private CallList mCallList;
54    private InCallActivity mInCallActivity;
55    private InCallState mInCallState = InCallState.NO_CALLS;
56    private ProximitySensor mProximitySensor;
57    private boolean mServiceConnected = false;
58    private boolean mAccountSelectionCancelled = false;
59
60    private final Phone.Listener mPhoneListener = new Phone.Listener() {
61        @Override
62        public void onBringToForeground(Phone phone, boolean showDialpad) {
63            Log.i(this, "Bringing UI to foreground.");
64            bringToForeground(showDialpad);
65        }
66        @Override
67        public void onCallAdded(Phone phone, android.telecomm.Call call) {
68            call.addListener(mCallListener);
69        }
70        @Override
71        public void onCallRemoved(Phone phone, android.telecomm.Call call) {
72            call.removeListener(mCallListener);
73        }
74    };
75
76    private final android.telecomm.Call.Listener mCallListener =
77            new android.telecomm.Call.Listener() {
78        @Override
79        public void onPostDialWait(android.telecomm.Call call, String remainingPostDialSequence) {
80            onPostDialCharWait(
81                    CallList.getInstance().getCallByTelecommCall(call).getId(),
82                    remainingPostDialSequence);
83        }
84    };
85
86    /**
87     * Is true when the activity has been previously started. Some code needs to know not just if
88     * the activity is currently up, but if it had been previously shown in foreground for this
89     * in-call session (e.g., StatusBarNotifier). This gets reset when the session ends in the
90     * tear-down method.
91     */
92    private boolean mIsActivityPreviouslyStarted = false;
93
94    private Phone mPhone;
95
96    public static synchronized InCallPresenter getInstance() {
97        if (sInCallPresenter == null) {
98            sInCallPresenter = new InCallPresenter();
99        }
100        return sInCallPresenter;
101    }
102
103    @Override
104    public void setPhone(Phone phone) {
105        mPhone = phone;
106        mPhone.addListener(mPhoneListener);
107    }
108
109    @Override
110    public void clearPhone() {
111        mPhone.removeListener(mPhoneListener);
112        mPhone = null;
113    }
114
115    public InCallState getInCallState() {
116        return mInCallState;
117    }
118
119    public CallList getCallList() {
120        return mCallList;
121    }
122
123    public void setUp(Context context, CallList callList, AudioModeProvider audioModeProvider) {
124        if (mServiceConnected) {
125            Log.i(this, "New service connection replacing existing one.");
126            // retain the current resources, no need to create new ones.
127            Preconditions.checkState(context == mContext);
128            Preconditions.checkState(callList == mCallList);
129            Preconditions.checkState(audioModeProvider == mAudioModeProvider);
130            return;
131        }
132
133        Preconditions.checkNotNull(context);
134        mContext = context;
135
136        mContactInfoCache = ContactInfoCache.getInstance(context);
137
138        mStatusBarNotifier = new StatusBarNotifier(context, mContactInfoCache);
139        addListener(mStatusBarNotifier);
140
141        mAudioModeProvider = audioModeProvider;
142
143        mProximitySensor = new ProximitySensor(context, mAudioModeProvider);
144        addListener(mProximitySensor);
145
146        mCallList = callList;
147
148        // This only gets called by the service so this is okay.
149        mServiceConnected = true;
150
151        // The final thing we do in this set up is add ourselves as a listener to CallList.  This
152        // will kick off an update and the whole process can start.
153        mCallList.addListener(this);
154
155        Log.d(this, "Finished InCallPresenter.setUp");
156    }
157
158    /**
159     * Called when the telephony service has disconnected from us.  This will happen when there are
160     * no more active calls. However, we may still want to continue showing the UI for
161     * certain cases like showing "Call Ended".
162     * What we really want is to wait for the activity and the service to both disconnect before we
163     * tear things down. This method sets a serviceConnected boolean and calls a secondary method
164     * that performs the aforementioned logic.
165     */
166    public void tearDown() {
167        Log.d(this, "tearDown");
168        mServiceConnected = false;
169        attemptCleanup();
170    }
171
172    private void attemptFinishActivity() {
173        final boolean doFinish = (mInCallActivity != null && isActivityStarted());
174        Log.i(this, "Hide in call UI: " + doFinish);
175
176        if (doFinish) {
177            mInCallActivity.finish();
178
179            if (mAccountSelectionCancelled) {
180                // This finish is a result of account selection cancellation
181                // do not include activity ending transition
182                mInCallActivity.overridePendingTransition(0, 0);
183            }
184        }
185    }
186
187    /**
188     * Called when the UI begins or ends. Starts the callstate callbacks if the UI just began.
189     * Attempts to tear down everything if the UI just ended. See #tearDown for more insight on
190     * the tear-down process.
191     */
192    public void setActivity(InCallActivity inCallActivity) {
193        boolean updateListeners = false;
194        boolean doAttemptCleanup = false;
195
196        if (inCallActivity != null) {
197            if (mInCallActivity == null) {
198                updateListeners = true;
199                Log.i(this, "UI Initialized");
200            } else if (mInCallActivity != inCallActivity) {
201                Log.wtf(this, "Setting a second activity before destroying the first.");
202            } else {
203                // since setActivity is called onStart(), it can be called multiple times.
204                // This is fine and ignorable, but we do not want to update the world every time
205                // this happens (like going to/from background) so we do not set updateListeners.
206            }
207
208            mInCallActivity = inCallActivity;
209
210            // By the time the UI finally comes up, the call may already be disconnected.
211            // If that's the case, we may need to show an error dialog.
212            if (mCallList != null && mCallList.getDisconnectedCall() != null) {
213                maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
214            }
215
216            // When the UI comes up, we need to first check the in-call state.
217            // If we are showing NO_CALLS, that means that a call probably connected and
218            // then immediately disconnected before the UI was able to come up.
219            // If we dont have any calls, start tearing down the UI instead.
220            // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
221            // it has been set.
222            if (mInCallState == InCallState.NO_CALLS) {
223                Log.i(this, "UI Intialized, but no calls left.  shut down.");
224                attemptFinishActivity();
225                return;
226            }
227        } else {
228            Log.i(this, "UI Destroyed)");
229            updateListeners = true;
230            mInCallActivity = null;
231
232            // We attempt cleanup for the destroy case but only after we recalculate the state
233            // to see if we need to come back up or stay shut down. This is why we do the cleanup
234            // after the call to onCallListChange() instead of directly here.
235            doAttemptCleanup = true;
236        }
237
238        // Messages can come from the telephony layer while the activity is coming up
239        // and while the activity is going down.  So in both cases we need to recalculate what
240        // state we should be in after they complete.
241        // Examples: (1) A new incoming call could come in and then get disconnected before
242        //               the activity is created.
243        //           (2) All calls could disconnect and then get a new incoming call before the
244        //               activity is destroyed.
245        //
246        // b/1122139 - We previously had a check for mServiceConnected here as well, but there are
247        // cases where we need to recalculate the current state even if the service in not
248        // connected.  In particular the case where startOrFinish() is called while the app is
249        // already finish()ing. In that case, we skip updating the state with the knowledge that
250        // we will check again once the activity has finished. That means we have to recalculate the
251        // state here even if the service is disconnected since we may not have finished a state
252        // transition while finish()ing.
253        if (updateListeners) {
254            onCallListChange(mCallList);
255        }
256
257        if (doAttemptCleanup) {
258            attemptCleanup();
259        }
260    }
261
262    /**
263     * Called when there is a change to the call list.
264     * Sets the In-Call state for the entire in-call app based on the information it gets from
265     * CallList. Dispatches the in-call state to all listeners. Can trigger the creation or
266     * destruction of the UI based on the states that is calculates.
267     */
268    @Override
269    public void onCallListChange(CallList callList) {
270        if (callList == null) {
271            return;
272        }
273        InCallState newState = getPotentialStateFromCallList(callList);
274        newState = startOrFinishUi(newState);
275
276        // Set the new state before announcing it to the world
277        Log.i(this, "Phone switching state: " + mInCallState + " -> " + newState);
278        mInCallState = newState;
279
280        // notify listeners of new state
281        for (InCallStateListener listener : mListeners) {
282            Log.d(this, "Notify " + listener + " of state " + mInCallState.toString());
283            listener.onStateChange(mInCallState, callList);
284        }
285
286        if (isActivityStarted()) {
287            final boolean hasCall = callList.getActiveOrBackgroundCall() != null ||
288                    callList.getOutgoingCall() != null;
289            mInCallActivity.dismissKeyguard(hasCall);
290        }
291    }
292
293    /**
294     * Called when there is a new incoming call.
295     *
296     * @param call
297     */
298    @Override
299    public void onIncomingCall(Call call) {
300        InCallState newState = startOrFinishUi(InCallState.INCOMING);
301
302        Log.i(this, "Phone switching state: " + mInCallState + " -> " + newState);
303        mInCallState = newState;
304
305        for (IncomingCallListener listener : mIncomingCallListeners) {
306            listener.onIncomingCall(mInCallState, call);
307        }
308    }
309
310    /**
311     * Called when a call becomes disconnected. Called everytime an existing call
312     * changes from being connected (incoming/outgoing/active) to disconnected.
313     */
314    @Override
315    public void onDisconnect(Call call) {
316        hideDialpadForDisconnect();
317        maybeShowErrorDialogOnDisconnect(call);
318
319        // We need to do the run the same code as onCallListChange.
320        onCallListChange(CallList.getInstance());
321
322        if (isActivityStarted()) {
323            mInCallActivity.dismissKeyguard(false);
324        }
325    }
326
327    /**
328     * Given the call list, return the state in which the in-call screen should be.
329     */
330    public static InCallState getPotentialStateFromCallList(CallList callList) {
331
332        InCallState newState = InCallState.NO_CALLS;
333
334        if (callList == null) {
335            return newState;
336        }
337        if (callList.getIncomingCall() != null) {
338            newState = InCallState.INCOMING;
339        } else if (callList.getWaitingForAccountCall() != null) {
340            newState = InCallState.WAITING_FOR_ACCOUNT;
341        } else if (callList.getOutgoingCall() != null) {
342            newState = InCallState.OUTGOING;
343        } else if (callList.getActiveCall() != null ||
344                callList.getBackgroundCall() != null ||
345                callList.getDisconnectedCall() != null ||
346                callList.getDisconnectingCall() != null) {
347            newState = InCallState.INCALL;
348        }
349
350        return newState;
351    }
352
353    public void addIncomingCallListener(IncomingCallListener listener) {
354        Preconditions.checkNotNull(listener);
355        mIncomingCallListeners.add(listener);
356    }
357
358    public void removeIncomingCallListener(IncomingCallListener listener) {
359        Preconditions.checkNotNull(listener);
360        mIncomingCallListeners.remove(listener);
361    }
362
363    public void addListener(InCallStateListener listener) {
364        Preconditions.checkNotNull(listener);
365        mListeners.add(listener);
366    }
367
368    public void removeListener(InCallStateListener listener) {
369        Preconditions.checkNotNull(listener);
370        mListeners.remove(listener);
371    }
372
373    public ProximitySensor getProximitySensor() {
374        return mProximitySensor;
375    }
376
377    public void handleAccountSelection(PhoneAccount account) {
378        Call call = mCallList.getWaitingForAccountCall();
379        if (call != null) {
380            String callId = call.getId();
381            TelecommAdapter.getInstance().phoneAccountSelected(callId, account);
382        }
383    }
384
385    public void cancelAccountSelection() {
386        mAccountSelectionCancelled = true;
387        Call call = mCallList.getWaitingForAccountCall();
388        if (call != null) {
389            String callId = call.getId();
390            TelecommAdapter.getInstance().disconnectCall(callId);
391        }
392    }
393
394    /**
395     * Hangs up any active or outgoing calls.
396     */
397    public void hangUpOngoingCall(Context context) {
398        // By the time we receive this intent, we could be shut down and call list
399        // could be null.  Bail in those cases.
400        if (mCallList == null) {
401            if (mStatusBarNotifier == null) {
402                // The In Call UI has crashed but the notification still stayed up. We should not
403                // come to this stage.
404                StatusBarNotifier.clearInCallNotification(context);
405            }
406            return;
407        }
408
409        Call call = mCallList.getOutgoingCall();
410        if (call == null) {
411            call = mCallList.getActiveOrBackgroundCall();
412        }
413
414        if (call != null) {
415            TelecommAdapter.getInstance().disconnectCall(call.getId());
416        }
417    }
418
419    /**
420     * Answers any incoming call.
421     */
422    public void answerIncomingCall(Context context, int videoState) {
423        // By the time we receive this intent, we could be shut down and call list
424        // could be null.  Bail in those cases.
425        if (mCallList == null) {
426            StatusBarNotifier.clearInCallNotification(context);
427            return;
428        }
429
430        Call call = mCallList.getIncomingCall();
431        if (call != null) {
432            TelecommAdapter.getInstance().answerCall(call.getId(), videoState);
433            showInCall(false, false/* newOutgoingCall */);
434        }
435    }
436
437    /**
438     * Declines any incoming call.
439     */
440    public void declineIncomingCall(Context context) {
441        // By the time we receive this intent, we could be shut down and call list
442        // could be null.  Bail in those cases.
443        if (mCallList == null) {
444            StatusBarNotifier.clearInCallNotification(context);
445            return;
446        }
447
448        Call call = mCallList.getIncomingCall();
449        if (call != null) {
450            TelecommAdapter.getInstance().rejectCall(call.getId(), false, null);
451        }
452    }
453
454    /**
455     * Returns true if the incall app is the foreground application.
456     */
457    public boolean isShowingInCallUi() {
458        return (isActivityStarted() && mInCallActivity.isForegroundActivity());
459    }
460
461    /**
462     * Returns true if the activity has been created and is running.
463     * Returns true as long as activity is not destroyed or finishing.  This ensures that we return
464     * true even if the activity is paused (not in foreground).
465     */
466    public boolean isActivityStarted() {
467        return (mInCallActivity != null &&
468                !mInCallActivity.isDestroyed() &&
469                !mInCallActivity.isFinishing());
470    }
471
472    public boolean isActivityPreviouslyStarted() {
473        return mIsActivityPreviouslyStarted;
474    }
475
476    /**
477     * Called when the activity goes in/out of the foreground.
478     */
479    public void onUiShowing(boolean showing) {
480        // We need to update the notification bar when we leave the UI because that
481        // could trigger it to show again.
482        if (mStatusBarNotifier != null) {
483            mStatusBarNotifier.updateNotification(mInCallState, mCallList);
484        }
485
486        if (mProximitySensor != null) {
487            mProximitySensor.onInCallShowing(showing);
488        }
489
490        if (showing) {
491            mIsActivityPreviouslyStarted = true;
492        }
493    }
494
495    /**
496     * Brings the app into the foreground if possible.
497     */
498    public void bringToForeground(boolean showDialpad) {
499        // Before we bring the incall UI to the foreground, we check to see if:
500        // 1. We've already started the activity once for this session
501        // 2. If it exists, the activity is not already in the foreground
502        // 3. We are in a state where we want to show the incall ui
503        if (mIsActivityPreviouslyStarted && !isShowingInCallUi() &&
504                mInCallState != InCallState.NO_CALLS) {
505            showInCall(showDialpad, false /* newOutgoingCall */);
506        }
507    }
508
509    public void onPostDialCharWait(String callId, String chars) {
510        if (isActivityStarted()) {
511            mInCallActivity.showPostCharWaitDialog(callId, chars);
512        }
513    }
514
515    /**
516     * Handles the green CALL key while in-call.
517     * @return true if we consumed the event.
518     */
519    public boolean handleCallKey() {
520        Log.v(this, "handleCallKey");
521
522        // The green CALL button means either "Answer", "Unhold", or
523        // "Swap calls", or can be a no-op, depending on the current state
524        // of the Phone.
525
526        /**
527         * INCOMING CALL
528         */
529        final CallList calls = CallList.getInstance();
530        final Call incomingCall = calls.getIncomingCall();
531        Log.v(this, "incomingCall: " + incomingCall);
532
533        // (1) Attempt to answer a call
534        if (incomingCall != null) {
535            TelecommAdapter.getInstance().answerCall(
536                    incomingCall.getId(), VideoCallProfile.VIDEO_STATE_AUDIO_ONLY);
537            return true;
538        }
539
540        /**
541         * ACTIVE CALL
542         */
543        final Call activeCall = calls.getActiveCall();
544        if (activeCall != null) {
545            // TODO: This logic is repeated from CallButtonPresenter.java. We should
546            // consolidate this logic.
547            final boolean isGeneric = activeCall.can(CallCapabilities.GENERIC_CONFERENCE);
548            final boolean canMerge = activeCall.can(CallCapabilities.MERGE_CALLS);
549            final boolean canSwap = activeCall.can(CallCapabilities.SWAP_CALLS);
550
551            Log.v(this, "activeCall: " + activeCall + ", isGeneric: " + isGeneric + ", canMerge: " +
552                    canMerge + ", canSwap: " + canSwap);
553
554            // (2) Attempt actions on Generic conference calls
555            if (activeCall.isConferenceCall() && isGeneric) {
556                if (canMerge) {
557                    TelecommAdapter.getInstance().merge(activeCall.getId());
558                    return true;
559                } else if (canSwap) {
560                    TelecommAdapter.getInstance().swap(activeCall.getId());
561                    return true;
562                }
563            }
564
565            // (3) Swap calls
566            if (canSwap) {
567                TelecommAdapter.getInstance().swap(activeCall.getId());
568                return true;
569            }
570        }
571
572        /**
573         * BACKGROUND CALL
574         */
575        final Call heldCall = calls.getBackgroundCall();
576        if (heldCall != null) {
577            // We have a hold call so presumeable it will always support HOLD...but
578            // there is no harm in double checking.
579            final boolean canHold = heldCall.can(CallCapabilities.HOLD);
580
581            Log.v(this, "heldCall: " + heldCall + ", canHold: " + canHold);
582
583            // (4) unhold call
584            if (heldCall.getState() == Call.State.ONHOLD && canHold) {
585                TelecommAdapter.getInstance().unholdCall(heldCall.getId());
586                return true;
587            }
588        }
589
590        // Always consume hard keys
591        return true;
592    }
593
594    /**
595     * A dialog could have prevented in-call screen from being previously finished.
596     * This function checks to see if there should be any UI left and if not attempts
597     * to tear down the UI.
598     */
599    public void onDismissDialog() {
600        Log.i(this, "Dialog dismissed");
601        if (mInCallState == InCallState.NO_CALLS) {
602            attemptFinishActivity();
603            attemptCleanup();
604        }
605    }
606
607    /**
608     * For some disconnected causes, we show a dialog.  This calls into the activity to show
609     * the dialog if appropriate for the call.
610     */
611    private void maybeShowErrorDialogOnDisconnect(Call call) {
612        // For newly disconnected calls, we may want to show a dialog on specific error conditions
613        if (isActivityStarted() && call.getState() == Call.State.DISCONNECTED) {
614            mInCallActivity.maybeShowErrorDialogOnDisconnect(call.getDisconnectCause());
615        }
616    }
617
618    /**
619     * Hides the dialpad.  Called when a call is disconnected (Requires hiding dialpad).
620     */
621    private void hideDialpadForDisconnect() {
622        if (isActivityStarted()) {
623            mInCallActivity.hideDialpadForDisconnect();
624        }
625    }
626
627    /**
628     * When the state of in-call changes, this is the first method to get called. It determines if
629     * the UI needs to be started or finished depending on the new state and does it.
630     */
631    private InCallState startOrFinishUi(InCallState newState) {
632        Log.d(this, "startOrFinishUi: " + mInCallState + " -> " + newState);
633
634        // TODO: Consider a proper state machine implementation
635
636        // If the state isn't changing, we have already done any starting/stopping of
637        // activities in a previous pass...so lets cut out early
638        if (newState == mInCallState) {
639            return newState;
640        }
641
642        // A new Incoming call means that the user needs to be notified of the the call (since
643        // it wasn't them who initiated it).  We do this through full screen notifications and
644        // happens indirectly through {@link StatusBarNotifier}.
645        //
646        // The process for incoming calls is as follows:
647        //
648        // 1) CallList          - Announces existence of new INCOMING call
649        // 2) InCallPresenter   - Gets announcement and calculates that the new InCallState
650        //                      - should be set to INCOMING.
651        // 3) InCallPresenter   - This method is called to see if we need to start or finish
652        //                        the app given the new state.
653        // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
654        //                        StatusBarNotifier explicitly to issue a FullScreen Notification
655        //                        that will either start the InCallActivity or show the user a
656        //                        top-level notification dialog if the user is in an immersive app.
657        //                        That notification can also start the InCallActivity.
658        // 5) InCallActivity    - Main activity starts up and at the end of its onCreate will
659        //                        call InCallPresenter::setActivity() to let the presenter
660        //                        know that start-up is complete.
661        //
662        //          [ AND NOW YOU'RE IN THE CALL. voila! ]
663        //
664        // Our app is started using a fullScreen notification.  We need to do this whenever
665        // we get an incoming call.
666        final boolean startStartupSequence = (InCallState.INCOMING == newState);
667
668        // A dialog to show on top of the InCallUI to select a PhoneAccount
669        final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
670
671        // A new outgoing call indicates that the user just now dialed a number and when that
672        // happens we need to display the screen immediately or show an account picker dialog if
673        // no default is set.
674        //
675        // This is different from the incoming call sequence because we do not need to shock the
676        // user with a top-level notification.  Just show the call UI normally.
677        final boolean showCallUi = (InCallState.OUTGOING == newState || showAccountPicker);
678
679        // TODO: Can we be suddenly in a call without it having been in the outgoing or incoming
680        // state?  I havent seen that but if it can happen, the code below should be enabled.
681        // showCallUi |= (InCallState.INCALL && !isActivityStarted());
682
683        // The only time that we have an instance of mInCallActivity and it isn't started is
684        // when it is being destroyed.  In that case, lets avoid bringing up another instance of
685        // the activity.  When it is finally destroyed, we double check if we should bring it back
686        // up so we aren't going to lose anything by avoiding a second startup here.
687        boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
688        if (activityIsFinishing) {
689            Log.i(this, "Undo the state change: " + newState + " -> " + mInCallState);
690            return mInCallState;
691        }
692
693        if (showCallUi) {
694            Log.i(this, "Start in call UI");
695            showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
696        } else if (startStartupSequence) {
697            Log.i(this, "Start Full Screen in call UI");
698
699            // We're about the bring up the in-call UI for an incoming call. If we still have
700            // dialogs up, we need to clear them out before showing incoming screen.
701            if (isActivityStarted()) {
702                mInCallActivity.dismissPendingDialogs();
703            }
704            startUi(newState);
705        } else if (newState == InCallState.NO_CALLS) {
706            // The new state is the no calls state.  Tear everything down.
707            attemptFinishActivity();
708            attemptCleanup();
709        }
710
711        return newState;
712    }
713
714    private void startUi(InCallState inCallState) {
715        final Call incomingCall = mCallList.getIncomingCall();
716        final boolean isCallWaiting = (incomingCall != null &&
717                incomingCall.getState() == Call.State.CALL_WAITING);
718
719        // If the screen is off, we need to make sure it gets turned on for incoming calls.
720        // This normally works just fine thanks to FLAG_TURN_SCREEN_ON but that only works
721        // when the activity is first created. Therefore, to ensure the screen is turned on
722        // for the call waiting case, we finish() the current activity and start a new one.
723        // There should be no jank from this since the screen is already off and will remain so
724        // until our new activity is up.
725        if (mProximitySensor.isScreenReallyOff() && isCallWaiting) {
726            if (isActivityStarted()) {
727                mInCallActivity.finish();
728            }
729            mInCallActivity = null;
730        }
731
732        mStatusBarNotifier.updateNotification(inCallState, mCallList);
733    }
734
735    /**
736     * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all
737     * down.
738     */
739    private void attemptCleanup() {
740        boolean shouldCleanup = (mInCallActivity == null && !mServiceConnected &&
741                mInCallState == InCallState.NO_CALLS);
742        Log.i(this, "attemptCleanup? " + shouldCleanup);
743
744        if (shouldCleanup) {
745            mIsActivityPreviouslyStarted = false;
746
747            // blow away stale contact info so that we get fresh data on
748            // the next set of calls
749            if (mContactInfoCache != null) {
750                mContactInfoCache.clearCache();
751            }
752            mContactInfoCache = null;
753
754            if (mProximitySensor != null) {
755                removeListener(mProximitySensor);
756                mProximitySensor.tearDown();
757            }
758            mProximitySensor = null;
759
760            mAudioModeProvider = null;
761
762            if (mStatusBarNotifier != null) {
763                removeListener(mStatusBarNotifier);
764            }
765            mStatusBarNotifier = null;
766
767            if (mCallList != null) {
768                mCallList.removeListener(this);
769            }
770            mCallList = null;
771
772            mContext = null;
773            mInCallActivity = null;
774
775            mListeners.clear();
776            mIncomingCallListeners.clear();
777
778            Log.d(this, "Finished InCallPresenter.CleanUp");
779        }
780    }
781
782    private void showInCall(boolean showDialpad, boolean newOutgoingCall) {
783        mContext.startActivity(getInCallIntent(showDialpad, newOutgoingCall));
784    }
785
786    public Intent getInCallIntent(boolean showDialpad, boolean newOutgoingCall) {
787        final Intent intent = new Intent(Intent.ACTION_MAIN, null);
788        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
789                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
790                | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
791        intent.setClass(mContext, InCallActivity.class);
792        if (showDialpad) {
793            intent.putExtra(InCallActivity.SHOW_DIALPAD_EXTRA, true);
794        }
795
796        intent.putExtra(InCallActivity.NEW_OUTGOING_CALL, newOutgoingCall);
797        return intent;
798    }
799
800    /**
801     * Private constructor. Must use getInstance() to get this singleton.
802     */
803    private InCallPresenter() {
804    }
805
806    /**
807     * All the main states of InCallActivity.
808     */
809    public enum InCallState {
810        // InCall Screen is off and there are no calls
811        NO_CALLS,
812
813        // Incoming-call screen is up
814        INCOMING,
815
816        // In-call experience is showing
817        INCALL,
818
819        // Waiting for user input before placing outgoing call
820        WAITING_FOR_ACCOUNT,
821
822        // User is dialing out
823        OUTGOING;
824
825        public boolean isIncoming() {
826            return (this == INCOMING);
827        }
828
829        public boolean isConnectingOrConnected() {
830            return (this == INCOMING ||
831                    this == OUTGOING ||
832                    this == INCALL);
833        }
834    }
835
836    /**
837     * Interface implemented by classes that need to know about the InCall State.
838     */
839    public interface InCallStateListener {
840        // TODO: Enhance state to contain the call objects instead of passing CallList
841        public void onStateChange(InCallState state, CallList callList);
842    }
843
844    public interface IncomingCallListener {
845        public void onIncomingCall(InCallState state, Call call);
846    }
847}
848