blob: 97105fb78dba1cd30f21571f626c345add4489cc [file] [log] [blame]
Eric Erfanianccca3152017-02-22 16:32:36 -08001/*
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.graphics.Point;
22import android.os.Bundle;
23import android.os.Handler;
24import android.support.annotation.NonNull;
25import android.support.annotation.Nullable;
26import android.support.annotation.VisibleForTesting;
27import android.telecom.Call.Details;
28import android.telecom.DisconnectCause;
29import android.telecom.PhoneAccount;
30import android.telecom.PhoneAccountHandle;
31import android.telecom.TelecomManager;
32import android.telecom.VideoProfile;
33import android.telephony.PhoneStateListener;
34import android.telephony.TelephonyManager;
35import android.view.Window;
36import android.view.WindowManager;
37import com.android.contacts.common.GeoUtil;
38import com.android.contacts.common.compat.CallCompat;
39import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler;
40import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler.OnCheckBlockedListener;
41import com.android.dialer.blocking.FilteredNumbersUtil;
42import com.android.dialer.common.LogUtil;
43import com.android.dialer.logging.Logger;
44import com.android.dialer.logging.nano.InteractionEvent;
45import com.android.dialer.telecom.TelecomUtil;
46import com.android.dialer.util.TouchPointManager;
47import com.android.incallui.InCallOrientationEventListener.ScreenOrientation;
48import com.android.incallui.answerproximitysensor.PseudoScreenState;
49import com.android.incallui.call.CallList;
50import com.android.incallui.call.DialerCall;
51import com.android.incallui.call.DialerCall.SessionModificationState;
52import com.android.incallui.call.ExternalCallList;
53import com.android.incallui.call.InCallVideoCallCallbackNotifier;
54import com.android.incallui.call.TelecomAdapter;
55import com.android.incallui.call.VideoUtils;
56import com.android.incallui.latencyreport.LatencyReport;
57import com.android.incallui.legacyblocking.BlockedNumberContentObserver;
58import com.android.incallui.spam.SpamCallListListener;
59import com.android.incallui.util.TelecomCallUtil;
60import com.android.incallui.videosurface.bindings.VideoSurfaceBindings;
61import com.android.incallui.videosurface.protocol.VideoSurfaceTexture;
62import java.util.Collections;
63import java.util.List;
64import java.util.Objects;
65import java.util.Set;
66import java.util.concurrent.ConcurrentHashMap;
67import java.util.concurrent.CopyOnWriteArrayList;
68import java.util.concurrent.atomic.AtomicBoolean;
69
70/**
71 * Takes updates from the CallList and notifies the InCallActivity (UI) of the changes. Responsible
72 * for starting the activity for a new call and finishing the activity when all calls are
73 * disconnected. Creates and manages the in-call state and provides a listener pattern for the
74 * presenters that want to listen in on the in-call state changes. TODO: This class has become more
75 * of a state machine at this point. Consider renaming.
76 */
77public class InCallPresenter
78 implements CallList.Listener, InCallVideoCallCallbackNotifier.SessionModificationListener {
79
80 private static final String EXTRA_FIRST_TIME_SHOWN =
81 "com.android.incallui.intent.extra.FIRST_TIME_SHOWN";
82
83 private static final long BLOCK_QUERY_TIMEOUT_MS = 1000;
84
85 private static final Bundle EMPTY_EXTRAS = new Bundle();
86
87 private static InCallPresenter sInCallPresenter;
88
89 /**
90 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before
91 * resizing, 1 means we only expect a single thread to access the map so make only a single shard
92 */
93 private final Set<InCallStateListener> mListeners =
94 Collections.newSetFromMap(new ConcurrentHashMap<InCallStateListener, Boolean>(8, 0.9f, 1));
95
96 private final List<IncomingCallListener> mIncomingCallListeners = new CopyOnWriteArrayList<>();
97 private final Set<InCallDetailsListener> mDetailsListeners =
98 Collections.newSetFromMap(new ConcurrentHashMap<InCallDetailsListener, Boolean>(8, 0.9f, 1));
99 private final Set<CanAddCallListener> mCanAddCallListeners =
100 Collections.newSetFromMap(new ConcurrentHashMap<CanAddCallListener, Boolean>(8, 0.9f, 1));
101 private final Set<InCallUiListener> mInCallUiListeners =
102 Collections.newSetFromMap(new ConcurrentHashMap<InCallUiListener, Boolean>(8, 0.9f, 1));
103 private final Set<InCallOrientationListener> mOrientationListeners =
104 Collections.newSetFromMap(
105 new ConcurrentHashMap<InCallOrientationListener, Boolean>(8, 0.9f, 1));
106 private final Set<InCallEventListener> mInCallEventListeners =
107 Collections.newSetFromMap(new ConcurrentHashMap<InCallEventListener, Boolean>(8, 0.9f, 1));
108
109 private StatusBarNotifier mStatusBarNotifier;
110 private ExternalCallNotifier mExternalCallNotifier;
111 private ContactInfoCache mContactInfoCache;
112 private Context mContext;
113 private final OnCheckBlockedListener mOnCheckBlockedListener =
114 new OnCheckBlockedListener() {
115 @Override
116 public void onCheckComplete(final Integer id) {
117 if (id != null && id != FilteredNumberAsyncQueryHandler.INVALID_ID) {
118 // Silence the ringer now to prevent ringing and vibration before the call is
119 // terminated when Telecom attempts to add it.
120 TelecomUtil.silenceRinger(mContext);
121 }
122 }
123 };
124 private CallList mCallList;
125 private ExternalCallList mExternalCallList;
126 private InCallActivity mInCallActivity;
127 private ManageConferenceActivity mManageConferenceActivity;
128 private final android.telecom.Call.Callback mCallCallback =
129 new android.telecom.Call.Callback() {
130 @Override
131 public void onPostDialWait(
132 android.telecom.Call telecomCall, String remainingPostDialSequence) {
133 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
134 if (call == null) {
135 Log.w(this, "DialerCall not found in call list: " + telecomCall);
136 return;
137 }
138 onPostDialCharWait(call.getId(), remainingPostDialSequence);
139 }
140
141 @Override
142 public void onDetailsChanged(
143 android.telecom.Call telecomCall, android.telecom.Call.Details details) {
144 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
145 if (call == null) {
146 Log.w(this, "DialerCall not found in call list: " + telecomCall);
147 return;
148 }
149
150 if (details.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL)
151 && !mExternalCallList.isCallTracked(telecomCall)) {
152
153 // A regular call became an external call so swap call lists.
154 Log.i(this, "Call became external: " + telecomCall);
155 mCallList.onInternalCallMadeExternal(mContext, telecomCall);
156 mExternalCallList.onCallAdded(telecomCall);
157 return;
158 }
159
160 for (InCallDetailsListener listener : mDetailsListeners) {
161 listener.onDetailsChanged(call, details);
162 }
163 }
164
165 @Override
166 public void onConferenceableCallsChanged(
167 android.telecom.Call telecomCall, List<android.telecom.Call> conferenceableCalls) {
168 Log.i(this, "onConferenceableCallsChanged: " + telecomCall);
169 onDetailsChanged(telecomCall, telecomCall.getDetails());
170 }
171 };
172 private InCallState mInCallState = InCallState.NO_CALLS;
173 private ProximitySensor mProximitySensor;
174 private final PseudoScreenState mPseudoScreenState = new PseudoScreenState();
175 private boolean mServiceConnected;
176 private boolean mAccountSelectionCancelled;
177 private InCallCameraManager mInCallCameraManager;
178 private FilteredNumberAsyncQueryHandler mFilteredQueryHandler;
179 private CallList.Listener mSpamCallListListener;
180 /** Whether or not we are currently bound and waiting for Telecom to send us a new call. */
181 private boolean mBoundAndWaitingForOutgoingCall;
182 /** Determines if the InCall UI is in fullscreen mode or not. */
183 private boolean mIsFullScreen = false;
184
185 private PhoneStateListener mPhoneStateListener =
186 new PhoneStateListener() {
187 @Override
188 public void onCallStateChanged(int state, String incomingNumber) {
189 if (state == TelephonyManager.CALL_STATE_RINGING) {
190 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
191 return;
192 }
193 // Check if the number is blocked, to silence the ringer.
194 String countryIso = GeoUtil.getCurrentCountryIso(mContext);
195 mFilteredQueryHandler.isBlockedNumber(
196 mOnCheckBlockedListener, incomingNumber, countryIso);
197 }
198 }
199 };
200 /**
201 * Is true when the activity has been previously started. Some code needs to know not just if the
202 * activity is currently up, but if it had been previously shown in foreground for this in-call
203 * session (e.g., StatusBarNotifier). This gets reset when the session ends in the tear-down
204 * method.
205 */
206 private boolean mIsActivityPreviouslyStarted = false;
207
208 /** Whether or not InCallService is bound to Telecom. */
209 private boolean mServiceBound = false;
210
211 /**
212 * When configuration changes Android kills the current activity and starts a new one. The flag is
213 * used to check if full clean up is necessary (activity is stopped and new activity won't be
214 * started), or if a new activity will be started right after the current one is destroyed, and
215 * therefore no need in release all resources.
216 */
217 private boolean mIsChangingConfigurations = false;
218
219 private boolean mAwaitingCallListUpdate = false;
220
221 private ExternalCallList.ExternalCallListener mExternalCallListener =
222 new ExternalCallList.ExternalCallListener() {
223
224 @Override
225 public void onExternalCallPulled(android.telecom.Call call) {
226 // Note: keep this code in sync with InCallPresenter#onCallAdded
227 LatencyReport latencyReport = new LatencyReport(call);
228 latencyReport.onCallBlockingDone();
229 // Note: External calls do not require spam checking.
230 mCallList.onCallAdded(mContext, call, latencyReport);
231 call.registerCallback(mCallCallback);
232 }
233
234 @Override
235 public void onExternalCallAdded(android.telecom.Call call) {
236 // No-op
237 }
238
239 @Override
240 public void onExternalCallRemoved(android.telecom.Call call) {
241 // No-op
242 }
243
244 @Override
245 public void onExternalCallUpdated(android.telecom.Call call) {
246 // No-op
247 }
248 };
249
250 private ThemeColorManager mThemeColorManager;
251 private VideoSurfaceTexture mLocalVideoSurfaceTexture;
252 private VideoSurfaceTexture mRemoteVideoSurfaceTexture;
253
254 /** Inaccessible constructor. Must use getInstance() to get this singleton. */
255 @VisibleForTesting
256 InCallPresenter() {}
257
258 public static synchronized InCallPresenter getInstance() {
259 if (sInCallPresenter == null) {
260 sInCallPresenter = new InCallPresenter();
261 }
262 return sInCallPresenter;
263 }
264
265 /**
266 * Determines whether or not a call has no valid phone accounts that can be used to make the call
267 * with. Emergency calls do not require a phone account.
268 *
269 * @param call to check accounts for.
270 * @return {@code true} if the call has no call capable phone accounts set, {@code false} if the
271 * call contains a phone account that could be used to initiate it with, or is an emergency
272 * call.
273 */
274 public static boolean isCallWithNoValidAccounts(DialerCall call) {
275 if (call != null && !call.isEmergencyCall()) {
276 Bundle extras = call.getIntentExtras();
277
278 if (extras == null) {
279 extras = EMPTY_EXTRAS;
280 }
281
282 final List<PhoneAccountHandle> phoneAccountHandles =
283 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
284
285 if ((call.getAccountHandle() == null
286 && (phoneAccountHandles == null || phoneAccountHandles.isEmpty()))) {
287 Log.i(InCallPresenter.getInstance(), "No valid accounts for call " + call);
288 return true;
289 }
290 }
291 return false;
292 }
293
294 public InCallState getInCallState() {
295 return mInCallState;
296 }
297
298 public CallList getCallList() {
299 return mCallList;
300 }
301
302 public void setUp(
303 @NonNull Context context,
304 CallList callList,
305 ExternalCallList externalCallList,
306 StatusBarNotifier statusBarNotifier,
307 ExternalCallNotifier externalCallNotifier,
308 ContactInfoCache contactInfoCache,
309 ProximitySensor proximitySensor) {
310 if (mServiceConnected) {
311 Log.i(this, "New service connection replacing existing one.");
312 if (context != mContext || callList != mCallList) {
313 throw new IllegalStateException();
314 }
315 return;
316 }
317
318 Objects.requireNonNull(context);
319 mContext = context;
320
321 mContactInfoCache = contactInfoCache;
322
323 mStatusBarNotifier = statusBarNotifier;
324 mExternalCallNotifier = externalCallNotifier;
325 addListener(mStatusBarNotifier);
326
327 mProximitySensor = proximitySensor;
328 addListener(mProximitySensor);
329
330 mThemeColorManager =
331 new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources()));
332
333 mCallList = callList;
334 mExternalCallList = externalCallList;
335 externalCallList.addExternalCallListener(mExternalCallNotifier);
336 externalCallList.addExternalCallListener(mExternalCallListener);
337
338 // This only gets called by the service so this is okay.
339 mServiceConnected = true;
340
341 // The final thing we do in this set up is add ourselves as a listener to CallList. This
342 // will kick off an update and the whole process can start.
343 mCallList.addListener(this);
344
345 // Create spam call list listener and add it to the list of listeners
346 mSpamCallListListener = new SpamCallListListener(context);
347 mCallList.addListener(mSpamCallListListener);
348
349 VideoPauseController.getInstance().setUp(this);
350 InCallVideoCallCallbackNotifier.getInstance().addSessionModificationListener(this);
351
352 mFilteredQueryHandler = new FilteredNumberAsyncQueryHandler(context);
353 mContext
354 .getSystemService(TelephonyManager.class)
355 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
356
357 Log.d(this, "Finished InCallPresenter.setUp");
358 }
359
360 /**
361 * Called when the telephony service has disconnected from us. This will happen when there are no
362 * more active calls. However, we may still want to continue showing the UI for certain cases like
363 * showing "Call Ended". What we really want is to wait for the activity and the service to both
364 * disconnect before we tear things down. This method sets a serviceConnected boolean and calls a
365 * secondary method that performs the aforementioned logic.
366 */
367 public void tearDown() {
368 Log.d(this, "tearDown");
369 mCallList.clearOnDisconnect();
370
371 mServiceConnected = false;
372
373 mContext
374 .getSystemService(TelephonyManager.class)
375 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
376
377 attemptCleanup();
378 VideoPauseController.getInstance().tearDown();
379 InCallVideoCallCallbackNotifier.getInstance().removeSessionModificationListener(this);
380 }
381
382 private void attemptFinishActivity() {
383 final boolean doFinish = (mInCallActivity != null && isActivityStarted());
384 Log.i(this, "Hide in call UI: " + doFinish);
385 if (doFinish) {
386 mInCallActivity.setExcludeFromRecents(true);
387 mInCallActivity.finish();
388
389 if (mAccountSelectionCancelled) {
390 // This finish is a result of account selection cancellation
391 // do not include activity ending transition
392 mInCallActivity.overridePendingTransition(0, 0);
393 }
394 }
395 }
396
397 /**
398 * Called when the UI ends. Attempts to tear down everything if necessary. See {@link #tearDown()}
399 * for more insight on the tear-down process.
400 */
401 public void unsetActivity(InCallActivity inCallActivity) {
402 if (inCallActivity == null) {
403 throw new IllegalArgumentException("unregisterActivity cannot be called with null");
404 }
405 if (mInCallActivity == null) {
406 Log.i(this, "No InCallActivity currently set, no need to unset.");
407 return;
408 }
409 if (mInCallActivity != inCallActivity) {
410 Log.w(
411 this,
412 "Second instance of InCallActivity is trying to unregister when another"
413 + " instance is active. Ignoring.");
414 return;
415 }
416 updateActivity(null);
417 }
418
419 /**
420 * Updates the current instance of {@link InCallActivity} with the provided one. If a {@code null}
421 * activity is provided, it means that the activity was finished and we should attempt to cleanup.
422 */
423 private void updateActivity(InCallActivity inCallActivity) {
424 boolean updateListeners = false;
425 boolean doAttemptCleanup = false;
426
427 if (inCallActivity != null) {
428 if (mInCallActivity == null) {
429 updateListeners = true;
430 Log.i(this, "UI Initialized");
431 } else {
432 // since setActivity is called onStart(), it can be called multiple times.
433 // This is fine and ignorable, but we do not want to update the world every time
434 // this happens (like going to/from background) so we do not set updateListeners.
435 }
436
437 mInCallActivity = inCallActivity;
438 mInCallActivity.setExcludeFromRecents(false);
439
440 // By the time the UI finally comes up, the call may already be disconnected.
441 // If that's the case, we may need to show an error dialog.
442 if (mCallList != null && mCallList.getDisconnectedCall() != null) {
443 maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
444 }
445
446 // When the UI comes up, we need to first check the in-call state.
447 // If we are showing NO_CALLS, that means that a call probably connected and
448 // then immediately disconnected before the UI was able to come up.
449 // If we dont have any calls, start tearing down the UI instead.
450 // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
451 // it has been set.
452 if (mInCallState == InCallState.NO_CALLS) {
453 Log.i(this, "UI Initialized, but no calls left. shut down.");
454 attemptFinishActivity();
455 return;
456 }
457 } else {
458 Log.i(this, "UI Destroyed");
459 updateListeners = true;
460 mInCallActivity = null;
461
462 // We attempt cleanup for the destroy case but only after we recalculate the state
463 // to see if we need to come back up or stay shut down. This is why we do the
464 // cleanup after the call to onCallListChange() instead of directly here.
465 doAttemptCleanup = true;
466 }
467
468 // Messages can come from the telephony layer while the activity is coming up
469 // and while the activity is going down. So in both cases we need to recalculate what
470 // state we should be in after they complete.
471 // Examples: (1) A new incoming call could come in and then get disconnected before
472 // the activity is created.
473 // (2) All calls could disconnect and then get a new incoming call before the
474 // activity is destroyed.
475 //
476 // b/1122139 - We previously had a check for mServiceConnected here as well, but there are
477 // cases where we need to recalculate the current state even if the service in not
478 // connected. In particular the case where startOrFinish() is called while the app is
479 // already finish()ing. In that case, we skip updating the state with the knowledge that
480 // we will check again once the activity has finished. That means we have to recalculate the
481 // state here even if the service is disconnected since we may not have finished a state
482 // transition while finish()ing.
483 if (updateListeners) {
484 onCallListChange(mCallList);
485 }
486
487 if (doAttemptCleanup) {
488 attemptCleanup();
489 }
490 }
491
492 public void setManageConferenceActivity(
493 @Nullable ManageConferenceActivity manageConferenceActivity) {
494 mManageConferenceActivity = manageConferenceActivity;
495 }
496
497 public void onBringToForeground(boolean showDialpad) {
498 Log.i(this, "Bringing UI to foreground.");
499 bringToForeground(showDialpad);
500 }
501
502 public void onCallAdded(final android.telecom.Call call) {
503 LatencyReport latencyReport = new LatencyReport(call);
504 if (shouldAttemptBlocking(call)) {
505 maybeBlockCall(call, latencyReport);
506 } else {
507 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
508 mExternalCallList.onCallAdded(call);
509 } else {
510 latencyReport.onCallBlockingDone();
511 mCallList.onCallAdded(mContext, call, latencyReport);
512 }
513 }
514
515 // Since a call has been added we are no longer waiting for Telecom to send us a call.
516 setBoundAndWaitingForOutgoingCall(false, null);
517 call.registerCallback(mCallCallback);
518 }
519
520 private boolean shouldAttemptBlocking(android.telecom.Call call) {
521 if (call.getState() != android.telecom.Call.STATE_RINGING) {
522 return false;
523 }
524 if (TelecomCallUtil.isEmergencyCall(call)) {
525 Log.i(this, "Not attempting to block incoming emergency call");
526 return false;
527 }
528 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
529 Log.i(this, "Not attempting to block incoming call due to recent emergency call");
530 return false;
531 }
532 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
533 return false;
534 }
535 return true;
536 }
537
538 /**
539 * Checks whether a call should be blocked, and blocks it if so. Otherwise, it adds the call to
540 * the CallList so it can proceed as normal. There is a timeout, so if the function for checking
541 * whether a function is blocked does not return in a reasonable time, we proceed with adding the
542 * call anyways.
543 */
544 private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) {
545 final String countryIso = GeoUtil.getCurrentCountryIso(mContext);
546 final String number = TelecomCallUtil.getNumber(call);
547 final long timeAdded = System.currentTimeMillis();
548
549 // Though AtomicBoolean's can be scary, don't fear, as in this case it is only used on the
550 // main UI thread. It is needed so we can change its value within different scopes, since
551 // that cannot be done with a final boolean.
552 final AtomicBoolean hasTimedOut = new AtomicBoolean(false);
553
554 final Handler handler = new Handler();
555
556 // Proceed if the query is slow; the call may still be blocked after the query returns.
557 final Runnable runnable =
558 new Runnable() {
559 @Override
560 public void run() {
561 hasTimedOut.set(true);
562 latencyReport.onCallBlockingDone();
563 mCallList.onCallAdded(mContext, call, latencyReport);
564 }
565 };
566 handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS);
567
568 OnCheckBlockedListener onCheckBlockedListener =
569 new OnCheckBlockedListener() {
570 @Override
571 public void onCheckComplete(final Integer id) {
572 if (isReadyForTearDown()) {
573 Log.i(this, "InCallPresenter is torn down, not adding call");
574 return;
575 }
576 if (!hasTimedOut.get()) {
577 handler.removeCallbacks(runnable);
578 }
579 if (id == null) {
580 if (!hasTimedOut.get()) {
581 latencyReport.onCallBlockingDone();
582 mCallList.onCallAdded(mContext, call, latencyReport);
583 }
584 } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) {
585 Log.d(this, "checkForBlockedCall: invalid number, skipping block checking");
586 if (!hasTimedOut.get()) {
587 handler.removeCallbacks(runnable);
588
589 latencyReport.onCallBlockingDone();
590 mCallList.onCallAdded(mContext, call, latencyReport);
591 }
592 } else {
593 Log.i(this, "Rejecting incoming call from blocked number");
594 call.reject(false, null);
595 Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED);
596
597 /*
598 * If mContext is null, then the InCallPresenter was torn down before the
599 * block check had a chance to complete. The context is no longer valid, so
600 * don't attempt to remove the call log entry.
601 */
602 if (mContext == null) {
603 return;
604 }
605 // Register observer to update the call log.
606 // BlockedNumberContentObserver will unregister after successful log or timeout.
607 BlockedNumberContentObserver contentObserver =
608 new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded);
609 contentObserver.register();
610 }
611 }
612 };
613
614 mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso);
615 }
616
617 public void onCallRemoved(android.telecom.Call call) {
618 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
619 mExternalCallList.onCallRemoved(call);
620 } else {
621 mCallList.onCallRemoved(mContext, call);
622 call.unregisterCallback(mCallCallback);
623 }
624 }
625
626 public void onCanAddCallChanged(boolean canAddCall) {
627 for (CanAddCallListener listener : mCanAddCallListeners) {
628 listener.onCanAddCallChanged(canAddCall);
629 }
630 }
631
632 @Override
633 public void onWiFiToLteHandover(DialerCall call) {
634 if (mInCallActivity != null) {
635 mInCallActivity.onWiFiToLteHandover(call);
636 }
637 }
638
639 @Override
640 public void onHandoverToWifiFailed(DialerCall call) {
641 if (mInCallActivity != null) {
642 mInCallActivity.onHandoverToWifiFailed(call);
643 }
644 }
645
646 /**
647 * Called when there is a change to the call list. Sets the In-Call state for the entire in-call
648 * app based on the information it gets from CallList. Dispatches the in-call state to all
649 * listeners. Can trigger the creation or destruction of the UI based on the states that is
650 * calculates.
651 */
652 @Override
653 public void onCallListChange(CallList callList) {
654 if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) {
655 mAwaitingCallListUpdate = true;
656 return;
657 }
658 if (callList == null) {
659 return;
660 }
661
662 mAwaitingCallListUpdate = false;
663
664 InCallState newState = getPotentialStateFromCallList(callList);
665 InCallState oldState = mInCallState;
666 Log.d(this, "onCallListChange oldState= " + oldState + " newState=" + newState);
667 newState = startOrFinishUi(newState);
668 Log.d(this, "onCallListChange newState changed to " + newState);
669
670 // Set the new state before announcing it to the world
671 Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
672 mInCallState = newState;
673
674 // notify listeners of new state
675 for (InCallStateListener listener : mListeners) {
676 Log.d(this, "Notify " + listener + " of state " + mInCallState.toString());
677 listener.onStateChange(oldState, mInCallState, callList);
678 }
679
680 if (isActivityStarted()) {
681 final boolean hasCall =
682 callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null;
683 mInCallActivity.dismissKeyguard(hasCall);
684 }
685 }
686
687 /** Called when there is a new incoming call. */
688 @Override
689 public void onIncomingCall(DialerCall call) {
690 InCallState newState = startOrFinishUi(InCallState.INCOMING);
691 InCallState oldState = mInCallState;
692
693 Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
694 mInCallState = newState;
695
696 for (IncomingCallListener listener : mIncomingCallListeners) {
697 listener.onIncomingCall(oldState, mInCallState, call);
698 }
699
700 if (mInCallActivity != null) {
701 // Re-evaluate which fragment is being shown.
702 mInCallActivity.onPrimaryCallStateChanged();
703 }
704 }
705
706 @Override
707 public void onUpgradeToVideo(DialerCall call) {
708 if (call.getSessionModificationState()
709 == DialerCall.SESSION_MODIFICATION_STATE_RECEIVED_UPGRADE_TO_VIDEO_REQUEST
710 && mInCallState == InCallPresenter.InCallState.INCOMING) {
711 LogUtil.i(
712 "InCallPresenter.onUpgradeToVideo",
713 "rejecting upgrade request due to existing incoming call");
714 call.declineUpgradeRequest();
715 }
716
717 if (mInCallActivity != null) {
718 // Re-evaluate which fragment is being shown.
719 mInCallActivity.onPrimaryCallStateChanged();
720 }
721 }
722
723 @Override
724 public void onSessionModificationStateChange(@SessionModificationState int newState) {
725 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
726 if (mProximitySensor == null) {
727 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
728 return;
729 }
730 mProximitySensor.setIsAttemptingVideoCall(
731 VideoUtils.hasSentVideoUpgradeRequest(newState)
732 || VideoUtils.hasReceivedVideoUpgradeRequest(newState));
733 if (mInCallActivity != null) {
734 // Re-evaluate which fragment is being shown.
735 mInCallActivity.onPrimaryCallStateChanged();
736 }
737 }
738
739 /**
740 * Called when a call becomes disconnected. Called everytime an existing call changes from being
741 * connected (incoming/outgoing/active) to disconnected.
742 */
743 @Override
744 public void onDisconnect(DialerCall call) {
745 maybeShowErrorDialogOnDisconnect(call);
746
747 // We need to do the run the same code as onCallListChange.
748 onCallListChange(mCallList);
749
750 if (isActivityStarted()) {
751 mInCallActivity.dismissKeyguard(false);
752 }
753
754 if (call.isEmergencyCall()) {
755 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
756 }
757 }
758
759 @Override
760 public void onUpgradeToVideoRequest(DialerCall call, int videoState) {
761 LogUtil.d(
762 "InCallPresenter.onUpgradeToVideoRequest",
763 "call = " + call + " video state = " + videoState);
764
765 if (call == null) {
766 return;
767 }
768
769 call.setRequestedVideoState(videoState);
770 }
771
772 /** Given the call list, return the state in which the in-call screen should be. */
773 public InCallState getPotentialStateFromCallList(CallList callList) {
774
775 InCallState newState = InCallState.NO_CALLS;
776
777 if (callList == null) {
778 return newState;
779 }
780 if (callList.getIncomingCall() != null) {
781 newState = InCallState.INCOMING;
782 } else if (callList.getWaitingForAccountCall() != null) {
783 newState = InCallState.WAITING_FOR_ACCOUNT;
784 } else if (callList.getPendingOutgoingCall() != null) {
785 newState = InCallState.PENDING_OUTGOING;
786 } else if (callList.getOutgoingCall() != null) {
787 newState = InCallState.OUTGOING;
788 } else if (callList.getActiveCall() != null
789 || callList.getBackgroundCall() != null
790 || callList.getDisconnectedCall() != null
791 || callList.getDisconnectingCall() != null) {
792 newState = InCallState.INCALL;
793 }
794
795 if (newState == InCallState.NO_CALLS) {
796 if (mBoundAndWaitingForOutgoingCall) {
797 return InCallState.OUTGOING;
798 }
799 }
800
801 return newState;
802 }
803
804 public boolean isBoundAndWaitingForOutgoingCall() {
805 return mBoundAndWaitingForOutgoingCall;
806 }
807
808 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
809 Log.i(this, "setBoundAndWaitingForOutgoingCall: " + isBound);
810 mBoundAndWaitingForOutgoingCall = isBound;
811 mThemeColorManager.setPendingPhoneAccountHandle(handle);
812 if (isBound && mInCallState == InCallState.NO_CALLS) {
813 mInCallState = InCallState.OUTGOING;
814 }
815 }
816
817 public void onShrinkAnimationComplete() {
818 if (mAwaitingCallListUpdate) {
819 onCallListChange(mCallList);
820 }
821 }
822
823 public void addIncomingCallListener(IncomingCallListener listener) {
824 Objects.requireNonNull(listener);
825 mIncomingCallListeners.add(listener);
826 }
827
828 public void removeIncomingCallListener(IncomingCallListener listener) {
829 if (listener != null) {
830 mIncomingCallListeners.remove(listener);
831 }
832 }
833
834 public void addListener(InCallStateListener listener) {
835 Objects.requireNonNull(listener);
836 mListeners.add(listener);
837 }
838
839 public void removeListener(InCallStateListener listener) {
840 if (listener != null) {
841 mListeners.remove(listener);
842 }
843 }
844
845 public void addDetailsListener(InCallDetailsListener listener) {
846 Objects.requireNonNull(listener);
847 mDetailsListeners.add(listener);
848 }
849
850 public void removeDetailsListener(InCallDetailsListener listener) {
851 if (listener != null) {
852 mDetailsListeners.remove(listener);
853 }
854 }
855
856 public void addCanAddCallListener(CanAddCallListener listener) {
857 Objects.requireNonNull(listener);
858 mCanAddCallListeners.add(listener);
859 }
860
861 public void removeCanAddCallListener(CanAddCallListener listener) {
862 if (listener != null) {
863 mCanAddCallListeners.remove(listener);
864 }
865 }
866
867 public void addOrientationListener(InCallOrientationListener listener) {
868 Objects.requireNonNull(listener);
869 mOrientationListeners.add(listener);
870 }
871
872 public void removeOrientationListener(InCallOrientationListener listener) {
873 if (listener != null) {
874 mOrientationListeners.remove(listener);
875 }
876 }
877
878 public void addInCallEventListener(InCallEventListener listener) {
879 Objects.requireNonNull(listener);
880 mInCallEventListeners.add(listener);
881 }
882
883 public void removeInCallEventListener(InCallEventListener listener) {
884 if (listener != null) {
885 mInCallEventListeners.remove(listener);
886 }
887 }
888
889 public ProximitySensor getProximitySensor() {
890 return mProximitySensor;
891 }
892
893 public PseudoScreenState getPseudoScreenState() {
894 return mPseudoScreenState;
895 }
896
897 /** Returns true if the incall app is the foreground application. */
898 public boolean isShowingInCallUi() {
899 if (!isActivityStarted()) {
900 return false;
901 }
902 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
903 return true;
904 }
905 return mInCallActivity.isVisible();
906 }
907
908 /**
909 * Returns true if the activity has been created and is running. Returns true as long as activity
910 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
911 * (not in foreground).
912 */
913 public boolean isActivityStarted() {
914 return (mInCallActivity != null
915 && !mInCallActivity.isDestroyed()
916 && !mInCallActivity.isFinishing());
917 }
918
919 /**
920 * Determines if the In-Call app is currently changing configuration.
921 *
922 * @return {@code true} if the In-Call app is changing configuration.
923 */
924 public boolean isChangingConfigurations() {
925 return mIsChangingConfigurations;
926 }
927
928 /**
929 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
930 * screen orientation).
931 */
932 /*package*/
933 void updateIsChangingConfigurations() {
934 mIsChangingConfigurations = false;
935 if (mInCallActivity != null) {
936 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
937 }
938 Log.v(this, "updateIsChangingConfigurations = " + mIsChangingConfigurations);
939 }
940
941 /** Called when the activity goes in/out of the foreground. */
942 public void onUiShowing(boolean showing) {
943 // We need to update the notification bar when we leave the UI because that
944 // could trigger it to show again.
945 if (mStatusBarNotifier != null) {
946 mStatusBarNotifier.updateNotification(mCallList);
947 }
948
949 if (mProximitySensor != null) {
950 mProximitySensor.onInCallShowing(showing);
951 }
952
953 Intent broadcastIntent = Bindings.get(mContext).getUiReadyBroadcastIntent(mContext);
954 if (broadcastIntent != null) {
955 broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
956
957 if (showing) {
958 Log.d(this, "Sending sticky broadcast: ", broadcastIntent);
959 mContext.sendStickyBroadcast(broadcastIntent);
960 } else {
961 Log.d(this, "Removing sticky broadcast: ", broadcastIntent);
962 mContext.removeStickyBroadcast(broadcastIntent);
963 }
964 }
965
966 if (showing) {
967 mIsActivityPreviouslyStarted = true;
968 } else {
969 updateIsChangingConfigurations();
970 }
971
972 for (InCallUiListener listener : mInCallUiListeners) {
973 listener.onUiShowing(showing);
974 }
975
976 if (mInCallActivity != null) {
977 // Re-evaluate which fragment is being shown.
978 mInCallActivity.onPrimaryCallStateChanged();
979 }
980 }
981
982 public void addInCallUiListener(InCallUiListener listener) {
983 mInCallUiListeners.add(listener);
984 }
985
986 public boolean removeInCallUiListener(InCallUiListener listener) {
987 return mInCallUiListeners.remove(listener);
988 }
989
990 /*package*/
991 void onActivityStarted() {
992 Log.d(this, "onActivityStarted");
993 notifyVideoPauseController(true);
994 mStatusBarNotifier.updateNotification(mCallList);
995 }
996
997 /*package*/
998 void onActivityStopped() {
999 Log.d(this, "onActivityStopped");
1000 notifyVideoPauseController(false);
1001 }
1002
1003 private void notifyVideoPauseController(boolean showing) {
1004 Log.d(
1005 this, "notifyVideoPauseController: mIsChangingConfigurations=" + mIsChangingConfigurations);
1006 if (!mIsChangingConfigurations) {
1007 VideoPauseController.getInstance().onUiShowing(showing);
1008 }
1009 }
1010
1011 /** Brings the app into the foreground if possible. */
1012 public void bringToForeground(boolean showDialpad) {
1013 // Before we bring the incall UI to the foreground, we check to see if:
1014 // 1. It is not currently in the foreground
1015 // 2. We are in a state where we want to show the incall ui (i.e. there are calls to
1016 // be displayed)
1017 // If the activity hadn't actually been started previously, yet there are still calls
1018 // present (e.g. a call was accepted by a bluetooth or wired headset), we want to
1019 // bring it up the UI regardless.
1020 if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
1021 showInCall(showDialpad, false /* newOutgoingCall */, false /* isVideoCall */);
1022 }
1023 }
1024
1025 public void onPostDialCharWait(String callId, String chars) {
1026 if (isActivityStarted()) {
1027 mInCallActivity.showPostCharWaitDialog(callId, chars);
1028 }
1029 }
1030
1031 /**
1032 * Handles the green CALL key while in-call.
1033 *
1034 * @return true if we consumed the event.
1035 */
1036 public boolean handleCallKey() {
1037 LogUtil.v("InCallPresenter.handleCallKey", null);
1038
1039 // The green CALL button means either "Answer", "Unhold", or
1040 // "Swap calls", or can be a no-op, depending on the current state
1041 // of the Phone.
1042
1043 /** INCOMING CALL */
1044 final CallList calls = mCallList;
1045 final DialerCall incomingCall = calls.getIncomingCall();
1046 LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall);
1047
1048 // (1) Attempt to answer a call
1049 if (incomingCall != null) {
1050 incomingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
1051 return true;
1052 }
1053
1054 /** STATE_ACTIVE CALL */
1055 final DialerCall activeCall = calls.getActiveCall();
1056 if (activeCall != null) {
1057 // TODO: This logic is repeated from CallButtonPresenter.java. We should
1058 // consolidate this logic.
1059 final boolean canMerge =
1060 activeCall.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
1061 final boolean canSwap =
1062 activeCall.can(android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
1063
1064 Log.v(
1065 this, "activeCall: " + activeCall + ", canMerge: " + canMerge + ", canSwap: " + canSwap);
1066
1067 // (2) Attempt actions on conference calls
1068 if (canMerge) {
1069 TelecomAdapter.getInstance().merge(activeCall.getId());
1070 return true;
1071 } else if (canSwap) {
1072 TelecomAdapter.getInstance().swap(activeCall.getId());
1073 return true;
1074 }
1075 }
1076
1077 /** BACKGROUND CALL */
1078 final DialerCall heldCall = calls.getBackgroundCall();
1079 if (heldCall != null) {
1080 // We have a hold call so presumeable it will always support HOLD...but
1081 // there is no harm in double checking.
1082 final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
1083
1084 Log.v(this, "heldCall: " + heldCall + ", canHold: " + canHold);
1085
1086 // (4) unhold call
1087 if (heldCall.getState() == DialerCall.State.ONHOLD && canHold) {
1088 heldCall.unhold();
1089 return true;
1090 }
1091 }
1092
1093 // Always consume hard keys
1094 return true;
1095 }
1096
1097 /**
1098 * A dialog could have prevented in-call screen from being previously finished. This function
1099 * checks to see if there should be any UI left and if not attempts to tear down the UI.
1100 */
1101 public void onDismissDialog() {
1102 Log.i(this, "Dialog dismissed");
1103 if (mInCallState == InCallState.NO_CALLS) {
1104 attemptFinishActivity();
1105 attemptCleanup();
1106 }
1107 }
1108
1109 /** Clears the previous fullscreen state. */
1110 public void clearFullscreen() {
1111 mIsFullScreen = false;
1112 }
1113
1114 /**
1115 * Changes the fullscreen mode of the in-call UI.
1116 *
1117 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1118 * otherwise.
1119 */
1120 public void setFullScreen(boolean isFullScreen) {
1121 setFullScreen(isFullScreen, false /* force */);
1122 }
1123
1124 /**
1125 * Changes the fullscreen mode of the in-call UI.
1126 *
1127 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1128 * otherwise.
1129 * @param force {@code true} if fullscreen mode should be set regardless of its current state.
1130 */
1131 public void setFullScreen(boolean isFullScreen, boolean force) {
1132 Log.i(this, "setFullScreen = " + isFullScreen);
1133
1134 // As a safeguard, ensure we cannot enter fullscreen if the dialpad is shown.
1135 if (isDialpadVisible()) {
1136 isFullScreen = false;
1137 Log.v(this, "setFullScreen overridden as dialpad is shown = " + isFullScreen);
1138 }
1139
1140 if (mIsFullScreen == isFullScreen && !force) {
1141 Log.v(this, "setFullScreen ignored as already in that state.");
1142 return;
1143 }
1144 mIsFullScreen = isFullScreen;
1145 notifyFullscreenModeChange(mIsFullScreen);
1146 }
1147
1148 /**
1149 * @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
1150 * otherwise.
1151 */
1152 public boolean isFullscreen() {
1153 return mIsFullScreen;
1154 }
1155
1156 /**
1157 * Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
1158 *
1159 * @param isFullscreenMode {@code True} if entering full screen mode.
1160 */
1161 public void notifyFullscreenModeChange(boolean isFullscreenMode) {
1162 for (InCallEventListener listener : mInCallEventListeners) {
1163 listener.onFullscreenModeChanged(isFullscreenMode);
1164 }
1165 }
1166
1167 /**
1168 * For some disconnected causes, we show a dialog. This calls into the activity to show the dialog
1169 * if appropriate for the call.
1170 */
1171 private void maybeShowErrorDialogOnDisconnect(DialerCall call) {
1172 // For newly disconnected calls, we may want to show a dialog on specific error conditions
1173 if (isActivityStarted() && call.getState() == DialerCall.State.DISCONNECTED) {
1174 if (call.getAccountHandle() == null && !call.isConferenceCall()) {
1175 setDisconnectCauseForMissingAccounts(call);
1176 }
1177 mInCallActivity.maybeShowErrorDialogOnDisconnect(call.getDisconnectCause());
1178 }
1179 }
1180
1181 /**
1182 * When the state of in-call changes, this is the first method to get called. It determines if the
1183 * UI needs to be started or finished depending on the new state and does it.
1184 */
1185 private InCallState startOrFinishUi(InCallState newState) {
1186 Log.d(this, "startOrFinishUi: " + mInCallState + " -> " + newState);
1187
1188 // TODO: Consider a proper state machine implementation
1189
1190 // If the state isn't changing we have already done any starting/stopping of activities in
1191 // a previous pass...so lets cut out early
1192 if (newState == mInCallState) {
1193 return newState;
1194 }
1195
1196 // A new Incoming call means that the user needs to be notified of the the call (since
1197 // it wasn't them who initiated it). We do this through full screen notifications and
1198 // happens indirectly through {@link StatusBarNotifier}.
1199 //
1200 // The process for incoming calls is as follows:
1201 //
1202 // 1) CallList - Announces existence of new INCOMING call
1203 // 2) InCallPresenter - Gets announcement and calculates that the new InCallState
1204 // - should be set to INCOMING.
1205 // 3) InCallPresenter - This method is called to see if we need to start or finish
1206 // the app given the new state.
1207 // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
1208 // StatusBarNotifier explicitly to issue a FullScreen Notification
1209 // that will either start the InCallActivity or show the user a
1210 // top-level notification dialog if the user is in an immersive app.
1211 // That notification can also start the InCallActivity.
1212 // 5) InCallActivity - Main activity starts up and at the end of its onCreate will
1213 // call InCallPresenter::setActivity() to let the presenter
1214 // know that start-up is complete.
1215 //
1216 // [ AND NOW YOU'RE IN THE CALL. voila! ]
1217 //
1218 // Our app is started using a fullScreen notification. We need to do this whenever
1219 // we get an incoming call. Depending on the current context of the device, either a
1220 // incoming call HUN or the actual InCallActivity will be shown.
1221 final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
1222
1223 // A dialog to show on top of the InCallUI to select a PhoneAccount
1224 final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
1225
1226 // A new outgoing call indicates that the user just now dialed a number and when that
1227 // happens we need to display the screen immediately or show an account picker dialog if
1228 // no default is set. However, if the main InCallUI is already visible, we do not want to
1229 // re-initiate the start-up animation, so we do not need to do anything here.
1230 //
1231 // It is also possible to go into an intermediate state where the call has been initiated
1232 // but Telecom has not yet returned with the details of the call (handle, gateway, etc.).
1233 // This pending outgoing state can also launch the call screen.
1234 //
1235 // This is different from the incoming call sequence because we do not need to shock the
1236 // user with a top-level notification. Just show the call UI normally.
1237 boolean callCardFragmentVisible =
1238 mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible();
1239 final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible;
1240 boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
1241
1242 // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
1243 // outgoing call process, so the UI should be brought up to show an error dialog.
1244 showCallUi |=
1245 (InCallState.PENDING_OUTGOING == mInCallState
1246 && InCallState.INCALL == newState
1247 && !isShowingInCallUi());
1248
1249 // Another exception - InCallActivity is in charge of disconnecting a call with no
1250 // valid accounts set. Bring the UI up if this is true for the current pending outgoing
1251 // call so that:
1252 // 1) The call can be disconnected correctly
1253 // 2) The UI comes up and correctly displays the error dialog.
1254 // TODO: Remove these special case conditions by making InCallPresenter a true state
1255 // machine. Telecom should also be the component responsible for disconnecting a call
1256 // with no valid accounts.
1257 showCallUi |=
1258 InCallState.PENDING_OUTGOING == newState
1259 && mainUiNotVisible
1260 && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
1261
1262 // The only time that we have an instance of mInCallActivity and it isn't started is
1263 // when it is being destroyed. In that case, lets avoid bringing up another instance of
1264 // the activity. When it is finally destroyed, we double check if we should bring it back
1265 // up so we aren't going to lose anything by avoiding a second startup here.
1266 boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
1267 if (activityIsFinishing) {
1268 Log.i(this, "Undo the state change: " + newState + " -> " + mInCallState);
1269 return mInCallState;
1270 }
1271
1272 // We're about the bring up the in-call UI for outgoing and incoming call. If we still have
1273 // dialogs up, we need to clear them out before showing in-call screen. This is necessary
1274 // to fix the bug that dialog will show up when data reaches limit even after makeing new
1275 // outgoing call after user ignore it by pressing home button.
1276 if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING)
1277 && !showCallUi
1278 && isActivityStarted()) {
1279 mInCallActivity.dismissPendingDialogs();
1280 }
1281
1282 if (showCallUi || showAccountPicker) {
1283 Log.i(this, "Start in call UI");
1284 showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */, false);
1285 } else if (startIncomingCallSequence) {
1286 Log.i(this, "Start Full Screen in call UI");
1287
1288 if (!startUi()) {
1289 // startUI refused to start the UI. This indicates that it needed to restart the
1290 // activity. When it finally restarts, it will call us back, so we do not actually
1291 // change the state yet (we return mInCallState instead of newState).
1292 return mInCallState;
1293 }
1294 } else if (newState == InCallState.NO_CALLS) {
1295 // The new state is the no calls state. Tear everything down.
1296 attemptFinishActivity();
1297 attemptCleanup();
1298 }
1299
1300 return newState;
1301 }
1302
1303 /**
1304 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1305 * or PhoneAccounts to select from.
1306 */
1307 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1308
1309 Bundle extras = call.getIntentExtras();
1310 // Initialize the extras bundle to avoid NPE
1311 if (extras == null) {
1312 extras = new Bundle();
1313 }
1314
1315 final List<PhoneAccountHandle> phoneAccountHandles =
1316 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1317
1318 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1319 String scheme = call.getHandle().getScheme();
1320 final String errorMsg =
1321 PhoneAccount.SCHEME_TEL.equals(scheme)
1322 ? mContext.getString(R.string.callFailed_simError)
1323 : mContext.getString(R.string.incall_error_supp_service_unknown);
1324 DisconnectCause disconnectCause =
1325 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1326 call.setDisconnectCause(disconnectCause);
1327 }
1328 }
1329
1330 private boolean startUi() {
1331 boolean isCallWaiting =
1332 mCallList.getActiveCall() != null && mCallList.getIncomingCall() != null;
1333
1334 if (isCallWaiting) {
1335 showInCall(false, false, false /* isVideoCall */);
1336 } else {
1337 mStatusBarNotifier.updateNotification(mCallList);
1338 }
1339 return true;
1340 }
1341
1342 /**
1343 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1344 * Calling classes should use this as an indication whether to interact with the
1345 * InCallPresenter or not.
1346 */
1347 public boolean isReadyForTearDown() {
1348 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1349 }
1350
1351 /**
1352 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1353 */
1354 private void attemptCleanup() {
1355 if (isReadyForTearDown()) {
1356 Log.i(this, "Cleaning up");
1357
1358 cleanupSurfaces();
1359
1360 mIsActivityPreviouslyStarted = false;
1361 mIsChangingConfigurations = false;
1362
1363 // blow away stale contact info so that we get fresh data on
1364 // the next set of calls
1365 if (mContactInfoCache != null) {
1366 mContactInfoCache.clearCache();
1367 }
1368 mContactInfoCache = null;
1369
1370 if (mProximitySensor != null) {
1371 removeListener(mProximitySensor);
1372 mProximitySensor.tearDown();
1373 }
1374 mProximitySensor = null;
1375
1376 if (mStatusBarNotifier != null) {
1377 removeListener(mStatusBarNotifier);
1378 }
1379 if (mExternalCallNotifier != null && mExternalCallList != null) {
1380 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1381 }
1382 mStatusBarNotifier = null;
1383
1384 if (mCallList != null) {
1385 mCallList.removeListener(this);
1386 mCallList.removeListener(mSpamCallListListener);
1387 }
1388 mCallList = null;
1389
1390 mContext = null;
1391 mInCallActivity = null;
1392 mManageConferenceActivity = null;
1393
1394 mListeners.clear();
1395 mIncomingCallListeners.clear();
1396 mDetailsListeners.clear();
1397 mCanAddCallListeners.clear();
1398 mOrientationListeners.clear();
1399 mInCallEventListeners.clear();
1400 mInCallUiListeners.clear();
1401
1402 Log.d(this, "Finished InCallPresenter.CleanUp");
1403 }
1404 }
1405
1406 public void showInCall(boolean showDialpad, boolean newOutgoingCall, boolean isVideoCall) {
1407 Log.i(this, "Showing InCallActivity");
1408 mContext.startActivity(
1409 InCallActivity.getIntent(
1410 mContext, showDialpad, newOutgoingCall, isVideoCall, false /* forFullScreen */));
1411 }
1412
1413 public void onServiceBind() {
1414 mServiceBound = true;
1415 }
1416
1417 public void onServiceUnbind() {
1418 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1419 mServiceBound = false;
1420 }
1421
1422 public boolean isServiceBound() {
1423 return mServiceBound;
1424 }
1425
1426 public void maybeStartRevealAnimation(Intent intent) {
1427 if (intent == null || mInCallActivity != null) {
1428 return;
1429 }
1430 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1431 if (extras == null) {
1432 // Incoming call, just show the in-call UI directly.
1433 return;
1434 }
1435
1436 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1437 // Account selection dialog will show up so don't show the animation.
1438 return;
1439 }
1440
1441 final PhoneAccountHandle accountHandle =
1442 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1443 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
1444 int videoState =
1445 extras.getInt(
1446 TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, VideoProfile.STATE_AUDIO_ONLY);
1447
1448 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1449
1450 final Intent activityIntent =
1451 InCallActivity.getIntent(
1452 mContext, false, true, VideoUtils.isVideoCall(videoState), false /* forFullScreen */);
1453 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1454 mContext.startActivity(activityIntent);
1455 }
1456
1457 /**
1458 * Retrieves the current in-call camera manager instance, creating if necessary.
1459 *
1460 * @return The {@link InCallCameraManager}.
1461 */
1462 public InCallCameraManager getInCallCameraManager() {
1463 synchronized (this) {
1464 if (mInCallCameraManager == null) {
1465 mInCallCameraManager = new InCallCameraManager(mContext);
1466 }
1467
1468 return mInCallCameraManager;
1469 }
1470 }
1471
1472 /**
1473 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1474 *
1475 * @param orientation The screen orientation of the device (one of: {@link
1476 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1477 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1478 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1479 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1480 */
1481 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
1482 Log.d(this, "onDeviceOrientationChange: orientation= " + orientation);
1483
1484 if (mCallList != null) {
1485 mCallList.notifyCallsOfDeviceRotation(orientation);
1486 } else {
1487 Log.w(this, "onDeviceOrientationChange: CallList is null.");
1488 }
1489
1490 // Notify listeners of device orientation changed.
1491 for (InCallOrientationListener listener : mOrientationListeners) {
1492 listener.onDeviceOrientationChanged(orientation);
1493 }
1494 }
1495
1496 /**
1497 * Configures the in-call UI activity so it can change orientations or not. Enables the
1498 * orientation event listener if allowOrientationChange is true, disables it if false.
1499 *
1500 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1501 * landscape. {@code false} if the in-call UI should be locked in portrait.
1502 */
1503 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1504 if (mInCallActivity == null) {
1505 Log.e(this, "InCallActivity is null. Can't set requested orientation.");
1506 return;
1507 }
1508 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1509 }
1510
1511 public void enableScreenTimeout(boolean enable) {
1512 Log.v(this, "enableScreenTimeout: value=" + enable);
1513 if (mInCallActivity == null) {
1514 Log.e(this, "enableScreenTimeout: InCallActivity is null.");
1515 return;
1516 }
1517
1518 final Window window = mInCallActivity.getWindow();
1519 if (enable) {
1520 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1521 } else {
1522 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1523 }
1524 }
1525
1526 /**
1527 * Hides or shows the conference manager fragment.
1528 *
1529 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1530 * be hidden.
1531 */
1532 public void showConferenceCallManager(boolean show) {
1533 if (mInCallActivity != null) {
1534 mInCallActivity.showConferenceFragment(show);
1535 }
1536 if (!show && mManageConferenceActivity != null) {
1537 mManageConferenceActivity.finish();
1538 }
1539 }
1540
1541 /**
1542 * Determines if the dialpad is visible.
1543 *
1544 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1545 */
1546 public boolean isDialpadVisible() {
1547 if (mInCallActivity == null) {
1548 return false;
1549 }
1550 return mInCallActivity.isDialpadVisible();
1551 }
1552
1553 public ThemeColorManager getThemeColorManager() {
1554 return mThemeColorManager;
1555 }
1556
1557 /** Called when the foreground call changes. */
1558 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1559 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1560 if (mInCallActivity != null) {
1561 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1562 }
1563 }
1564
1565 public InCallActivity getActivity() {
1566 return mInCallActivity;
1567 }
1568
1569 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1570 public void setActivity(InCallActivity inCallActivity) {
1571 if (inCallActivity == null) {
1572 throw new IllegalArgumentException("registerActivity cannot be called with null");
1573 }
1574 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
1575 Log.w(this, "Setting a second activity before destroying the first.");
1576 }
1577 updateActivity(inCallActivity);
1578 }
1579
1580 ExternalCallNotifier getExternalCallNotifier() {
1581 return mExternalCallNotifier;
1582 }
1583
1584 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1585 if (mLocalVideoSurfaceTexture == null) {
1586 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture();
1587 }
1588 return mLocalVideoSurfaceTexture;
1589 }
1590
1591 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1592 if (mRemoteVideoSurfaceTexture == null) {
1593 mRemoteVideoSurfaceTexture = VideoSurfaceBindings.createRemoteVideoSurfaceTexture();
1594 }
1595 return mRemoteVideoSurfaceTexture;
1596 }
1597
1598 void cleanupSurfaces() {
1599 if (mRemoteVideoSurfaceTexture != null) {
1600 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1601 mRemoteVideoSurfaceTexture = null;
1602 }
1603 if (mLocalVideoSurfaceTexture != null) {
1604 mLocalVideoSurfaceTexture.setDoneWithSurface();
1605 mLocalVideoSurfaceTexture = null;
1606 }
1607 }
1608
1609 /** All the main states of InCallActivity. */
1610 public enum InCallState {
1611 // InCall Screen is off and there are no calls
1612 NO_CALLS,
1613
1614 // Incoming-call screen is up
1615 INCOMING,
1616
1617 // In-call experience is showing
1618 INCALL,
1619
1620 // Waiting for user input before placing outgoing call
1621 WAITING_FOR_ACCOUNT,
1622
1623 // UI is starting up but no call has been initiated yet.
1624 // The UI is waiting for Telecom to respond.
1625 PENDING_OUTGOING,
1626
1627 // User is dialing out
1628 OUTGOING;
1629
1630 public boolean isIncoming() {
1631 return (this == INCOMING);
1632 }
1633
1634 public boolean isConnectingOrConnected() {
1635 return (this == INCOMING || this == OUTGOING || this == INCALL);
1636 }
1637 }
1638
1639 /** Interface implemented by classes that need to know about the InCall State. */
1640 public interface InCallStateListener {
1641
1642 // TODO: Enhance state to contain the call objects instead of passing CallList
1643 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1644 }
1645
1646 public interface IncomingCallListener {
1647
1648 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1649 }
1650
1651 public interface CanAddCallListener {
1652
1653 void onCanAddCallChanged(boolean canAddCall);
1654 }
1655
1656 public interface InCallDetailsListener {
1657
1658 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1659 }
1660
1661 public interface InCallOrientationListener {
1662
1663 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1664 }
1665
1666 /**
1667 * Interface implemented by classes that need to know about events which occur within the In-Call
1668 * UI. Used as a means of communicating between fragments that make up the UI.
1669 */
1670 public interface InCallEventListener {
1671
1672 void onFullscreenModeChanged(boolean isFullscreenMode);
1673 }
1674
1675 public interface InCallUiListener {
1676
1677 void onUiShowing(boolean showing);
1678 }
1679}