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