blob: ed7b2c29053a7b6ac155ab5a925dd0ca32ca75f6 [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;
Eric Erfanian2ca43182017-08-31 06:57:16 -070024import android.os.Trace;
twyen8efb4952017-10-06 16:35:54 -070025import android.support.annotation.MainThread;
Eric Erfanianccca3152017-02-22 16:32:36 -080026import android.support.annotation.NonNull;
27import android.support.annotation.Nullable;
28import android.support.annotation.VisibleForTesting;
Eric Erfanian83b20212017-05-31 08:53:10 -070029import android.support.v4.os.UserManagerCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080030import android.telecom.Call.Details;
31import android.telecom.DisconnectCause;
32import android.telecom.PhoneAccount;
33import android.telecom.PhoneAccountHandle;
34import android.telecom.TelecomManager;
35import android.telecom.VideoProfile;
36import android.telephony.PhoneStateListener;
37import android.telephony.TelephonyManager;
twyen8efb4952017-10-06 16:35:54 -070038import android.util.ArraySet;
Eric Erfanianccca3152017-02-22 16:32:36 -080039import android.view.Window;
40import android.view.WindowManager;
Eric Erfanianccca3152017-02-22 16:32:36 -080041import com.android.contacts.common.compat.CallCompat;
42import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler;
43import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler.OnCheckBlockedListener;
Eric Erfanian83b20212017-05-31 08:53:10 -070044import com.android.dialer.blocking.FilteredNumberCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080045import com.android.dialer.blocking.FilteredNumbersUtil;
twyen8efb4952017-10-06 16:35:54 -070046import com.android.dialer.common.Assert;
Eric Erfanianccca3152017-02-22 16:32:36 -080047import com.android.dialer.common.LogUtil;
zachh6a4cebd2017-10-24 17:10:06 -070048import com.android.dialer.common.concurrent.DialerExecutorComponent;
Eric Erfaniand8046e52017-04-06 09:41:50 -070049import com.android.dialer.enrichedcall.EnrichedCallComponent;
Eric Erfanian10b34a52017-05-04 08:23:17 -070050import com.android.dialer.location.GeoUtil;
Eric Erfanian8369df02017-05-03 10:27:13 -070051import com.android.dialer.logging.InteractionEvent;
Eric Erfanianccca3152017-02-22 16:32:36 -080052import com.android.dialer.logging.Logger;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070053import com.android.dialer.postcall.PostCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080054import com.android.dialer.telecom.TelecomUtil;
55import com.android.dialer.util.TouchPointManager;
56import com.android.incallui.InCallOrientationEventListener.ScreenOrientation;
57import com.android.incallui.answerproximitysensor.PseudoScreenState;
58import com.android.incallui.call.CallList;
59import com.android.incallui.call.DialerCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080060import com.android.incallui.call.ExternalCallList;
Eric Erfanianccca3152017-02-22 16:32:36 -080061import com.android.incallui.call.TelecomAdapter;
Eric Erfanian2ca43182017-08-31 06:57:16 -070062import com.android.incallui.disconnectdialog.DisconnectMessage;
twyen8efb4952017-10-06 16:35:54 -070063import com.android.incallui.incalluilock.InCallUiLock;
Eric Erfanianccca3152017-02-22 16:32:36 -080064import com.android.incallui.latencyreport.LatencyReport;
65import com.android.incallui.legacyblocking.BlockedNumberContentObserver;
66import com.android.incallui.spam.SpamCallListListener;
67import com.android.incallui.util.TelecomCallUtil;
68import com.android.incallui.videosurface.bindings.VideoSurfaceBindings;
69import com.android.incallui.videosurface.protocol.VideoSurfaceTexture;
Eric Erfanian90508232017-03-24 09:31:16 -070070import com.android.incallui.videotech.utils.VideoUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080071import java.util.Collections;
72import java.util.List;
73import java.util.Objects;
74import java.util.Set;
75import java.util.concurrent.ConcurrentHashMap;
76import java.util.concurrent.CopyOnWriteArrayList;
77import java.util.concurrent.atomic.AtomicBoolean;
78
79/**
80 * Takes updates from the CallList and notifies the InCallActivity (UI) of the changes. Responsible
81 * for starting the activity for a new call and finishing the activity when all calls are
82 * disconnected. Creates and manages the in-call state and provides a listener pattern for the
83 * presenters that want to listen in on the in-call state changes. TODO: This class has become more
84 * of a state machine at this point. Consider renaming.
85 */
Eric Erfaniand5e47f62017-03-15 14:41:07 -070086public class InCallPresenter implements CallList.Listener {
Eric Erfanian2ca43182017-08-31 06:57:16 -070087 private static final String PIXEL2017_SYSTEM_FEATURE =
88 "com.google.android.feature.PIXEL_2017_EXPERIENCE";
Eric Erfanianccca3152017-02-22 16:32:36 -080089 private static final String EXTRA_FIRST_TIME_SHOWN =
90 "com.android.incallui.intent.extra.FIRST_TIME_SHOWN";
91
92 private static final long BLOCK_QUERY_TIMEOUT_MS = 1000;
93
94 private static final Bundle EMPTY_EXTRAS = new Bundle();
95
96 private static InCallPresenter sInCallPresenter;
97
98 /**
99 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before
100 * resizing, 1 means we only expect a single thread to access the map so make only a single shard
101 */
102 private final Set<InCallStateListener> mListeners =
103 Collections.newSetFromMap(new ConcurrentHashMap<InCallStateListener, Boolean>(8, 0.9f, 1));
104
105 private final List<IncomingCallListener> mIncomingCallListeners = new CopyOnWriteArrayList<>();
106 private final Set<InCallDetailsListener> mDetailsListeners =
107 Collections.newSetFromMap(new ConcurrentHashMap<InCallDetailsListener, Boolean>(8, 0.9f, 1));
108 private final Set<CanAddCallListener> mCanAddCallListeners =
109 Collections.newSetFromMap(new ConcurrentHashMap<CanAddCallListener, Boolean>(8, 0.9f, 1));
110 private final Set<InCallUiListener> mInCallUiListeners =
111 Collections.newSetFromMap(new ConcurrentHashMap<InCallUiListener, Boolean>(8, 0.9f, 1));
112 private final Set<InCallOrientationListener> mOrientationListeners =
113 Collections.newSetFromMap(
114 new ConcurrentHashMap<InCallOrientationListener, Boolean>(8, 0.9f, 1));
115 private final Set<InCallEventListener> mInCallEventListeners =
116 Collections.newSetFromMap(new ConcurrentHashMap<InCallEventListener, Boolean>(8, 0.9f, 1));
117
118 private StatusBarNotifier mStatusBarNotifier;
119 private ExternalCallNotifier mExternalCallNotifier;
120 private ContactInfoCache mContactInfoCache;
121 private Context mContext;
122 private final OnCheckBlockedListener mOnCheckBlockedListener =
123 new OnCheckBlockedListener() {
124 @Override
125 public void onCheckComplete(final Integer id) {
126 if (id != null && id != FilteredNumberAsyncQueryHandler.INVALID_ID) {
127 // Silence the ringer now to prevent ringing and vibration before the call is
128 // terminated when Telecom attempts to add it.
129 TelecomUtil.silenceRinger(mContext);
130 }
131 }
132 };
133 private CallList mCallList;
134 private ExternalCallList mExternalCallList;
135 private InCallActivity mInCallActivity;
136 private ManageConferenceActivity mManageConferenceActivity;
137 private final android.telecom.Call.Callback mCallCallback =
138 new android.telecom.Call.Callback() {
139 @Override
140 public void onPostDialWait(
141 android.telecom.Call telecomCall, String remainingPostDialSequence) {
142 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
143 if (call == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700144 LogUtil.w(
145 "InCallPresenter.onPostDialWait",
146 "DialerCall not found in call list: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800147 return;
148 }
149 onPostDialCharWait(call.getId(), remainingPostDialSequence);
150 }
151
152 @Override
153 public void onDetailsChanged(
154 android.telecom.Call telecomCall, android.telecom.Call.Details details) {
155 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
156 if (call == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700157 LogUtil.w(
158 "InCallPresenter.onDetailsChanged",
159 "DialerCall not found in call list: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800160 return;
161 }
162
163 if (details.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL)
164 && !mExternalCallList.isCallTracked(telecomCall)) {
165
166 // A regular call became an external call so swap call lists.
Eric Erfanian2ca43182017-08-31 06:57:16 -0700167 LogUtil.i("InCallPresenter.onDetailsChanged", "Call became external: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800168 mCallList.onInternalCallMadeExternal(mContext, telecomCall);
169 mExternalCallList.onCallAdded(telecomCall);
170 return;
171 }
172
173 for (InCallDetailsListener listener : mDetailsListeners) {
174 listener.onDetailsChanged(call, details);
175 }
176 }
177
178 @Override
179 public void onConferenceableCallsChanged(
180 android.telecom.Call telecomCall, List<android.telecom.Call> conferenceableCalls) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700181 LogUtil.i(
182 "InCallPresenter.onConferenceableCallsChanged",
183 "onConferenceableCallsChanged: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800184 onDetailsChanged(telecomCall, telecomCall.getDetails());
185 }
186 };
187 private InCallState mInCallState = InCallState.NO_CALLS;
188 private ProximitySensor mProximitySensor;
189 private final PseudoScreenState mPseudoScreenState = new PseudoScreenState();
190 private boolean mServiceConnected;
Eric Erfanianccca3152017-02-22 16:32:36 -0800191 private InCallCameraManager mInCallCameraManager;
192 private FilteredNumberAsyncQueryHandler mFilteredQueryHandler;
193 private CallList.Listener mSpamCallListListener;
194 /** Whether or not we are currently bound and waiting for Telecom to send us a new call. */
195 private boolean mBoundAndWaitingForOutgoingCall;
196 /** Determines if the InCall UI is in fullscreen mode or not. */
197 private boolean mIsFullScreen = false;
198
Eric Erfanian2ca43182017-08-31 06:57:16 -0700199 private boolean mScreenTimeoutEnabled = true;
200
Eric Erfanianccca3152017-02-22 16:32:36 -0800201 private PhoneStateListener mPhoneStateListener =
202 new PhoneStateListener() {
203 @Override
204 public void onCallStateChanged(int state, String incomingNumber) {
205 if (state == TelephonyManager.CALL_STATE_RINGING) {
206 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
207 return;
208 }
209 // Check if the number is blocked, to silence the ringer.
210 String countryIso = GeoUtil.getCurrentCountryIso(mContext);
211 mFilteredQueryHandler.isBlockedNumber(
212 mOnCheckBlockedListener, incomingNumber, countryIso);
213 }
214 }
215 };
216 /**
217 * Is true when the activity has been previously started. Some code needs to know not just if the
218 * activity is currently up, but if it had been previously shown in foreground for this in-call
219 * session (e.g., StatusBarNotifier). This gets reset when the session ends in the tear-down
220 * method.
221 */
222 private boolean mIsActivityPreviouslyStarted = false;
223
224 /** Whether or not InCallService is bound to Telecom. */
225 private boolean mServiceBound = false;
226
227 /**
228 * When configuration changes Android kills the current activity and starts a new one. The flag is
229 * used to check if full clean up is necessary (activity is stopped and new activity won't be
230 * started), or if a new activity will be started right after the current one is destroyed, and
231 * therefore no need in release all resources.
232 */
233 private boolean mIsChangingConfigurations = false;
234
235 private boolean mAwaitingCallListUpdate = false;
236
237 private ExternalCallList.ExternalCallListener mExternalCallListener =
238 new ExternalCallList.ExternalCallListener() {
239
240 @Override
241 public void onExternalCallPulled(android.telecom.Call call) {
242 // Note: keep this code in sync with InCallPresenter#onCallAdded
243 LatencyReport latencyReport = new LatencyReport(call);
244 latencyReport.onCallBlockingDone();
245 // Note: External calls do not require spam checking.
246 mCallList.onCallAdded(mContext, call, latencyReport);
247 call.registerCallback(mCallCallback);
248 }
249
250 @Override
251 public void onExternalCallAdded(android.telecom.Call call) {
252 // No-op
253 }
254
255 @Override
256 public void onExternalCallRemoved(android.telecom.Call call) {
257 // No-op
258 }
259
260 @Override
261 public void onExternalCallUpdated(android.telecom.Call call) {
262 // No-op
263 }
264 };
265
266 private ThemeColorManager mThemeColorManager;
267 private VideoSurfaceTexture mLocalVideoSurfaceTexture;
268 private VideoSurfaceTexture mRemoteVideoSurfaceTexture;
269
Eric Erfanian10b34a52017-05-04 08:23:17 -0700270 /** Inaccessible constructor. Must use getRunningInstance() to get this singleton. */
Eric Erfanianccca3152017-02-22 16:32:36 -0800271 @VisibleForTesting
272 InCallPresenter() {}
273
274 public static synchronized InCallPresenter getInstance() {
275 if (sInCallPresenter == null) {
wangqic8cf79e2017-10-17 09:21:00 -0700276 Trace.beginSection("InCallPresenter.Constructor");
Eric Erfanianccca3152017-02-22 16:32:36 -0800277 sInCallPresenter = new InCallPresenter();
wangqic8cf79e2017-10-17 09:21:00 -0700278 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800279 }
280 return sInCallPresenter;
281 }
282
Eric Erfanian10b34a52017-05-04 08:23:17 -0700283 @VisibleForTesting
284 public static synchronized void setInstanceForTesting(InCallPresenter inCallPresenter) {
285 sInCallPresenter = inCallPresenter;
286 }
287
Eric Erfanianccca3152017-02-22 16:32:36 -0800288 /**
289 * Determines whether or not a call has no valid phone accounts that can be used to make the call
290 * with. Emergency calls do not require a phone account.
291 *
292 * @param call to check accounts for.
293 * @return {@code true} if the call has no call capable phone accounts set, {@code false} if the
294 * call contains a phone account that could be used to initiate it with, or is an emergency
295 * call.
296 */
297 public static boolean isCallWithNoValidAccounts(DialerCall call) {
298 if (call != null && !call.isEmergencyCall()) {
299 Bundle extras = call.getIntentExtras();
300
301 if (extras == null) {
302 extras = EMPTY_EXTRAS;
303 }
304
305 final List<PhoneAccountHandle> phoneAccountHandles =
306 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
307
308 if ((call.getAccountHandle() == null
309 && (phoneAccountHandles == null || phoneAccountHandles.isEmpty()))) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700310 LogUtil.i(
311 "InCallPresenter.isCallWithNoValidAccounts", "No valid accounts for call " + call);
Eric Erfanianccca3152017-02-22 16:32:36 -0800312 return true;
313 }
314 }
315 return false;
316 }
317
318 public InCallState getInCallState() {
319 return mInCallState;
320 }
321
322 public CallList getCallList() {
323 return mCallList;
324 }
325
326 public void setUp(
327 @NonNull Context context,
328 CallList callList,
329 ExternalCallList externalCallList,
330 StatusBarNotifier statusBarNotifier,
331 ExternalCallNotifier externalCallNotifier,
332 ContactInfoCache contactInfoCache,
Eric Erfanian83b20212017-05-31 08:53:10 -0700333 ProximitySensor proximitySensor,
334 FilteredNumberAsyncQueryHandler filteredNumberQueryHandler) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700335 Trace.beginSection("InCallPresenter.setUp");
Eric Erfanianccca3152017-02-22 16:32:36 -0800336 if (mServiceConnected) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700337 LogUtil.i("InCallPresenter.setUp", "New service connection replacing existing one.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800338 if (context != mContext || callList != mCallList) {
339 throw new IllegalStateException();
340 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700341 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800342 return;
343 }
344
345 Objects.requireNonNull(context);
346 mContext = context;
347
348 mContactInfoCache = contactInfoCache;
349
350 mStatusBarNotifier = statusBarNotifier;
351 mExternalCallNotifier = externalCallNotifier;
352 addListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -0700353 EnrichedCallComponent.get(mContext)
354 .getEnrichedCallManager()
355 .registerStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -0800356
357 mProximitySensor = proximitySensor;
358 addListener(mProximitySensor);
359
wangqi8d662ca2017-10-26 11:27:19 -0700360 if (mThemeColorManager == null) {
361 mThemeColorManager =
362 new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources()));
363 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800364
365 mCallList = callList;
366 mExternalCallList = externalCallList;
367 externalCallList.addExternalCallListener(mExternalCallNotifier);
368 externalCallList.addExternalCallListener(mExternalCallListener);
369
370 // This only gets called by the service so this is okay.
371 mServiceConnected = true;
372
373 // The final thing we do in this set up is add ourselves as a listener to CallList. This
374 // will kick off an update and the whole process can start.
375 mCallList.addListener(this);
376
377 // Create spam call list listener and add it to the list of listeners
zachh6a4cebd2017-10-24 17:10:06 -0700378 mSpamCallListListener =
379 new SpamCallListListener(
380 context, DialerExecutorComponent.get(context).dialerExecutorFactory());
Eric Erfanianccca3152017-02-22 16:32:36 -0800381 mCallList.addListener(mSpamCallListListener);
382
383 VideoPauseController.getInstance().setUp(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800384
Eric Erfanian83b20212017-05-31 08:53:10 -0700385 mFilteredQueryHandler = filteredNumberQueryHandler;
Eric Erfanianccca3152017-02-22 16:32:36 -0800386 mContext
387 .getSystemService(TelephonyManager.class)
388 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
389
Eric Erfanian2ca43182017-08-31 06:57:16 -0700390 LogUtil.d("InCallPresenter.setUp", "Finished InCallPresenter.setUp");
391 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800392 }
393
394 /**
395 * Called when the telephony service has disconnected from us. This will happen when there are no
396 * more active calls. However, we may still want to continue showing the UI for certain cases like
397 * showing "Call Ended". What we really want is to wait for the activity and the service to both
398 * disconnect before we tear things down. This method sets a serviceConnected boolean and calls a
399 * secondary method that performs the aforementioned logic.
400 */
401 public void tearDown() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700402 LogUtil.d("InCallPresenter.tearDown", "tearDown");
Eric Erfanianccca3152017-02-22 16:32:36 -0800403 mCallList.clearOnDisconnect();
404
405 mServiceConnected = false;
406
407 mContext
408 .getSystemService(TelephonyManager.class)
409 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
410
411 attemptCleanup();
412 VideoPauseController.getInstance().tearDown();
Eric Erfanianccca3152017-02-22 16:32:36 -0800413 }
414
415 private void attemptFinishActivity() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700416 mScreenTimeoutEnabled = true;
Eric Erfanianccca3152017-02-22 16:32:36 -0800417 final boolean doFinish = (mInCallActivity != null && isActivityStarted());
Eric Erfanian2ca43182017-08-31 06:57:16 -0700418 LogUtil.i("InCallPresenter.attemptFinishActivity", "Hide in call UI: " + doFinish);
Eric Erfanianccca3152017-02-22 16:32:36 -0800419 if (doFinish) {
420 mInCallActivity.setExcludeFromRecents(true);
421 mInCallActivity.finish();
Eric Erfanianccca3152017-02-22 16:32:36 -0800422 }
423 }
424
425 /**
426 * Called when the UI ends. Attempts to tear down everything if necessary. See {@link #tearDown()}
427 * for more insight on the tear-down process.
428 */
429 public void unsetActivity(InCallActivity inCallActivity) {
430 if (inCallActivity == null) {
431 throw new IllegalArgumentException("unregisterActivity cannot be called with null");
432 }
433 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700434 LogUtil.i(
435 "InCallPresenter.unsetActivity", "No InCallActivity currently set, no need to unset.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800436 return;
437 }
438 if (mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700439 LogUtil.w(
440 "InCallPresenter.unsetActivity",
Eric Erfanianccca3152017-02-22 16:32:36 -0800441 "Second instance of InCallActivity is trying to unregister when another"
442 + " instance is active. Ignoring.");
443 return;
444 }
445 updateActivity(null);
446 }
447
448 /**
449 * Updates the current instance of {@link InCallActivity} with the provided one. If a {@code null}
450 * activity is provided, it means that the activity was finished and we should attempt to cleanup.
451 */
452 private void updateActivity(InCallActivity inCallActivity) {
wangqi9982f0d2017-10-11 17:46:07 -0700453 Trace.beginSection("InCallPresenter.updateActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -0800454 boolean updateListeners = false;
455 boolean doAttemptCleanup = false;
456
457 if (inCallActivity != null) {
458 if (mInCallActivity == null) {
Eric Erfanian938468d2017-10-24 14:05:52 -0700459 mContext = inCallActivity.getApplicationContext();
Eric Erfanianccca3152017-02-22 16:32:36 -0800460 updateListeners = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700461 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized");
Eric Erfanianccca3152017-02-22 16:32:36 -0800462 } else {
463 // since setActivity is called onStart(), it can be called multiple times.
464 // This is fine and ignorable, but we do not want to update the world every time
465 // this happens (like going to/from background) so we do not set updateListeners.
466 }
467
468 mInCallActivity = inCallActivity;
469 mInCallActivity.setExcludeFromRecents(false);
470
471 // By the time the UI finally comes up, the call may already be disconnected.
472 // If that's the case, we may need to show an error dialog.
473 if (mCallList != null && mCallList.getDisconnectedCall() != null) {
474 maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
475 }
476
477 // When the UI comes up, we need to first check the in-call state.
478 // If we are showing NO_CALLS, that means that a call probably connected and
479 // then immediately disconnected before the UI was able to come up.
480 // If we dont have any calls, start tearing down the UI instead.
481 // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
482 // it has been set.
483 if (mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700484 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized, but no calls left. Shut down");
Eric Erfanianccca3152017-02-22 16:32:36 -0800485 attemptFinishActivity();
wangqi9982f0d2017-10-11 17:46:07 -0700486 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800487 return;
488 }
489 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700490 LogUtil.i("InCallPresenter.updateActivity", "UI Destroyed");
Eric Erfanianccca3152017-02-22 16:32:36 -0800491 updateListeners = true;
492 mInCallActivity = null;
493
494 // We attempt cleanup for the destroy case but only after we recalculate the state
495 // to see if we need to come back up or stay shut down. This is why we do the
496 // cleanup after the call to onCallListChange() instead of directly here.
497 doAttemptCleanup = true;
498 }
499
500 // Messages can come from the telephony layer while the activity is coming up
501 // and while the activity is going down. So in both cases we need to recalculate what
502 // state we should be in after they complete.
503 // Examples: (1) A new incoming call could come in and then get disconnected before
504 // the activity is created.
505 // (2) All calls could disconnect and then get a new incoming call before the
506 // activity is destroyed.
507 //
Eric Erfanian938468d2017-10-24 14:05:52 -0700508 // a bug - We previously had a check for mServiceConnected here as well, but there are
Eric Erfanianccca3152017-02-22 16:32:36 -0800509 // cases where we need to recalculate the current state even if the service in not
510 // connected. In particular the case where startOrFinish() is called while the app is
511 // already finish()ing. In that case, we skip updating the state with the knowledge that
512 // we will check again once the activity has finished. That means we have to recalculate the
513 // state here even if the service is disconnected since we may not have finished a state
514 // transition while finish()ing.
515 if (updateListeners) {
516 onCallListChange(mCallList);
517 }
518
519 if (doAttemptCleanup) {
520 attemptCleanup();
521 }
wangqi9982f0d2017-10-11 17:46:07 -0700522 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800523 }
524
525 public void setManageConferenceActivity(
526 @Nullable ManageConferenceActivity manageConferenceActivity) {
527 mManageConferenceActivity = manageConferenceActivity;
528 }
529
530 public void onBringToForeground(boolean showDialpad) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700531 LogUtil.i("InCallPresenter.onBringToForeground", "Bringing UI to foreground.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800532 bringToForeground(showDialpad);
533 }
534
535 public void onCallAdded(final android.telecom.Call call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700536 Trace.beginSection("InCallPresenter.onCallAdded");
Eric Erfanianccca3152017-02-22 16:32:36 -0800537 LatencyReport latencyReport = new LatencyReport(call);
538 if (shouldAttemptBlocking(call)) {
539 maybeBlockCall(call, latencyReport);
540 } else {
541 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
542 mExternalCallList.onCallAdded(call);
543 } else {
544 latencyReport.onCallBlockingDone();
545 mCallList.onCallAdded(mContext, call, latencyReport);
546 }
547 }
548
549 // Since a call has been added we are no longer waiting for Telecom to send us a call.
550 setBoundAndWaitingForOutgoingCall(false, null);
551 call.registerCallback(mCallCallback);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700552 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800553 }
554
555 private boolean shouldAttemptBlocking(android.telecom.Call call) {
556 if (call.getState() != android.telecom.Call.STATE_RINGING) {
557 return false;
558 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700559 if (!UserManagerCompat.isUserUnlocked(mContext)) {
560 LogUtil.i(
561 "InCallPresenter.shouldAttemptBlocking",
562 "not attempting to block incoming call because user is locked");
563 return false;
564 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800565 if (TelecomCallUtil.isEmergencyCall(call)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700566 LogUtil.i(
567 "InCallPresenter.shouldAttemptBlocking",
568 "Not attempting to block incoming emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800569 return false;
570 }
571 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700572 LogUtil.i(
573 "InCallPresenter.shouldAttemptBlocking",
574 "Not attempting to block incoming call due to recent emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800575 return false;
576 }
577 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
578 return false;
579 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700580 if (FilteredNumberCompat.useNewFiltering(mContext)) {
581 LogUtil.i(
582 "InCallPresenter.shouldAttemptBlocking",
583 "not attempting to block incoming call because framework blocking is in use");
584 return false;
585 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800586 return true;
587 }
588
589 /**
590 * Checks whether a call should be blocked, and blocks it if so. Otherwise, it adds the call to
591 * the CallList so it can proceed as normal. There is a timeout, so if the function for checking
592 * whether a function is blocked does not return in a reasonable time, we proceed with adding the
593 * call anyways.
594 */
595 private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) {
596 final String countryIso = GeoUtil.getCurrentCountryIso(mContext);
597 final String number = TelecomCallUtil.getNumber(call);
598 final long timeAdded = System.currentTimeMillis();
599
600 // Though AtomicBoolean's can be scary, don't fear, as in this case it is only used on the
601 // main UI thread. It is needed so we can change its value within different scopes, since
602 // that cannot be done with a final boolean.
603 final AtomicBoolean hasTimedOut = new AtomicBoolean(false);
604
605 final Handler handler = new Handler();
606
607 // Proceed if the query is slow; the call may still be blocked after the query returns.
608 final Runnable runnable =
609 new Runnable() {
610 @Override
611 public void run() {
612 hasTimedOut.set(true);
613 latencyReport.onCallBlockingDone();
614 mCallList.onCallAdded(mContext, call, latencyReport);
615 }
616 };
617 handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS);
618
619 OnCheckBlockedListener onCheckBlockedListener =
620 new OnCheckBlockedListener() {
621 @Override
622 public void onCheckComplete(final Integer id) {
623 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700624 LogUtil.i("InCallPresenter.onCheckComplete", "torn down, not adding call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800625 return;
626 }
627 if (!hasTimedOut.get()) {
628 handler.removeCallbacks(runnable);
629 }
630 if (id == null) {
631 if (!hasTimedOut.get()) {
632 latencyReport.onCallBlockingDone();
633 mCallList.onCallAdded(mContext, call, latencyReport);
634 }
635 } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700636 LogUtil.d(
637 "InCallPresenter.onCheckComplete", "invalid number, skipping block checking");
Eric Erfanianccca3152017-02-22 16:32:36 -0800638 if (!hasTimedOut.get()) {
639 handler.removeCallbacks(runnable);
640
641 latencyReport.onCallBlockingDone();
642 mCallList.onCallAdded(mContext, call, latencyReport);
643 }
644 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700645 LogUtil.i(
646 "InCallPresenter.onCheckComplete", "Rejecting incoming call from blocked number");
Eric Erfanianccca3152017-02-22 16:32:36 -0800647 call.reject(false, null);
648 Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED);
649
650 /*
651 * If mContext is null, then the InCallPresenter was torn down before the
652 * block check had a chance to complete. The context is no longer valid, so
653 * don't attempt to remove the call log entry.
654 */
655 if (mContext == null) {
656 return;
657 }
658 // Register observer to update the call log.
659 // BlockedNumberContentObserver will unregister after successful log or timeout.
660 BlockedNumberContentObserver contentObserver =
661 new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded);
662 contentObserver.register();
663 }
664 }
665 };
666
667 mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso);
668 }
669
670 public void onCallRemoved(android.telecom.Call call) {
671 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
672 mExternalCallList.onCallRemoved(call);
673 } else {
674 mCallList.onCallRemoved(mContext, call);
675 call.unregisterCallback(mCallCallback);
676 }
677 }
678
679 public void onCanAddCallChanged(boolean canAddCall) {
680 for (CanAddCallListener listener : mCanAddCallListeners) {
681 listener.onCanAddCallChanged(canAddCall);
682 }
683 }
684
685 @Override
686 public void onWiFiToLteHandover(DialerCall call) {
687 if (mInCallActivity != null) {
688 mInCallActivity.onWiFiToLteHandover(call);
689 }
690 }
691
692 @Override
693 public void onHandoverToWifiFailed(DialerCall call) {
694 if (mInCallActivity != null) {
695 mInCallActivity.onHandoverToWifiFailed(call);
696 }
697 }
698
Eric Erfanianc857f902017-05-15 14:05:33 -0700699 @Override
700 public void onInternationalCallOnWifi(@NonNull DialerCall call) {
701 LogUtil.enterBlock("InCallPresenter.onInternationalCallOnWifi");
702 if (mInCallActivity != null) {
703 mInCallActivity.onInternationalCallOnWifi(call);
704 }
705 }
706
Eric Erfanianccca3152017-02-22 16:32:36 -0800707 /**
708 * Called when there is a change to the call list. Sets the In-Call state for the entire in-call
709 * app based on the information it gets from CallList. Dispatches the in-call state to all
710 * listeners. Can trigger the creation or destruction of the UI based on the states that is
711 * calculates.
712 */
713 @Override
714 public void onCallListChange(CallList callList) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700715 Trace.beginSection("InCallPresenter.onCallListChange");
Eric Erfanianccca3152017-02-22 16:32:36 -0800716 if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) {
717 mAwaitingCallListUpdate = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700718 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800719 return;
720 }
721 if (callList == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700722 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800723 return;
724 }
725
726 mAwaitingCallListUpdate = false;
727
728 InCallState newState = getPotentialStateFromCallList(callList);
729 InCallState oldState = mInCallState;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700730 LogUtil.d(
731 "InCallPresenter.onCallListChange",
732 "onCallListChange oldState= " + oldState + " newState=" + newState);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700733
734 // If the user placed a call and was asked to choose the account, but then pressed "Home", the
735 // incall activity for that call will still exist (even if it's not visible). In the case of
736 // an incoming call in that situation, just disconnect that "waiting for account" call and
737 // dismiss the dialog. The same activity will be reused to handle the new incoming call. See
Eric Erfanian938468d2017-10-24 14:05:52 -0700738 // a bug for more details.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700739 DialerCall waitingForAccountCall;
740 if (newState == InCallState.INCOMING
741 && (waitingForAccountCall = callList.getWaitingForAccountCall()) != null) {
742 waitingForAccountCall.disconnect();
Eric Erfanian2ca43182017-08-31 06:57:16 -0700743 // The InCallActivity might be destroyed or not started yet at this point.
744 if (isActivityStarted()) {
745 mInCallActivity.dismissPendingDialogs();
746 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700747 }
748
Eric Erfanianccca3152017-02-22 16:32:36 -0800749 newState = startOrFinishUi(newState);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700750 LogUtil.d(
751 "InCallPresenter.onCallListChange", "onCallListChange newState changed to " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800752
753 // Set the new state before announcing it to the world
Eric Erfanian2ca43182017-08-31 06:57:16 -0700754 LogUtil.i(
755 "InCallPresenter.onCallListChange",
756 "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800757 mInCallState = newState;
758
759 // notify listeners of new state
760 for (InCallStateListener listener : mListeners) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700761 LogUtil.d(
762 "InCallPresenter.onCallListChange",
763 "Notify " + listener + " of state " + mInCallState.toString());
Eric Erfanianccca3152017-02-22 16:32:36 -0800764 listener.onStateChange(oldState, mInCallState, callList);
765 }
766
767 if (isActivityStarted()) {
768 final boolean hasCall =
769 callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null;
770 mInCallActivity.dismissKeyguard(hasCall);
771 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700772 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800773 }
774
775 /** Called when there is a new incoming call. */
776 @Override
777 public void onIncomingCall(DialerCall call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700778 Trace.beginSection("InCallPresenter.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800779 InCallState newState = startOrFinishUi(InCallState.INCOMING);
780 InCallState oldState = mInCallState;
781
Eric Erfanian2ca43182017-08-31 06:57:16 -0700782 LogUtil.i(
783 "InCallPresenter.onIncomingCall", "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800784 mInCallState = newState;
785
wangqicf61ca02017-08-31 15:32:55 -0700786 Trace.beginSection("listener.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800787 for (IncomingCallListener listener : mIncomingCallListeners) {
788 listener.onIncomingCall(oldState, mInCallState, call);
789 }
wangqicf61ca02017-08-31 15:32:55 -0700790 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800791
wangqicf61ca02017-08-31 15:32:55 -0700792 Trace.beginSection("onPrimaryCallStateChanged");
Eric Erfanianccca3152017-02-22 16:32:36 -0800793 if (mInCallActivity != null) {
794 // Re-evaluate which fragment is being shown.
795 mInCallActivity.onPrimaryCallStateChanged();
796 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700797 Trace.endSection();
wangqicf61ca02017-08-31 15:32:55 -0700798 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800799 }
800
801 @Override
802 public void onUpgradeToVideo(DialerCall call) {
Eric Erfanian90508232017-03-24 09:31:16 -0700803 if (VideoUtils.hasReceivedVideoUpgradeRequest(call.getVideoTech().getSessionModificationState())
Eric Erfanianccca3152017-02-22 16:32:36 -0800804 && mInCallState == InCallPresenter.InCallState.INCOMING) {
805 LogUtil.i(
806 "InCallPresenter.onUpgradeToVideo",
807 "rejecting upgrade request due to existing incoming call");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700808 call.getVideoTech().declineVideoRequest();
Eric Erfanianccca3152017-02-22 16:32:36 -0800809 }
810
811 if (mInCallActivity != null) {
812 // Re-evaluate which fragment is being shown.
813 mInCallActivity.onPrimaryCallStateChanged();
814 }
815 }
816
817 @Override
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700818 public void onSessionModificationStateChange(DialerCall call) {
819 int newState = call.getVideoTech().getSessionModificationState();
Eric Erfanianccca3152017-02-22 16:32:36 -0800820 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
821 if (mProximitySensor == null) {
822 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
823 return;
824 }
825 mProximitySensor.setIsAttemptingVideoCall(
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700826 call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest());
Eric Erfanianccca3152017-02-22 16:32:36 -0800827 if (mInCallActivity != null) {
828 // Re-evaluate which fragment is being shown.
829 mInCallActivity.onPrimaryCallStateChanged();
830 }
831 }
832
833 /**
834 * Called when a call becomes disconnected. Called everytime an existing call changes from being
835 * connected (incoming/outgoing/active) to disconnected.
836 */
837 @Override
838 public void onDisconnect(DialerCall call) {
839 maybeShowErrorDialogOnDisconnect(call);
840
841 // We need to do the run the same code as onCallListChange.
842 onCallListChange(mCallList);
843
844 if (isActivityStarted()) {
845 mInCallActivity.dismissKeyguard(false);
846 }
847
848 if (call.isEmergencyCall()) {
849 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
850 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800851
Eric Erfanianfc37b022017-03-21 10:11:17 -0700852 if (!mCallList.hasLiveCall()
853 && !call.getLogState().isIncoming
Eric Erfanian10b34a52017-05-04 08:23:17 -0700854 && !isSecretCode(call.getNumber())
wangqi9982f0d2017-10-11 17:46:07 -0700855 && !call.isVoiceMailNumber()) {
Eric Erfanian10b34a52017-05-04 08:23:17 -0700856 PostCall.onCallDisconnected(mContext, call.getNumber(), call.getConnectTimeMillis());
Eric Erfanianccca3152017-02-22 16:32:36 -0800857 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800858 }
859
Eric Erfanian10b34a52017-05-04 08:23:17 -0700860 private boolean isSecretCode(@Nullable String number) {
861 return number != null
862 && (number.length() <= 8 || number.startsWith("*#*#") || number.endsWith("#*#*"));
863 }
864
Eric Erfanianccca3152017-02-22 16:32:36 -0800865 /** Given the call list, return the state in which the in-call screen should be. */
866 public InCallState getPotentialStateFromCallList(CallList callList) {
867
868 InCallState newState = InCallState.NO_CALLS;
869
870 if (callList == null) {
871 return newState;
872 }
873 if (callList.getIncomingCall() != null) {
874 newState = InCallState.INCOMING;
875 } else if (callList.getWaitingForAccountCall() != null) {
876 newState = InCallState.WAITING_FOR_ACCOUNT;
877 } else if (callList.getPendingOutgoingCall() != null) {
878 newState = InCallState.PENDING_OUTGOING;
879 } else if (callList.getOutgoingCall() != null) {
880 newState = InCallState.OUTGOING;
881 } else if (callList.getActiveCall() != null
882 || callList.getBackgroundCall() != null
883 || callList.getDisconnectedCall() != null
884 || callList.getDisconnectingCall() != null) {
885 newState = InCallState.INCALL;
886 }
887
888 if (newState == InCallState.NO_CALLS) {
889 if (mBoundAndWaitingForOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700890 return InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800891 }
892 }
893
894 return newState;
895 }
896
897 public boolean isBoundAndWaitingForOutgoingCall() {
898 return mBoundAndWaitingForOutgoingCall;
899 }
900
901 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700902 LogUtil.i(
903 "InCallPresenter.setBoundAndWaitingForOutgoingCall",
904 "setBoundAndWaitingForOutgoingCall: " + isBound);
Eric Erfanianccca3152017-02-22 16:32:36 -0800905 mBoundAndWaitingForOutgoingCall = isBound;
906 mThemeColorManager.setPendingPhoneAccountHandle(handle);
907 if (isBound && mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700908 mInCallState = InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800909 }
910 }
911
912 public void onShrinkAnimationComplete() {
913 if (mAwaitingCallListUpdate) {
914 onCallListChange(mCallList);
915 }
916 }
917
918 public void addIncomingCallListener(IncomingCallListener listener) {
919 Objects.requireNonNull(listener);
920 mIncomingCallListeners.add(listener);
921 }
922
923 public void removeIncomingCallListener(IncomingCallListener listener) {
924 if (listener != null) {
925 mIncomingCallListeners.remove(listener);
926 }
927 }
928
929 public void addListener(InCallStateListener listener) {
930 Objects.requireNonNull(listener);
931 mListeners.add(listener);
932 }
933
934 public void removeListener(InCallStateListener listener) {
935 if (listener != null) {
936 mListeners.remove(listener);
937 }
938 }
939
940 public void addDetailsListener(InCallDetailsListener listener) {
941 Objects.requireNonNull(listener);
942 mDetailsListeners.add(listener);
943 }
944
945 public void removeDetailsListener(InCallDetailsListener listener) {
946 if (listener != null) {
947 mDetailsListeners.remove(listener);
948 }
949 }
950
951 public void addCanAddCallListener(CanAddCallListener listener) {
952 Objects.requireNonNull(listener);
953 mCanAddCallListeners.add(listener);
954 }
955
956 public void removeCanAddCallListener(CanAddCallListener listener) {
957 if (listener != null) {
958 mCanAddCallListeners.remove(listener);
959 }
960 }
961
962 public void addOrientationListener(InCallOrientationListener listener) {
963 Objects.requireNonNull(listener);
964 mOrientationListeners.add(listener);
965 }
966
967 public void removeOrientationListener(InCallOrientationListener listener) {
968 if (listener != null) {
969 mOrientationListeners.remove(listener);
970 }
971 }
972
973 public void addInCallEventListener(InCallEventListener listener) {
974 Objects.requireNonNull(listener);
975 mInCallEventListeners.add(listener);
976 }
977
978 public void removeInCallEventListener(InCallEventListener listener) {
979 if (listener != null) {
980 mInCallEventListeners.remove(listener);
981 }
982 }
983
984 public ProximitySensor getProximitySensor() {
985 return mProximitySensor;
986 }
987
988 public PseudoScreenState getPseudoScreenState() {
989 return mPseudoScreenState;
990 }
991
992 /** Returns true if the incall app is the foreground application. */
993 public boolean isShowingInCallUi() {
994 if (!isActivityStarted()) {
995 return false;
996 }
997 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
998 return true;
999 }
1000 return mInCallActivity.isVisible();
1001 }
1002
1003 /**
1004 * Returns true if the activity has been created and is running. Returns true as long as activity
1005 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
1006 * (not in foreground).
1007 */
1008 public boolean isActivityStarted() {
1009 return (mInCallActivity != null
1010 && !mInCallActivity.isDestroyed()
1011 && !mInCallActivity.isFinishing());
1012 }
1013
1014 /**
1015 * Determines if the In-Call app is currently changing configuration.
1016 *
1017 * @return {@code true} if the In-Call app is changing configuration.
1018 */
1019 public boolean isChangingConfigurations() {
1020 return mIsChangingConfigurations;
1021 }
1022
1023 /**
1024 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
1025 * screen orientation).
1026 */
1027 /*package*/
1028 void updateIsChangingConfigurations() {
1029 mIsChangingConfigurations = false;
1030 if (mInCallActivity != null) {
1031 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
1032 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001033 LogUtil.v(
1034 "InCallPresenter.updateIsChangingConfigurations",
1035 "updateIsChangingConfigurations = " + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001036 }
1037
1038 /** Called when the activity goes in/out of the foreground. */
1039 public void onUiShowing(boolean showing) {
1040 // We need to update the notification bar when we leave the UI because that
1041 // could trigger it to show again.
1042 if (mStatusBarNotifier != null) {
wangqic8cf79e2017-10-17 09:21:00 -07001043 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001044 }
1045
1046 if (mProximitySensor != null) {
1047 mProximitySensor.onInCallShowing(showing);
1048 }
1049
1050 Intent broadcastIntent = Bindings.get(mContext).getUiReadyBroadcastIntent(mContext);
1051 if (broadcastIntent != null) {
1052 broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
1053
1054 if (showing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001055 LogUtil.d("InCallPresenter.onUiShowing", "Sending sticky broadcast: ", broadcastIntent);
Eric Erfanianccca3152017-02-22 16:32:36 -08001056 mContext.sendStickyBroadcast(broadcastIntent);
1057 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001058 LogUtil.d("InCallPresenter.onUiShowing", "Removing sticky broadcast: ", broadcastIntent);
Eric Erfanianccca3152017-02-22 16:32:36 -08001059 mContext.removeStickyBroadcast(broadcastIntent);
1060 }
1061 }
1062
1063 if (showing) {
1064 mIsActivityPreviouslyStarted = true;
1065 } else {
1066 updateIsChangingConfigurations();
1067 }
1068
1069 for (InCallUiListener listener : mInCallUiListeners) {
1070 listener.onUiShowing(showing);
1071 }
1072
1073 if (mInCallActivity != null) {
1074 // Re-evaluate which fragment is being shown.
1075 mInCallActivity.onPrimaryCallStateChanged();
1076 }
1077 }
1078
Eric Erfanian2ca43182017-08-31 06:57:16 -07001079 public void refreshUi() {
1080 if (mInCallActivity != null) {
1081 // Re-evaluate which fragment is being shown.
1082 mInCallActivity.onPrimaryCallStateChanged();
1083 }
1084 }
1085
Eric Erfanianccca3152017-02-22 16:32:36 -08001086 public void addInCallUiListener(InCallUiListener listener) {
1087 mInCallUiListeners.add(listener);
1088 }
1089
1090 public boolean removeInCallUiListener(InCallUiListener listener) {
1091 return mInCallUiListeners.remove(listener);
1092 }
1093
1094 /*package*/
1095 void onActivityStarted() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001096 LogUtil.d("InCallPresenter.onActivityStarted", "onActivityStarted");
Eric Erfanianccca3152017-02-22 16:32:36 -08001097 notifyVideoPauseController(true);
Eric Erfanian2ca43182017-08-31 06:57:16 -07001098 applyScreenTimeout();
Eric Erfanianccca3152017-02-22 16:32:36 -08001099 }
1100
1101 /*package*/
1102 void onActivityStopped() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001103 LogUtil.d("InCallPresenter.onActivityStopped", "onActivityStopped");
Eric Erfanianccca3152017-02-22 16:32:36 -08001104 notifyVideoPauseController(false);
1105 }
1106
1107 private void notifyVideoPauseController(boolean showing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001108 LogUtil.d(
1109 "InCallPresenter.notifyVideoPauseController",
1110 "mIsChangingConfigurations=" + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001111 if (!mIsChangingConfigurations) {
1112 VideoPauseController.getInstance().onUiShowing(showing);
1113 }
1114 }
1115
1116 /** Brings the app into the foreground if possible. */
1117 public void bringToForeground(boolean showDialpad) {
1118 // Before we bring the incall UI to the foreground, we check to see if:
1119 // 1. It is not currently in the foreground
1120 // 2. We are in a state where we want to show the incall ui (i.e. there are calls to
1121 // be displayed)
1122 // If the activity hadn't actually been started previously, yet there are still calls
1123 // present (e.g. a call was accepted by a bluetooth or wired headset), we want to
1124 // bring it up the UI regardless.
1125 if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001126 showInCall(showDialpad, false /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001127 }
1128 }
1129
1130 public void onPostDialCharWait(String callId, String chars) {
1131 if (isActivityStarted()) {
1132 mInCallActivity.showPostCharWaitDialog(callId, chars);
1133 }
1134 }
1135
1136 /**
1137 * Handles the green CALL key while in-call.
1138 *
1139 * @return true if we consumed the event.
1140 */
1141 public boolean handleCallKey() {
1142 LogUtil.v("InCallPresenter.handleCallKey", null);
1143
1144 // The green CALL button means either "Answer", "Unhold", or
1145 // "Swap calls", or can be a no-op, depending on the current state
1146 // of the Phone.
1147
1148 /** INCOMING CALL */
1149 final CallList calls = mCallList;
1150 final DialerCall incomingCall = calls.getIncomingCall();
1151 LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall);
1152
1153 // (1) Attempt to answer a call
1154 if (incomingCall != null) {
1155 incomingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
1156 return true;
1157 }
1158
1159 /** STATE_ACTIVE CALL */
1160 final DialerCall activeCall = calls.getActiveCall();
1161 if (activeCall != null) {
1162 // TODO: This logic is repeated from CallButtonPresenter.java. We should
1163 // consolidate this logic.
1164 final boolean canMerge =
1165 activeCall.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
1166 final boolean canSwap =
1167 activeCall.can(android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
1168
Eric Erfanian2ca43182017-08-31 06:57:16 -07001169 LogUtil.v(
1170 "InCallPresenter.handleCallKey",
1171 "activeCall: " + activeCall + ", canMerge: " + canMerge + ", canSwap: " + canSwap);
Eric Erfanianccca3152017-02-22 16:32:36 -08001172
1173 // (2) Attempt actions on conference calls
1174 if (canMerge) {
1175 TelecomAdapter.getInstance().merge(activeCall.getId());
1176 return true;
1177 } else if (canSwap) {
1178 TelecomAdapter.getInstance().swap(activeCall.getId());
1179 return true;
1180 }
1181 }
1182
1183 /** BACKGROUND CALL */
1184 final DialerCall heldCall = calls.getBackgroundCall();
1185 if (heldCall != null) {
1186 // We have a hold call so presumeable it will always support HOLD...but
1187 // there is no harm in double checking.
1188 final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
1189
Eric Erfanian2ca43182017-08-31 06:57:16 -07001190 LogUtil.v("InCallPresenter.handleCallKey", "heldCall: " + heldCall + ", canHold: " + canHold);
Eric Erfanianccca3152017-02-22 16:32:36 -08001191
1192 // (4) unhold call
1193 if (heldCall.getState() == DialerCall.State.ONHOLD && canHold) {
1194 heldCall.unhold();
1195 return true;
1196 }
1197 }
1198
1199 // Always consume hard keys
1200 return true;
1201 }
1202
Eric Erfanianccca3152017-02-22 16:32:36 -08001203 /** Clears the previous fullscreen state. */
1204 public void clearFullscreen() {
1205 mIsFullScreen = false;
1206 }
1207
1208 /**
1209 * Changes the fullscreen mode of the in-call UI.
1210 *
1211 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1212 * otherwise.
1213 */
1214 public void setFullScreen(boolean isFullScreen) {
1215 setFullScreen(isFullScreen, false /* force */);
1216 }
1217
1218 /**
1219 * Changes the fullscreen mode of the in-call UI.
1220 *
1221 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1222 * otherwise.
1223 * @param force {@code true} if fullscreen mode should be set regardless of its current state.
1224 */
1225 public void setFullScreen(boolean isFullScreen, boolean force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001226 LogUtil.i("InCallPresenter.setFullScreen", "setFullScreen = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001227
1228 // As a safeguard, ensure we cannot enter fullscreen if the dialpad is shown.
1229 if (isDialpadVisible()) {
1230 isFullScreen = false;
Eric Erfanian2ca43182017-08-31 06:57:16 -07001231 LogUtil.v(
1232 "InCallPresenter.setFullScreen",
1233 "setFullScreen overridden as dialpad is shown = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001234 }
1235
1236 if (mIsFullScreen == isFullScreen && !force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001237 LogUtil.v("InCallPresenter.setFullScreen", "setFullScreen ignored as already in that state.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001238 return;
1239 }
1240 mIsFullScreen = isFullScreen;
1241 notifyFullscreenModeChange(mIsFullScreen);
1242 }
1243
1244 /**
1245 * @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
1246 * otherwise.
1247 */
1248 public boolean isFullscreen() {
1249 return mIsFullScreen;
1250 }
1251
1252 /**
1253 * Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
1254 *
1255 * @param isFullscreenMode {@code True} if entering full screen mode.
1256 */
1257 public void notifyFullscreenModeChange(boolean isFullscreenMode) {
1258 for (InCallEventListener listener : mInCallEventListeners) {
1259 listener.onFullscreenModeChanged(isFullscreenMode);
1260 }
1261 }
1262
1263 /**
1264 * For some disconnected causes, we show a dialog. This calls into the activity to show the dialog
1265 * if appropriate for the call.
1266 */
1267 private void maybeShowErrorDialogOnDisconnect(DialerCall call) {
1268 // For newly disconnected calls, we may want to show a dialog on specific error conditions
1269 if (isActivityStarted() && call.getState() == DialerCall.State.DISCONNECTED) {
1270 if (call.getAccountHandle() == null && !call.isConferenceCall()) {
1271 setDisconnectCauseForMissingAccounts(call);
1272 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001273 mInCallActivity.maybeShowErrorDialogOnDisconnect(
1274 new DisconnectMessage(mInCallActivity, call));
Eric Erfanianccca3152017-02-22 16:32:36 -08001275 }
1276 }
1277
1278 /**
1279 * When the state of in-call changes, this is the first method to get called. It determines if the
1280 * UI needs to be started or finished depending on the new state and does it.
1281 */
1282 private InCallState startOrFinishUi(InCallState newState) {
wangqicf61ca02017-08-31 15:32:55 -07001283 Trace.beginSection("InCallPresenter.startOrFinishUi");
Eric Erfanian2ca43182017-08-31 06:57:16 -07001284 LogUtil.d(
1285 "InCallPresenter.startOrFinishUi", "startOrFinishUi: " + mInCallState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -08001286
1287 // TODO: Consider a proper state machine implementation
1288
1289 // If the state isn't changing we have already done any starting/stopping of activities in
1290 // a previous pass...so lets cut out early
1291 if (newState == mInCallState) {
wangqicf61ca02017-08-31 15:32:55 -07001292 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001293 return newState;
1294 }
1295
1296 // A new Incoming call means that the user needs to be notified of the the call (since
1297 // it wasn't them who initiated it). We do this through full screen notifications and
1298 // happens indirectly through {@link StatusBarNotifier}.
1299 //
1300 // The process for incoming calls is as follows:
1301 //
1302 // 1) CallList - Announces existence of new INCOMING call
1303 // 2) InCallPresenter - Gets announcement and calculates that the new InCallState
1304 // - should be set to INCOMING.
1305 // 3) InCallPresenter - This method is called to see if we need to start or finish
1306 // the app given the new state.
1307 // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
1308 // StatusBarNotifier explicitly to issue a FullScreen Notification
1309 // that will either start the InCallActivity or show the user a
1310 // top-level notification dialog if the user is in an immersive app.
1311 // That notification can also start the InCallActivity.
1312 // 5) InCallActivity - Main activity starts up and at the end of its onCreate will
1313 // call InCallPresenter::setActivity() to let the presenter
1314 // know that start-up is complete.
1315 //
1316 // [ AND NOW YOU'RE IN THE CALL. voila! ]
1317 //
1318 // Our app is started using a fullScreen notification. We need to do this whenever
1319 // we get an incoming call. Depending on the current context of the device, either a
1320 // incoming call HUN or the actual InCallActivity will be shown.
1321 final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
1322
1323 // A dialog to show on top of the InCallUI to select a PhoneAccount
1324 final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
1325
1326 // A new outgoing call indicates that the user just now dialed a number and when that
1327 // happens we need to display the screen immediately or show an account picker dialog if
1328 // no default is set. However, if the main InCallUI is already visible, we do not want to
1329 // re-initiate the start-up animation, so we do not need to do anything here.
1330 //
1331 // It is also possible to go into an intermediate state where the call has been initiated
1332 // but Telecom has not yet returned with the details of the call (handle, gateway, etc.).
1333 // This pending outgoing state can also launch the call screen.
1334 //
1335 // This is different from the incoming call sequence because we do not need to shock the
1336 // user with a top-level notification. Just show the call UI normally.
1337 boolean callCardFragmentVisible =
1338 mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible();
1339 final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible;
1340 boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
1341
1342 // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
1343 // outgoing call process, so the UI should be brought up to show an error dialog.
1344 showCallUi |=
1345 (InCallState.PENDING_OUTGOING == mInCallState
1346 && InCallState.INCALL == newState
1347 && !isShowingInCallUi());
1348
1349 // Another exception - InCallActivity is in charge of disconnecting a call with no
1350 // valid accounts set. Bring the UI up if this is true for the current pending outgoing
1351 // call so that:
1352 // 1) The call can be disconnected correctly
1353 // 2) The UI comes up and correctly displays the error dialog.
1354 // TODO: Remove these special case conditions by making InCallPresenter a true state
1355 // machine. Telecom should also be the component responsible for disconnecting a call
1356 // with no valid accounts.
1357 showCallUi |=
1358 InCallState.PENDING_OUTGOING == newState
1359 && mainUiNotVisible
1360 && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
1361
1362 // The only time that we have an instance of mInCallActivity and it isn't started is
1363 // when it is being destroyed. In that case, lets avoid bringing up another instance of
1364 // the activity. When it is finally destroyed, we double check if we should bring it back
1365 // up so we aren't going to lose anything by avoiding a second startup here.
1366 boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
1367 if (activityIsFinishing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001368 LogUtil.i(
1369 "InCallPresenter.startOrFinishUi",
1370 "Undo the state change: " + newState + " -> " + mInCallState);
wangqicf61ca02017-08-31 15:32:55 -07001371 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001372 return mInCallState;
1373 }
1374
1375 // We're about the bring up the in-call UI for outgoing and incoming call. If we still have
1376 // dialogs up, we need to clear them out before showing in-call screen. This is necessary
1377 // to fix the bug that dialog will show up when data reaches limit even after makeing new
1378 // outgoing call after user ignore it by pressing home button.
1379 if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING)
1380 && !showCallUi
1381 && isActivityStarted()) {
1382 mInCallActivity.dismissPendingDialogs();
1383 }
1384
1385 if (showCallUi || showAccountPicker) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001386 LogUtil.i("InCallPresenter.startOrFinishUi", "Start in call UI");
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001387 showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001388 } else if (startIncomingCallSequence) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001389 LogUtil.i("InCallPresenter.startOrFinishUi", "Start Full Screen in call UI");
Eric Erfanianccca3152017-02-22 16:32:36 -08001390
wangqic8cf79e2017-10-17 09:21:00 -07001391 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001392 } else if (newState == InCallState.NO_CALLS) {
1393 // The new state is the no calls state. Tear everything down.
1394 attemptFinishActivity();
1395 attemptCleanup();
1396 }
1397
wangqicf61ca02017-08-31 15:32:55 -07001398 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001399 return newState;
1400 }
1401
1402 /**
1403 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1404 * or PhoneAccounts to select from.
1405 */
1406 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1407
1408 Bundle extras = call.getIntentExtras();
1409 // Initialize the extras bundle to avoid NPE
1410 if (extras == null) {
1411 extras = new Bundle();
1412 }
1413
1414 final List<PhoneAccountHandle> phoneAccountHandles =
1415 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1416
1417 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1418 String scheme = call.getHandle().getScheme();
1419 final String errorMsg =
1420 PhoneAccount.SCHEME_TEL.equals(scheme)
1421 ? mContext.getString(R.string.callFailed_simError)
1422 : mContext.getString(R.string.incall_error_supp_service_unknown);
1423 DisconnectCause disconnectCause =
1424 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1425 call.setDisconnectCause(disconnectCause);
1426 }
1427 }
1428
Eric Erfanianccca3152017-02-22 16:32:36 -08001429 /**
1430 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1431 * Calling classes should use this as an indication whether to interact with the
1432 * InCallPresenter or not.
1433 */
1434 public boolean isReadyForTearDown() {
1435 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1436 }
1437
1438 /**
1439 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1440 */
1441 private void attemptCleanup() {
1442 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001443 LogUtil.i("InCallPresenter.attemptCleanup", "Cleaning up");
Eric Erfanianccca3152017-02-22 16:32:36 -08001444
1445 cleanupSurfaces();
1446
1447 mIsActivityPreviouslyStarted = false;
1448 mIsChangingConfigurations = false;
1449
1450 // blow away stale contact info so that we get fresh data on
1451 // the next set of calls
1452 if (mContactInfoCache != null) {
1453 mContactInfoCache.clearCache();
1454 }
1455 mContactInfoCache = null;
1456
1457 if (mProximitySensor != null) {
1458 removeListener(mProximitySensor);
1459 mProximitySensor.tearDown();
1460 }
1461 mProximitySensor = null;
1462
1463 if (mStatusBarNotifier != null) {
1464 removeListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -07001465 EnrichedCallComponent.get(mContext)
1466 .getEnrichedCallManager()
1467 .unregisterStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -08001468 }
Eric Erfaniand8046e52017-04-06 09:41:50 -07001469
Eric Erfanianccca3152017-02-22 16:32:36 -08001470 if (mExternalCallNotifier != null && mExternalCallList != null) {
1471 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1472 }
1473 mStatusBarNotifier = null;
1474
1475 if (mCallList != null) {
1476 mCallList.removeListener(this);
1477 mCallList.removeListener(mSpamCallListListener);
1478 }
1479 mCallList = null;
1480
1481 mContext = null;
1482 mInCallActivity = null;
1483 mManageConferenceActivity = null;
1484
1485 mListeners.clear();
1486 mIncomingCallListeners.clear();
1487 mDetailsListeners.clear();
1488 mCanAddCallListeners.clear();
1489 mOrientationListeners.clear();
1490 mInCallEventListeners.clear();
1491 mInCallUiListeners.clear();
twyen8efb4952017-10-06 16:35:54 -07001492 if (!mInCallUiLocks.isEmpty()) {
1493 LogUtil.e("InCallPresenter.attemptCleanup", "held in call locks: " + mInCallUiLocks);
1494 mInCallUiLocks.clear();
1495 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001496 LogUtil.d("InCallPresenter.attemptCleanup", "finished");
Eric Erfanianccca3152017-02-22 16:32:36 -08001497 }
1498 }
1499
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001500 public void showInCall(boolean showDialpad, boolean newOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001501 LogUtil.i("InCallPresenter.showInCall", "Showing InCallActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -08001502 mContext.startActivity(
1503 InCallActivity.getIntent(
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001504 mContext, showDialpad, newOutgoingCall, false /* forFullScreen */));
Eric Erfanianccca3152017-02-22 16:32:36 -08001505 }
1506
1507 public void onServiceBind() {
1508 mServiceBound = true;
1509 }
1510
1511 public void onServiceUnbind() {
1512 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1513 mServiceBound = false;
1514 }
1515
1516 public boolean isServiceBound() {
1517 return mServiceBound;
1518 }
1519
1520 public void maybeStartRevealAnimation(Intent intent) {
1521 if (intent == null || mInCallActivity != null) {
1522 return;
1523 }
1524 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1525 if (extras == null) {
1526 // Incoming call, just show the in-call UI directly.
1527 return;
1528 }
1529
1530 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1531 // Account selection dialog will show up so don't show the animation.
1532 return;
1533 }
1534
1535 final PhoneAccountHandle accountHandle =
1536 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1537 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
Eric Erfanianccca3152017-02-22 16:32:36 -08001538
1539 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1540
1541 final Intent activityIntent =
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001542 InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001543 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1544 mContext.startActivity(activityIntent);
1545 }
1546
1547 /**
1548 * Retrieves the current in-call camera manager instance, creating if necessary.
1549 *
1550 * @return The {@link InCallCameraManager}.
1551 */
1552 public InCallCameraManager getInCallCameraManager() {
1553 synchronized (this) {
1554 if (mInCallCameraManager == null) {
1555 mInCallCameraManager = new InCallCameraManager(mContext);
1556 }
1557
1558 return mInCallCameraManager;
1559 }
1560 }
1561
1562 /**
1563 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1564 *
1565 * @param orientation The screen orientation of the device (one of: {@link
1566 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1567 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1568 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1569 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1570 */
1571 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001572 LogUtil.d(
1573 "InCallPresenter.onDeviceOrientationChange",
1574 "onDeviceOrientationChange: orientation= " + orientation);
Eric Erfanianccca3152017-02-22 16:32:36 -08001575
1576 if (mCallList != null) {
1577 mCallList.notifyCallsOfDeviceRotation(orientation);
1578 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001579 LogUtil.w("InCallPresenter.onDeviceOrientationChange", "CallList is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001580 }
1581
1582 // Notify listeners of device orientation changed.
1583 for (InCallOrientationListener listener : mOrientationListeners) {
1584 listener.onDeviceOrientationChanged(orientation);
1585 }
1586 }
1587
1588 /**
1589 * Configures the in-call UI activity so it can change orientations or not. Enables the
1590 * orientation event listener if allowOrientationChange is true, disables it if false.
1591 *
1592 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1593 * landscape. {@code false} if the in-call UI should be locked in portrait.
1594 */
1595 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1596 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001597 LogUtil.e(
1598 "InCallPresenter.setInCallAllowsOrientationChange",
1599 "InCallActivity is null. Can't set requested orientation.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001600 return;
1601 }
1602 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1603 }
1604
1605 public void enableScreenTimeout(boolean enable) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001606 LogUtil.v("InCallPresenter.enableScreenTimeout", "enableScreenTimeout: value=" + enable);
1607 mScreenTimeoutEnabled = enable;
1608 applyScreenTimeout();
1609 }
1610
1611 private void applyScreenTimeout() {
Eric Erfanianccca3152017-02-22 16:32:36 -08001612 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001613 LogUtil.e("InCallPresenter.applyScreenTimeout", "InCallActivity is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001614 return;
1615 }
1616
1617 final Window window = mInCallActivity.getWindow();
Eric Erfanian2ca43182017-08-31 06:57:16 -07001618 if (mScreenTimeoutEnabled) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001619 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1620 } else {
1621 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1622 }
1623 }
1624
1625 /**
1626 * Hides or shows the conference manager fragment.
1627 *
1628 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1629 * be hidden.
1630 */
1631 public void showConferenceCallManager(boolean show) {
1632 if (mInCallActivity != null) {
1633 mInCallActivity.showConferenceFragment(show);
1634 }
1635 if (!show && mManageConferenceActivity != null) {
1636 mManageConferenceActivity.finish();
1637 }
1638 }
1639
1640 /**
1641 * Determines if the dialpad is visible.
1642 *
1643 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1644 */
1645 public boolean isDialpadVisible() {
1646 if (mInCallActivity == null) {
1647 return false;
1648 }
1649 return mInCallActivity.isDialpadVisible();
1650 }
1651
1652 public ThemeColorManager getThemeColorManager() {
1653 return mThemeColorManager;
1654 }
1655
wangqi8d662ca2017-10-26 11:27:19 -07001656 @VisibleForTesting
1657 public void setThemeColorManager(ThemeColorManager themeColorManager) {
1658 mThemeColorManager = themeColorManager;
1659 }
1660
Eric Erfanianccca3152017-02-22 16:32:36 -08001661 /** Called when the foreground call changes. */
1662 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1663 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1664 if (mInCallActivity != null) {
1665 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1666 }
1667 }
1668
1669 public InCallActivity getActivity() {
1670 return mInCallActivity;
1671 }
1672
1673 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1674 public void setActivity(InCallActivity inCallActivity) {
1675 if (inCallActivity == null) {
1676 throw new IllegalArgumentException("registerActivity cannot be called with null");
1677 }
1678 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001679 LogUtil.w(
1680 "InCallPresenter.setActivity", "Setting a second activity before destroying the first.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001681 }
1682 updateActivity(inCallActivity);
1683 }
1684
1685 ExternalCallNotifier getExternalCallNotifier() {
1686 return mExternalCallNotifier;
1687 }
1688
1689 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1690 if (mLocalVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001691 boolean isPixel2017 = false;
1692 if (mContext != null) {
1693 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1694 }
1695 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001696 }
1697 return mLocalVideoSurfaceTexture;
1698 }
1699
1700 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1701 if (mRemoteVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001702 boolean isPixel2017 = false;
1703 if (mContext != null) {
1704 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1705 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001706 mRemoteVideoSurfaceTexture =
roldenburg12b50c62017-09-01 14:41:19 -07001707 VideoSurfaceBindings.createRemoteVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001708 }
1709 return mRemoteVideoSurfaceTexture;
1710 }
1711
1712 void cleanupSurfaces() {
1713 if (mRemoteVideoSurfaceTexture != null) {
1714 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1715 mRemoteVideoSurfaceTexture = null;
1716 }
1717 if (mLocalVideoSurfaceTexture != null) {
1718 mLocalVideoSurfaceTexture.setDoneWithSurface();
1719 mLocalVideoSurfaceTexture = null;
1720 }
1721 }
1722
1723 /** All the main states of InCallActivity. */
1724 public enum InCallState {
1725 // InCall Screen is off and there are no calls
1726 NO_CALLS,
1727
1728 // Incoming-call screen is up
1729 INCOMING,
1730
1731 // In-call experience is showing
1732 INCALL,
1733
1734 // Waiting for user input before placing outgoing call
1735 WAITING_FOR_ACCOUNT,
1736
1737 // UI is starting up but no call has been initiated yet.
1738 // The UI is waiting for Telecom to respond.
1739 PENDING_OUTGOING,
1740
1741 // User is dialing out
1742 OUTGOING;
1743
1744 public boolean isIncoming() {
1745 return (this == INCOMING);
1746 }
1747
1748 public boolean isConnectingOrConnected() {
1749 return (this == INCOMING || this == OUTGOING || this == INCALL);
1750 }
1751 }
1752
1753 /** Interface implemented by classes that need to know about the InCall State. */
1754 public interface InCallStateListener {
1755
1756 // TODO: Enhance state to contain the call objects instead of passing CallList
1757 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1758 }
1759
1760 public interface IncomingCallListener {
1761
1762 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1763 }
1764
1765 public interface CanAddCallListener {
1766
1767 void onCanAddCallChanged(boolean canAddCall);
1768 }
1769
1770 public interface InCallDetailsListener {
1771
1772 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1773 }
1774
1775 public interface InCallOrientationListener {
1776
1777 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1778 }
1779
1780 /**
1781 * Interface implemented by classes that need to know about events which occur within the In-Call
1782 * UI. Used as a means of communicating between fragments that make up the UI.
1783 */
1784 public interface InCallEventListener {
1785
1786 void onFullscreenModeChanged(boolean isFullscreenMode);
1787 }
1788
1789 public interface InCallUiListener {
1790
1791 void onUiShowing(boolean showing);
1792 }
twyen8efb4952017-10-06 16:35:54 -07001793
1794 private class InCallUiLockImpl implements InCallUiLock {
1795 private final String tag;
1796
1797 private InCallUiLockImpl(String tag) {
1798 this.tag = tag;
1799 }
1800
1801 @MainThread
1802 @Override
1803 public void release() {
1804 Assert.isMainThread();
1805 releaseInCallUiLock(InCallUiLockImpl.this);
1806 }
1807
1808 @Override
1809 public String toString() {
1810 return "InCallUiLock[" + tag + "]";
1811 }
1812 }
1813
1814 @MainThread
1815 public InCallUiLock acquireInCallUiLock(String tag) {
1816 Assert.isMainThread();
1817 InCallUiLock lock = new InCallUiLockImpl(tag);
1818 mInCallUiLocks.add(lock);
1819 return lock;
1820 }
1821
1822 @MainThread
1823 private void releaseInCallUiLock(InCallUiLock lock) {
1824 Assert.isMainThread();
1825 LogUtil.i("InCallPresenter.releaseInCallUiLock", "releasing %s", lock);
1826 mInCallUiLocks.remove(lock);
1827 if (mInCallUiLocks.isEmpty()) {
1828 LogUtil.i("InCallPresenter.releaseInCallUiLock", "all locks released");
1829 if (mInCallState == InCallState.NO_CALLS) {
1830 LogUtil.i("InCallPresenter.releaseInCallUiLock", "no more calls, finishing UI");
1831 attemptFinishActivity();
1832 attemptCleanup();
1833 }
1834 }
1835 }
1836
1837 @MainThread
1838 public boolean isInCallUiLocked() {
1839 Assert.isMainThread();
1840 if (mInCallUiLocks.isEmpty()) {
1841 return false;
1842 }
1843 for (InCallUiLock lock : mInCallUiLocks) {
1844 LogUtil.i("InCallPresenter.isInCallUiLocked", "still locked by %s", lock);
1845 }
1846 return true;
1847 }
1848
1849 private final Set<InCallUiLock> mInCallUiLocks = new ArraySet<>();
Eric Erfanianccca3152017-02-22 16:32:36 -08001850}