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