blob: b8a2baa00db6def74a29f47e6eab865076a7b788 [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;
Eric Erfanian2ca43182017-08-31 06:57:16 -070048import com.android.dialer.common.concurrent.DefaultDialerExecutorFactory;
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
360 mThemeColorManager =
361 new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources()));
362
363 mCallList = callList;
364 mExternalCallList = externalCallList;
365 externalCallList.addExternalCallListener(mExternalCallNotifier);
366 externalCallList.addExternalCallListener(mExternalCallListener);
367
368 // This only gets called by the service so this is okay.
369 mServiceConnected = true;
370
371 // The final thing we do in this set up is add ourselves as a listener to CallList. This
372 // will kick off an update and the whole process can start.
373 mCallList.addListener(this);
374
375 // Create spam call list listener and add it to the list of listeners
Eric Erfanian2ca43182017-08-31 06:57:16 -0700376 mSpamCallListListener = new SpamCallListListener(context, new DefaultDialerExecutorFactory());
Eric Erfanianccca3152017-02-22 16:32:36 -0800377 mCallList.addListener(mSpamCallListListener);
378
379 VideoPauseController.getInstance().setUp(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800380
Eric Erfanian83b20212017-05-31 08:53:10 -0700381 mFilteredQueryHandler = filteredNumberQueryHandler;
Eric Erfanianccca3152017-02-22 16:32:36 -0800382 mContext
383 .getSystemService(TelephonyManager.class)
384 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
385
Eric Erfanian2ca43182017-08-31 06:57:16 -0700386 LogUtil.d("InCallPresenter.setUp", "Finished InCallPresenter.setUp");
387 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800388 }
389
390 /**
391 * Called when the telephony service has disconnected from us. This will happen when there are no
392 * more active calls. However, we may still want to continue showing the UI for certain cases like
393 * showing "Call Ended". What we really want is to wait for the activity and the service to both
394 * disconnect before we tear things down. This method sets a serviceConnected boolean and calls a
395 * secondary method that performs the aforementioned logic.
396 */
397 public void tearDown() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700398 LogUtil.d("InCallPresenter.tearDown", "tearDown");
Eric Erfanianccca3152017-02-22 16:32:36 -0800399 mCallList.clearOnDisconnect();
400
401 mServiceConnected = false;
402
403 mContext
404 .getSystemService(TelephonyManager.class)
405 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
406
407 attemptCleanup();
408 VideoPauseController.getInstance().tearDown();
Eric Erfanianccca3152017-02-22 16:32:36 -0800409 }
410
411 private void attemptFinishActivity() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700412 mScreenTimeoutEnabled = true;
Eric Erfanianccca3152017-02-22 16:32:36 -0800413 final boolean doFinish = (mInCallActivity != null && isActivityStarted());
Eric Erfanian2ca43182017-08-31 06:57:16 -0700414 LogUtil.i("InCallPresenter.attemptFinishActivity", "Hide in call UI: " + doFinish);
Eric Erfanianccca3152017-02-22 16:32:36 -0800415 if (doFinish) {
416 mInCallActivity.setExcludeFromRecents(true);
417 mInCallActivity.finish();
Eric Erfanianccca3152017-02-22 16:32:36 -0800418 }
419 }
420
421 /**
422 * Called when the UI ends. Attempts to tear down everything if necessary. See {@link #tearDown()}
423 * for more insight on the tear-down process.
424 */
425 public void unsetActivity(InCallActivity inCallActivity) {
426 if (inCallActivity == null) {
427 throw new IllegalArgumentException("unregisterActivity cannot be called with null");
428 }
429 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700430 LogUtil.i(
431 "InCallPresenter.unsetActivity", "No InCallActivity currently set, no need to unset.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800432 return;
433 }
434 if (mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700435 LogUtil.w(
436 "InCallPresenter.unsetActivity",
Eric Erfanianccca3152017-02-22 16:32:36 -0800437 "Second instance of InCallActivity is trying to unregister when another"
438 + " instance is active. Ignoring.");
439 return;
440 }
441 updateActivity(null);
442 }
443
444 /**
445 * Updates the current instance of {@link InCallActivity} with the provided one. If a {@code null}
446 * activity is provided, it means that the activity was finished and we should attempt to cleanup.
447 */
448 private void updateActivity(InCallActivity inCallActivity) {
wangqi9982f0d2017-10-11 17:46:07 -0700449 Trace.beginSection("InCallPresenter.updateActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -0800450 boolean updateListeners = false;
451 boolean doAttemptCleanup = false;
452
453 if (inCallActivity != null) {
454 if (mInCallActivity == null) {
Eric Erfanian938468d2017-10-24 14:05:52 -0700455 mContext = inCallActivity.getApplicationContext();
Eric Erfanianccca3152017-02-22 16:32:36 -0800456 updateListeners = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700457 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized");
Eric Erfanianccca3152017-02-22 16:32:36 -0800458 } else {
459 // since setActivity is called onStart(), it can be called multiple times.
460 // This is fine and ignorable, but we do not want to update the world every time
461 // this happens (like going to/from background) so we do not set updateListeners.
462 }
463
464 mInCallActivity = inCallActivity;
465 mInCallActivity.setExcludeFromRecents(false);
466
467 // By the time the UI finally comes up, the call may already be disconnected.
468 // If that's the case, we may need to show an error dialog.
469 if (mCallList != null && mCallList.getDisconnectedCall() != null) {
470 maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
471 }
472
473 // When the UI comes up, we need to first check the in-call state.
474 // If we are showing NO_CALLS, that means that a call probably connected and
475 // then immediately disconnected before the UI was able to come up.
476 // If we dont have any calls, start tearing down the UI instead.
477 // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
478 // it has been set.
479 if (mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700480 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized, but no calls left. Shut down");
Eric Erfanianccca3152017-02-22 16:32:36 -0800481 attemptFinishActivity();
wangqi9982f0d2017-10-11 17:46:07 -0700482 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800483 return;
484 }
485 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700486 LogUtil.i("InCallPresenter.updateActivity", "UI Destroyed");
Eric Erfanianccca3152017-02-22 16:32:36 -0800487 updateListeners = true;
488 mInCallActivity = null;
489
490 // We attempt cleanup for the destroy case but only after we recalculate the state
491 // to see if we need to come back up or stay shut down. This is why we do the
492 // cleanup after the call to onCallListChange() instead of directly here.
493 doAttemptCleanup = true;
494 }
495
496 // Messages can come from the telephony layer while the activity is coming up
497 // and while the activity is going down. So in both cases we need to recalculate what
498 // state we should be in after they complete.
499 // Examples: (1) A new incoming call could come in and then get disconnected before
500 // the activity is created.
501 // (2) All calls could disconnect and then get a new incoming call before the
502 // activity is destroyed.
503 //
Eric Erfanian938468d2017-10-24 14:05:52 -0700504 // a bug - We previously had a check for mServiceConnected here as well, but there are
Eric Erfanianccca3152017-02-22 16:32:36 -0800505 // cases where we need to recalculate the current state even if the service in not
506 // connected. In particular the case where startOrFinish() is called while the app is
507 // already finish()ing. In that case, we skip updating the state with the knowledge that
508 // we will check again once the activity has finished. That means we have to recalculate the
509 // state here even if the service is disconnected since we may not have finished a state
510 // transition while finish()ing.
511 if (updateListeners) {
512 onCallListChange(mCallList);
513 }
514
515 if (doAttemptCleanup) {
516 attemptCleanup();
517 }
wangqi9982f0d2017-10-11 17:46:07 -0700518 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800519 }
520
521 public void setManageConferenceActivity(
522 @Nullable ManageConferenceActivity manageConferenceActivity) {
523 mManageConferenceActivity = manageConferenceActivity;
524 }
525
526 public void onBringToForeground(boolean showDialpad) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700527 LogUtil.i("InCallPresenter.onBringToForeground", "Bringing UI to foreground.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800528 bringToForeground(showDialpad);
529 }
530
531 public void onCallAdded(final android.telecom.Call call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700532 Trace.beginSection("InCallPresenter.onCallAdded");
Eric Erfanianccca3152017-02-22 16:32:36 -0800533 LatencyReport latencyReport = new LatencyReport(call);
534 if (shouldAttemptBlocking(call)) {
535 maybeBlockCall(call, latencyReport);
536 } else {
537 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
538 mExternalCallList.onCallAdded(call);
539 } else {
540 latencyReport.onCallBlockingDone();
541 mCallList.onCallAdded(mContext, call, latencyReport);
542 }
543 }
544
545 // Since a call has been added we are no longer waiting for Telecom to send us a call.
546 setBoundAndWaitingForOutgoingCall(false, null);
547 call.registerCallback(mCallCallback);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700548 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800549 }
550
551 private boolean shouldAttemptBlocking(android.telecom.Call call) {
552 if (call.getState() != android.telecom.Call.STATE_RINGING) {
553 return false;
554 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700555 if (!UserManagerCompat.isUserUnlocked(mContext)) {
556 LogUtil.i(
557 "InCallPresenter.shouldAttemptBlocking",
558 "not attempting to block incoming call because user is locked");
559 return false;
560 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800561 if (TelecomCallUtil.isEmergencyCall(call)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700562 LogUtil.i(
563 "InCallPresenter.shouldAttemptBlocking",
564 "Not attempting to block incoming emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800565 return false;
566 }
567 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700568 LogUtil.i(
569 "InCallPresenter.shouldAttemptBlocking",
570 "Not attempting to block incoming call due to recent emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800571 return false;
572 }
573 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
574 return false;
575 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700576 if (FilteredNumberCompat.useNewFiltering(mContext)) {
577 LogUtil.i(
578 "InCallPresenter.shouldAttemptBlocking",
579 "not attempting to block incoming call because framework blocking is in use");
580 return false;
581 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800582 return true;
583 }
584
585 /**
586 * Checks whether a call should be blocked, and blocks it if so. Otherwise, it adds the call to
587 * the CallList so it can proceed as normal. There is a timeout, so if the function for checking
588 * whether a function is blocked does not return in a reasonable time, we proceed with adding the
589 * call anyways.
590 */
591 private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) {
592 final String countryIso = GeoUtil.getCurrentCountryIso(mContext);
593 final String number = TelecomCallUtil.getNumber(call);
594 final long timeAdded = System.currentTimeMillis();
595
596 // Though AtomicBoolean's can be scary, don't fear, as in this case it is only used on the
597 // main UI thread. It is needed so we can change its value within different scopes, since
598 // that cannot be done with a final boolean.
599 final AtomicBoolean hasTimedOut = new AtomicBoolean(false);
600
601 final Handler handler = new Handler();
602
603 // Proceed if the query is slow; the call may still be blocked after the query returns.
604 final Runnable runnable =
605 new Runnable() {
606 @Override
607 public void run() {
608 hasTimedOut.set(true);
609 latencyReport.onCallBlockingDone();
610 mCallList.onCallAdded(mContext, call, latencyReport);
611 }
612 };
613 handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS);
614
615 OnCheckBlockedListener onCheckBlockedListener =
616 new OnCheckBlockedListener() {
617 @Override
618 public void onCheckComplete(final Integer id) {
619 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700620 LogUtil.i("InCallPresenter.onCheckComplete", "torn down, not adding call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800621 return;
622 }
623 if (!hasTimedOut.get()) {
624 handler.removeCallbacks(runnable);
625 }
626 if (id == null) {
627 if (!hasTimedOut.get()) {
628 latencyReport.onCallBlockingDone();
629 mCallList.onCallAdded(mContext, call, latencyReport);
630 }
631 } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700632 LogUtil.d(
633 "InCallPresenter.onCheckComplete", "invalid number, skipping block checking");
Eric Erfanianccca3152017-02-22 16:32:36 -0800634 if (!hasTimedOut.get()) {
635 handler.removeCallbacks(runnable);
636
637 latencyReport.onCallBlockingDone();
638 mCallList.onCallAdded(mContext, call, latencyReport);
639 }
640 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700641 LogUtil.i(
642 "InCallPresenter.onCheckComplete", "Rejecting incoming call from blocked number");
Eric Erfanianccca3152017-02-22 16:32:36 -0800643 call.reject(false, null);
644 Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED);
645
646 /*
647 * If mContext is null, then the InCallPresenter was torn down before the
648 * block check had a chance to complete. The context is no longer valid, so
649 * don't attempt to remove the call log entry.
650 */
651 if (mContext == null) {
652 return;
653 }
654 // Register observer to update the call log.
655 // BlockedNumberContentObserver will unregister after successful log or timeout.
656 BlockedNumberContentObserver contentObserver =
657 new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded);
658 contentObserver.register();
659 }
660 }
661 };
662
663 mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso);
664 }
665
666 public void onCallRemoved(android.telecom.Call call) {
667 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
668 mExternalCallList.onCallRemoved(call);
669 } else {
670 mCallList.onCallRemoved(mContext, call);
671 call.unregisterCallback(mCallCallback);
672 }
673 }
674
675 public void onCanAddCallChanged(boolean canAddCall) {
676 for (CanAddCallListener listener : mCanAddCallListeners) {
677 listener.onCanAddCallChanged(canAddCall);
678 }
679 }
680
681 @Override
682 public void onWiFiToLteHandover(DialerCall call) {
683 if (mInCallActivity != null) {
684 mInCallActivity.onWiFiToLteHandover(call);
685 }
686 }
687
688 @Override
689 public void onHandoverToWifiFailed(DialerCall call) {
690 if (mInCallActivity != null) {
691 mInCallActivity.onHandoverToWifiFailed(call);
692 }
693 }
694
Eric Erfanianc857f902017-05-15 14:05:33 -0700695 @Override
696 public void onInternationalCallOnWifi(@NonNull DialerCall call) {
697 LogUtil.enterBlock("InCallPresenter.onInternationalCallOnWifi");
698 if (mInCallActivity != null) {
699 mInCallActivity.onInternationalCallOnWifi(call);
700 }
701 }
702
Eric Erfanianccca3152017-02-22 16:32:36 -0800703 /**
704 * Called when there is a change to the call list. Sets the In-Call state for the entire in-call
705 * app based on the information it gets from CallList. Dispatches the in-call state to all
706 * listeners. Can trigger the creation or destruction of the UI based on the states that is
707 * calculates.
708 */
709 @Override
710 public void onCallListChange(CallList callList) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700711 Trace.beginSection("InCallPresenter.onCallListChange");
Eric Erfanianccca3152017-02-22 16:32:36 -0800712 if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) {
713 mAwaitingCallListUpdate = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700714 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800715 return;
716 }
717 if (callList == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700718 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800719 return;
720 }
721
722 mAwaitingCallListUpdate = false;
723
724 InCallState newState = getPotentialStateFromCallList(callList);
725 InCallState oldState = mInCallState;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700726 LogUtil.d(
727 "InCallPresenter.onCallListChange",
728 "onCallListChange oldState= " + oldState + " newState=" + newState);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700729
730 // If the user placed a call and was asked to choose the account, but then pressed "Home", the
731 // incall activity for that call will still exist (even if it's not visible). In the case of
732 // an incoming call in that situation, just disconnect that "waiting for account" call and
733 // dismiss the dialog. The same activity will be reused to handle the new incoming call. See
Eric Erfanian938468d2017-10-24 14:05:52 -0700734 // a bug for more details.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700735 DialerCall waitingForAccountCall;
736 if (newState == InCallState.INCOMING
737 && (waitingForAccountCall = callList.getWaitingForAccountCall()) != null) {
738 waitingForAccountCall.disconnect();
Eric Erfanian2ca43182017-08-31 06:57:16 -0700739 // The InCallActivity might be destroyed or not started yet at this point.
740 if (isActivityStarted()) {
741 mInCallActivity.dismissPendingDialogs();
742 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700743 }
744
Eric Erfanianccca3152017-02-22 16:32:36 -0800745 newState = startOrFinishUi(newState);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700746 LogUtil.d(
747 "InCallPresenter.onCallListChange", "onCallListChange newState changed to " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800748
749 // Set the new state before announcing it to the world
Eric Erfanian2ca43182017-08-31 06:57:16 -0700750 LogUtil.i(
751 "InCallPresenter.onCallListChange",
752 "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800753 mInCallState = newState;
754
755 // notify listeners of new state
756 for (InCallStateListener listener : mListeners) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700757 LogUtil.d(
758 "InCallPresenter.onCallListChange",
759 "Notify " + listener + " of state " + mInCallState.toString());
Eric Erfanianccca3152017-02-22 16:32:36 -0800760 listener.onStateChange(oldState, mInCallState, callList);
761 }
762
763 if (isActivityStarted()) {
764 final boolean hasCall =
765 callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null;
766 mInCallActivity.dismissKeyguard(hasCall);
767 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700768 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800769 }
770
771 /** Called when there is a new incoming call. */
772 @Override
773 public void onIncomingCall(DialerCall call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700774 Trace.beginSection("InCallPresenter.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800775 InCallState newState = startOrFinishUi(InCallState.INCOMING);
776 InCallState oldState = mInCallState;
777
Eric Erfanian2ca43182017-08-31 06:57:16 -0700778 LogUtil.i(
779 "InCallPresenter.onIncomingCall", "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800780 mInCallState = newState;
781
wangqicf61ca02017-08-31 15:32:55 -0700782 Trace.beginSection("listener.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800783 for (IncomingCallListener listener : mIncomingCallListeners) {
784 listener.onIncomingCall(oldState, mInCallState, call);
785 }
wangqicf61ca02017-08-31 15:32:55 -0700786 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800787
wangqicf61ca02017-08-31 15:32:55 -0700788 Trace.beginSection("onPrimaryCallStateChanged");
Eric Erfanianccca3152017-02-22 16:32:36 -0800789 if (mInCallActivity != null) {
790 // Re-evaluate which fragment is being shown.
791 mInCallActivity.onPrimaryCallStateChanged();
792 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700793 Trace.endSection();
wangqicf61ca02017-08-31 15:32:55 -0700794 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800795 }
796
797 @Override
798 public void onUpgradeToVideo(DialerCall call) {
Eric Erfanian90508232017-03-24 09:31:16 -0700799 if (VideoUtils.hasReceivedVideoUpgradeRequest(call.getVideoTech().getSessionModificationState())
Eric Erfanianccca3152017-02-22 16:32:36 -0800800 && mInCallState == InCallPresenter.InCallState.INCOMING) {
801 LogUtil.i(
802 "InCallPresenter.onUpgradeToVideo",
803 "rejecting upgrade request due to existing incoming call");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700804 call.getVideoTech().declineVideoRequest();
Eric Erfanianccca3152017-02-22 16:32:36 -0800805 }
806
807 if (mInCallActivity != null) {
808 // Re-evaluate which fragment is being shown.
809 mInCallActivity.onPrimaryCallStateChanged();
810 }
811 }
812
813 @Override
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700814 public void onSessionModificationStateChange(DialerCall call) {
815 int newState = call.getVideoTech().getSessionModificationState();
Eric Erfanianccca3152017-02-22 16:32:36 -0800816 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
817 if (mProximitySensor == null) {
818 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
819 return;
820 }
821 mProximitySensor.setIsAttemptingVideoCall(
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700822 call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest());
Eric Erfanianccca3152017-02-22 16:32:36 -0800823 if (mInCallActivity != null) {
824 // Re-evaluate which fragment is being shown.
825 mInCallActivity.onPrimaryCallStateChanged();
826 }
827 }
828
829 /**
830 * Called when a call becomes disconnected. Called everytime an existing call changes from being
831 * connected (incoming/outgoing/active) to disconnected.
832 */
833 @Override
834 public void onDisconnect(DialerCall call) {
835 maybeShowErrorDialogOnDisconnect(call);
836
837 // We need to do the run the same code as onCallListChange.
838 onCallListChange(mCallList);
839
840 if (isActivityStarted()) {
841 mInCallActivity.dismissKeyguard(false);
842 }
843
844 if (call.isEmergencyCall()) {
845 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
846 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800847
Eric Erfanianfc37b022017-03-21 10:11:17 -0700848 if (!mCallList.hasLiveCall()
849 && !call.getLogState().isIncoming
Eric Erfanian10b34a52017-05-04 08:23:17 -0700850 && !isSecretCode(call.getNumber())
wangqi9982f0d2017-10-11 17:46:07 -0700851 && !call.isVoiceMailNumber()) {
Eric Erfanian10b34a52017-05-04 08:23:17 -0700852 PostCall.onCallDisconnected(mContext, call.getNumber(), call.getConnectTimeMillis());
Eric Erfanianccca3152017-02-22 16:32:36 -0800853 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800854 }
855
Eric Erfanian10b34a52017-05-04 08:23:17 -0700856 private boolean isSecretCode(@Nullable String number) {
857 return number != null
858 && (number.length() <= 8 || number.startsWith("*#*#") || number.endsWith("#*#*"));
859 }
860
Eric Erfanianccca3152017-02-22 16:32:36 -0800861 /** Given the call list, return the state in which the in-call screen should be. */
862 public InCallState getPotentialStateFromCallList(CallList callList) {
863
864 InCallState newState = InCallState.NO_CALLS;
865
866 if (callList == null) {
867 return newState;
868 }
869 if (callList.getIncomingCall() != null) {
870 newState = InCallState.INCOMING;
871 } else if (callList.getWaitingForAccountCall() != null) {
872 newState = InCallState.WAITING_FOR_ACCOUNT;
873 } else if (callList.getPendingOutgoingCall() != null) {
874 newState = InCallState.PENDING_OUTGOING;
875 } else if (callList.getOutgoingCall() != null) {
876 newState = InCallState.OUTGOING;
877 } else if (callList.getActiveCall() != null
878 || callList.getBackgroundCall() != null
879 || callList.getDisconnectedCall() != null
880 || callList.getDisconnectingCall() != null) {
881 newState = InCallState.INCALL;
882 }
883
884 if (newState == InCallState.NO_CALLS) {
885 if (mBoundAndWaitingForOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700886 return InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800887 }
888 }
889
890 return newState;
891 }
892
893 public boolean isBoundAndWaitingForOutgoingCall() {
894 return mBoundAndWaitingForOutgoingCall;
895 }
896
897 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700898 LogUtil.i(
899 "InCallPresenter.setBoundAndWaitingForOutgoingCall",
900 "setBoundAndWaitingForOutgoingCall: " + isBound);
Eric Erfanianccca3152017-02-22 16:32:36 -0800901 mBoundAndWaitingForOutgoingCall = isBound;
902 mThemeColorManager.setPendingPhoneAccountHandle(handle);
903 if (isBound && mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700904 mInCallState = InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800905 }
906 }
907
908 public void onShrinkAnimationComplete() {
909 if (mAwaitingCallListUpdate) {
910 onCallListChange(mCallList);
911 }
912 }
913
914 public void addIncomingCallListener(IncomingCallListener listener) {
915 Objects.requireNonNull(listener);
916 mIncomingCallListeners.add(listener);
917 }
918
919 public void removeIncomingCallListener(IncomingCallListener listener) {
920 if (listener != null) {
921 mIncomingCallListeners.remove(listener);
922 }
923 }
924
925 public void addListener(InCallStateListener listener) {
926 Objects.requireNonNull(listener);
927 mListeners.add(listener);
928 }
929
930 public void removeListener(InCallStateListener listener) {
931 if (listener != null) {
932 mListeners.remove(listener);
933 }
934 }
935
936 public void addDetailsListener(InCallDetailsListener listener) {
937 Objects.requireNonNull(listener);
938 mDetailsListeners.add(listener);
939 }
940
941 public void removeDetailsListener(InCallDetailsListener listener) {
942 if (listener != null) {
943 mDetailsListeners.remove(listener);
944 }
945 }
946
947 public void addCanAddCallListener(CanAddCallListener listener) {
948 Objects.requireNonNull(listener);
949 mCanAddCallListeners.add(listener);
950 }
951
952 public void removeCanAddCallListener(CanAddCallListener listener) {
953 if (listener != null) {
954 mCanAddCallListeners.remove(listener);
955 }
956 }
957
958 public void addOrientationListener(InCallOrientationListener listener) {
959 Objects.requireNonNull(listener);
960 mOrientationListeners.add(listener);
961 }
962
963 public void removeOrientationListener(InCallOrientationListener listener) {
964 if (listener != null) {
965 mOrientationListeners.remove(listener);
966 }
967 }
968
969 public void addInCallEventListener(InCallEventListener listener) {
970 Objects.requireNonNull(listener);
971 mInCallEventListeners.add(listener);
972 }
973
974 public void removeInCallEventListener(InCallEventListener listener) {
975 if (listener != null) {
976 mInCallEventListeners.remove(listener);
977 }
978 }
979
980 public ProximitySensor getProximitySensor() {
981 return mProximitySensor;
982 }
983
984 public PseudoScreenState getPseudoScreenState() {
985 return mPseudoScreenState;
986 }
987
988 /** Returns true if the incall app is the foreground application. */
989 public boolean isShowingInCallUi() {
990 if (!isActivityStarted()) {
991 return false;
992 }
993 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
994 return true;
995 }
996 return mInCallActivity.isVisible();
997 }
998
999 /**
1000 * Returns true if the activity has been created and is running. Returns true as long as activity
1001 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
1002 * (not in foreground).
1003 */
1004 public boolean isActivityStarted() {
1005 return (mInCallActivity != null
1006 && !mInCallActivity.isDestroyed()
1007 && !mInCallActivity.isFinishing());
1008 }
1009
1010 /**
1011 * Determines if the In-Call app is currently changing configuration.
1012 *
1013 * @return {@code true} if the In-Call app is changing configuration.
1014 */
1015 public boolean isChangingConfigurations() {
1016 return mIsChangingConfigurations;
1017 }
1018
1019 /**
1020 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
1021 * screen orientation).
1022 */
1023 /*package*/
1024 void updateIsChangingConfigurations() {
1025 mIsChangingConfigurations = false;
1026 if (mInCallActivity != null) {
1027 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
1028 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001029 LogUtil.v(
1030 "InCallPresenter.updateIsChangingConfigurations",
1031 "updateIsChangingConfigurations = " + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001032 }
1033
1034 /** Called when the activity goes in/out of the foreground. */
1035 public void onUiShowing(boolean showing) {
1036 // We need to update the notification bar when we leave the UI because that
1037 // could trigger it to show again.
1038 if (mStatusBarNotifier != null) {
wangqic8cf79e2017-10-17 09:21:00 -07001039 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001040 }
1041
1042 if (mProximitySensor != null) {
1043 mProximitySensor.onInCallShowing(showing);
1044 }
1045
1046 Intent broadcastIntent = Bindings.get(mContext).getUiReadyBroadcastIntent(mContext);
1047 if (broadcastIntent != null) {
1048 broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
1049
1050 if (showing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001051 LogUtil.d("InCallPresenter.onUiShowing", "Sending sticky broadcast: ", broadcastIntent);
Eric Erfanianccca3152017-02-22 16:32:36 -08001052 mContext.sendStickyBroadcast(broadcastIntent);
1053 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001054 LogUtil.d("InCallPresenter.onUiShowing", "Removing sticky broadcast: ", broadcastIntent);
Eric Erfanianccca3152017-02-22 16:32:36 -08001055 mContext.removeStickyBroadcast(broadcastIntent);
1056 }
1057 }
1058
1059 if (showing) {
1060 mIsActivityPreviouslyStarted = true;
1061 } else {
1062 updateIsChangingConfigurations();
1063 }
1064
1065 for (InCallUiListener listener : mInCallUiListeners) {
1066 listener.onUiShowing(showing);
1067 }
1068
1069 if (mInCallActivity != null) {
1070 // Re-evaluate which fragment is being shown.
1071 mInCallActivity.onPrimaryCallStateChanged();
1072 }
1073 }
1074
Eric Erfanian2ca43182017-08-31 06:57:16 -07001075 public void refreshUi() {
1076 if (mInCallActivity != null) {
1077 // Re-evaluate which fragment is being shown.
1078 mInCallActivity.onPrimaryCallStateChanged();
1079 }
1080 }
1081
Eric Erfanianccca3152017-02-22 16:32:36 -08001082 public void addInCallUiListener(InCallUiListener listener) {
1083 mInCallUiListeners.add(listener);
1084 }
1085
1086 public boolean removeInCallUiListener(InCallUiListener listener) {
1087 return mInCallUiListeners.remove(listener);
1088 }
1089
1090 /*package*/
1091 void onActivityStarted() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001092 LogUtil.d("InCallPresenter.onActivityStarted", "onActivityStarted");
Eric Erfanianccca3152017-02-22 16:32:36 -08001093 notifyVideoPauseController(true);
Eric Erfanian2ca43182017-08-31 06:57:16 -07001094 applyScreenTimeout();
Eric Erfanianccca3152017-02-22 16:32:36 -08001095 }
1096
1097 /*package*/
1098 void onActivityStopped() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001099 LogUtil.d("InCallPresenter.onActivityStopped", "onActivityStopped");
Eric Erfanianccca3152017-02-22 16:32:36 -08001100 notifyVideoPauseController(false);
1101 }
1102
1103 private void notifyVideoPauseController(boolean showing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001104 LogUtil.d(
1105 "InCallPresenter.notifyVideoPauseController",
1106 "mIsChangingConfigurations=" + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001107 if (!mIsChangingConfigurations) {
1108 VideoPauseController.getInstance().onUiShowing(showing);
1109 }
1110 }
1111
1112 /** Brings the app into the foreground if possible. */
1113 public void bringToForeground(boolean showDialpad) {
1114 // Before we bring the incall UI to the foreground, we check to see if:
1115 // 1. It is not currently in the foreground
1116 // 2. We are in a state where we want to show the incall ui (i.e. there are calls to
1117 // be displayed)
1118 // If the activity hadn't actually been started previously, yet there are still calls
1119 // present (e.g. a call was accepted by a bluetooth or wired headset), we want to
1120 // bring it up the UI regardless.
1121 if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001122 showInCall(showDialpad, false /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001123 }
1124 }
1125
1126 public void onPostDialCharWait(String callId, String chars) {
1127 if (isActivityStarted()) {
1128 mInCallActivity.showPostCharWaitDialog(callId, chars);
1129 }
1130 }
1131
1132 /**
1133 * Handles the green CALL key while in-call.
1134 *
1135 * @return true if we consumed the event.
1136 */
1137 public boolean handleCallKey() {
1138 LogUtil.v("InCallPresenter.handleCallKey", null);
1139
1140 // The green CALL button means either "Answer", "Unhold", or
1141 // "Swap calls", or can be a no-op, depending on the current state
1142 // of the Phone.
1143
1144 /** INCOMING CALL */
1145 final CallList calls = mCallList;
1146 final DialerCall incomingCall = calls.getIncomingCall();
1147 LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall);
1148
1149 // (1) Attempt to answer a call
1150 if (incomingCall != null) {
1151 incomingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
1152 return true;
1153 }
1154
1155 /** STATE_ACTIVE CALL */
1156 final DialerCall activeCall = calls.getActiveCall();
1157 if (activeCall != null) {
1158 // TODO: This logic is repeated from CallButtonPresenter.java. We should
1159 // consolidate this logic.
1160 final boolean canMerge =
1161 activeCall.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
1162 final boolean canSwap =
1163 activeCall.can(android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
1164
Eric Erfanian2ca43182017-08-31 06:57:16 -07001165 LogUtil.v(
1166 "InCallPresenter.handleCallKey",
1167 "activeCall: " + activeCall + ", canMerge: " + canMerge + ", canSwap: " + canSwap);
Eric Erfanianccca3152017-02-22 16:32:36 -08001168
1169 // (2) Attempt actions on conference calls
1170 if (canMerge) {
1171 TelecomAdapter.getInstance().merge(activeCall.getId());
1172 return true;
1173 } else if (canSwap) {
1174 TelecomAdapter.getInstance().swap(activeCall.getId());
1175 return true;
1176 }
1177 }
1178
1179 /** BACKGROUND CALL */
1180 final DialerCall heldCall = calls.getBackgroundCall();
1181 if (heldCall != null) {
1182 // We have a hold call so presumeable it will always support HOLD...but
1183 // there is no harm in double checking.
1184 final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
1185
Eric Erfanian2ca43182017-08-31 06:57:16 -07001186 LogUtil.v("InCallPresenter.handleCallKey", "heldCall: " + heldCall + ", canHold: " + canHold);
Eric Erfanianccca3152017-02-22 16:32:36 -08001187
1188 // (4) unhold call
1189 if (heldCall.getState() == DialerCall.State.ONHOLD && canHold) {
1190 heldCall.unhold();
1191 return true;
1192 }
1193 }
1194
1195 // Always consume hard keys
1196 return true;
1197 }
1198
Eric Erfanianccca3152017-02-22 16:32:36 -08001199 /** Clears the previous fullscreen state. */
1200 public void clearFullscreen() {
1201 mIsFullScreen = false;
1202 }
1203
1204 /**
1205 * Changes the fullscreen mode of the in-call UI.
1206 *
1207 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1208 * otherwise.
1209 */
1210 public void setFullScreen(boolean isFullScreen) {
1211 setFullScreen(isFullScreen, false /* force */);
1212 }
1213
1214 /**
1215 * Changes the fullscreen mode of the in-call UI.
1216 *
1217 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1218 * otherwise.
1219 * @param force {@code true} if fullscreen mode should be set regardless of its current state.
1220 */
1221 public void setFullScreen(boolean isFullScreen, boolean force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001222 LogUtil.i("InCallPresenter.setFullScreen", "setFullScreen = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001223
1224 // As a safeguard, ensure we cannot enter fullscreen if the dialpad is shown.
1225 if (isDialpadVisible()) {
1226 isFullScreen = false;
Eric Erfanian2ca43182017-08-31 06:57:16 -07001227 LogUtil.v(
1228 "InCallPresenter.setFullScreen",
1229 "setFullScreen overridden as dialpad is shown = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001230 }
1231
1232 if (mIsFullScreen == isFullScreen && !force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001233 LogUtil.v("InCallPresenter.setFullScreen", "setFullScreen ignored as already in that state.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001234 return;
1235 }
1236 mIsFullScreen = isFullScreen;
1237 notifyFullscreenModeChange(mIsFullScreen);
1238 }
1239
1240 /**
1241 * @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
1242 * otherwise.
1243 */
1244 public boolean isFullscreen() {
1245 return mIsFullScreen;
1246 }
1247
1248 /**
1249 * Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
1250 *
1251 * @param isFullscreenMode {@code True} if entering full screen mode.
1252 */
1253 public void notifyFullscreenModeChange(boolean isFullscreenMode) {
1254 for (InCallEventListener listener : mInCallEventListeners) {
1255 listener.onFullscreenModeChanged(isFullscreenMode);
1256 }
1257 }
1258
1259 /**
1260 * For some disconnected causes, we show a dialog. This calls into the activity to show the dialog
1261 * if appropriate for the call.
1262 */
1263 private void maybeShowErrorDialogOnDisconnect(DialerCall call) {
1264 // For newly disconnected calls, we may want to show a dialog on specific error conditions
1265 if (isActivityStarted() && call.getState() == DialerCall.State.DISCONNECTED) {
1266 if (call.getAccountHandle() == null && !call.isConferenceCall()) {
1267 setDisconnectCauseForMissingAccounts(call);
1268 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001269 mInCallActivity.maybeShowErrorDialogOnDisconnect(
1270 new DisconnectMessage(mInCallActivity, call));
Eric Erfanianccca3152017-02-22 16:32:36 -08001271 }
1272 }
1273
1274 /**
1275 * When the state of in-call changes, this is the first method to get called. It determines if the
1276 * UI needs to be started or finished depending on the new state and does it.
1277 */
1278 private InCallState startOrFinishUi(InCallState newState) {
wangqicf61ca02017-08-31 15:32:55 -07001279 Trace.beginSection("InCallPresenter.startOrFinishUi");
Eric Erfanian2ca43182017-08-31 06:57:16 -07001280 LogUtil.d(
1281 "InCallPresenter.startOrFinishUi", "startOrFinishUi: " + mInCallState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -08001282
1283 // TODO: Consider a proper state machine implementation
1284
1285 // If the state isn't changing we have already done any starting/stopping of activities in
1286 // a previous pass...so lets cut out early
1287 if (newState == mInCallState) {
wangqicf61ca02017-08-31 15:32:55 -07001288 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001289 return newState;
1290 }
1291
1292 // A new Incoming call means that the user needs to be notified of the the call (since
1293 // it wasn't them who initiated it). We do this through full screen notifications and
1294 // happens indirectly through {@link StatusBarNotifier}.
1295 //
1296 // The process for incoming calls is as follows:
1297 //
1298 // 1) CallList - Announces existence of new INCOMING call
1299 // 2) InCallPresenter - Gets announcement and calculates that the new InCallState
1300 // - should be set to INCOMING.
1301 // 3) InCallPresenter - This method is called to see if we need to start or finish
1302 // the app given the new state.
1303 // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
1304 // StatusBarNotifier explicitly to issue a FullScreen Notification
1305 // that will either start the InCallActivity or show the user a
1306 // top-level notification dialog if the user is in an immersive app.
1307 // That notification can also start the InCallActivity.
1308 // 5) InCallActivity - Main activity starts up and at the end of its onCreate will
1309 // call InCallPresenter::setActivity() to let the presenter
1310 // know that start-up is complete.
1311 //
1312 // [ AND NOW YOU'RE IN THE CALL. voila! ]
1313 //
1314 // Our app is started using a fullScreen notification. We need to do this whenever
1315 // we get an incoming call. Depending on the current context of the device, either a
1316 // incoming call HUN or the actual InCallActivity will be shown.
1317 final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
1318
1319 // A dialog to show on top of the InCallUI to select a PhoneAccount
1320 final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
1321
1322 // A new outgoing call indicates that the user just now dialed a number and when that
1323 // happens we need to display the screen immediately or show an account picker dialog if
1324 // no default is set. However, if the main InCallUI is already visible, we do not want to
1325 // re-initiate the start-up animation, so we do not need to do anything here.
1326 //
1327 // It is also possible to go into an intermediate state where the call has been initiated
1328 // but Telecom has not yet returned with the details of the call (handle, gateway, etc.).
1329 // This pending outgoing state can also launch the call screen.
1330 //
1331 // This is different from the incoming call sequence because we do not need to shock the
1332 // user with a top-level notification. Just show the call UI normally.
1333 boolean callCardFragmentVisible =
1334 mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible();
1335 final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible;
1336 boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
1337
1338 // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
1339 // outgoing call process, so the UI should be brought up to show an error dialog.
1340 showCallUi |=
1341 (InCallState.PENDING_OUTGOING == mInCallState
1342 && InCallState.INCALL == newState
1343 && !isShowingInCallUi());
1344
1345 // Another exception - InCallActivity is in charge of disconnecting a call with no
1346 // valid accounts set. Bring the UI up if this is true for the current pending outgoing
1347 // call so that:
1348 // 1) The call can be disconnected correctly
1349 // 2) The UI comes up and correctly displays the error dialog.
1350 // TODO: Remove these special case conditions by making InCallPresenter a true state
1351 // machine. Telecom should also be the component responsible for disconnecting a call
1352 // with no valid accounts.
1353 showCallUi |=
1354 InCallState.PENDING_OUTGOING == newState
1355 && mainUiNotVisible
1356 && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
1357
1358 // The only time that we have an instance of mInCallActivity and it isn't started is
1359 // when it is being destroyed. In that case, lets avoid bringing up another instance of
1360 // the activity. When it is finally destroyed, we double check if we should bring it back
1361 // up so we aren't going to lose anything by avoiding a second startup here.
1362 boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
1363 if (activityIsFinishing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001364 LogUtil.i(
1365 "InCallPresenter.startOrFinishUi",
1366 "Undo the state change: " + newState + " -> " + mInCallState);
wangqicf61ca02017-08-31 15:32:55 -07001367 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001368 return mInCallState;
1369 }
1370
1371 // We're about the bring up the in-call UI for outgoing and incoming call. If we still have
1372 // dialogs up, we need to clear them out before showing in-call screen. This is necessary
1373 // to fix the bug that dialog will show up when data reaches limit even after makeing new
1374 // outgoing call after user ignore it by pressing home button.
1375 if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING)
1376 && !showCallUi
1377 && isActivityStarted()) {
1378 mInCallActivity.dismissPendingDialogs();
1379 }
1380
1381 if (showCallUi || showAccountPicker) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001382 LogUtil.i("InCallPresenter.startOrFinishUi", "Start in call UI");
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001383 showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001384 } else if (startIncomingCallSequence) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001385 LogUtil.i("InCallPresenter.startOrFinishUi", "Start Full Screen in call UI");
Eric Erfanianccca3152017-02-22 16:32:36 -08001386
wangqic8cf79e2017-10-17 09:21:00 -07001387 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001388 } else if (newState == InCallState.NO_CALLS) {
1389 // The new state is the no calls state. Tear everything down.
1390 attemptFinishActivity();
1391 attemptCleanup();
1392 }
1393
wangqicf61ca02017-08-31 15:32:55 -07001394 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001395 return newState;
1396 }
1397
1398 /**
1399 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1400 * or PhoneAccounts to select from.
1401 */
1402 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1403
1404 Bundle extras = call.getIntentExtras();
1405 // Initialize the extras bundle to avoid NPE
1406 if (extras == null) {
1407 extras = new Bundle();
1408 }
1409
1410 final List<PhoneAccountHandle> phoneAccountHandles =
1411 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1412
1413 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1414 String scheme = call.getHandle().getScheme();
1415 final String errorMsg =
1416 PhoneAccount.SCHEME_TEL.equals(scheme)
1417 ? mContext.getString(R.string.callFailed_simError)
1418 : mContext.getString(R.string.incall_error_supp_service_unknown);
1419 DisconnectCause disconnectCause =
1420 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1421 call.setDisconnectCause(disconnectCause);
1422 }
1423 }
1424
Eric Erfanianccca3152017-02-22 16:32:36 -08001425 /**
1426 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1427 * Calling classes should use this as an indication whether to interact with the
1428 * InCallPresenter or not.
1429 */
1430 public boolean isReadyForTearDown() {
1431 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1432 }
1433
1434 /**
1435 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1436 */
1437 private void attemptCleanup() {
1438 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001439 LogUtil.i("InCallPresenter.attemptCleanup", "Cleaning up");
Eric Erfanianccca3152017-02-22 16:32:36 -08001440
1441 cleanupSurfaces();
1442
1443 mIsActivityPreviouslyStarted = false;
1444 mIsChangingConfigurations = false;
1445
1446 // blow away stale contact info so that we get fresh data on
1447 // the next set of calls
1448 if (mContactInfoCache != null) {
1449 mContactInfoCache.clearCache();
1450 }
1451 mContactInfoCache = null;
1452
1453 if (mProximitySensor != null) {
1454 removeListener(mProximitySensor);
1455 mProximitySensor.tearDown();
1456 }
1457 mProximitySensor = null;
1458
1459 if (mStatusBarNotifier != null) {
1460 removeListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -07001461 EnrichedCallComponent.get(mContext)
1462 .getEnrichedCallManager()
1463 .unregisterStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -08001464 }
Eric Erfaniand8046e52017-04-06 09:41:50 -07001465
Eric Erfanianccca3152017-02-22 16:32:36 -08001466 if (mExternalCallNotifier != null && mExternalCallList != null) {
1467 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1468 }
1469 mStatusBarNotifier = null;
1470
1471 if (mCallList != null) {
1472 mCallList.removeListener(this);
1473 mCallList.removeListener(mSpamCallListListener);
1474 }
1475 mCallList = null;
1476
1477 mContext = null;
1478 mInCallActivity = null;
1479 mManageConferenceActivity = null;
1480
1481 mListeners.clear();
1482 mIncomingCallListeners.clear();
1483 mDetailsListeners.clear();
1484 mCanAddCallListeners.clear();
1485 mOrientationListeners.clear();
1486 mInCallEventListeners.clear();
1487 mInCallUiListeners.clear();
twyen8efb4952017-10-06 16:35:54 -07001488 if (!mInCallUiLocks.isEmpty()) {
1489 LogUtil.e("InCallPresenter.attemptCleanup", "held in call locks: " + mInCallUiLocks);
1490 mInCallUiLocks.clear();
1491 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001492 LogUtil.d("InCallPresenter.attemptCleanup", "finished");
Eric Erfanianccca3152017-02-22 16:32:36 -08001493 }
1494 }
1495
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001496 public void showInCall(boolean showDialpad, boolean newOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001497 LogUtil.i("InCallPresenter.showInCall", "Showing InCallActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -08001498 mContext.startActivity(
1499 InCallActivity.getIntent(
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001500 mContext, showDialpad, newOutgoingCall, false /* forFullScreen */));
Eric Erfanianccca3152017-02-22 16:32:36 -08001501 }
1502
1503 public void onServiceBind() {
1504 mServiceBound = true;
1505 }
1506
1507 public void onServiceUnbind() {
1508 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1509 mServiceBound = false;
1510 }
1511
1512 public boolean isServiceBound() {
1513 return mServiceBound;
1514 }
1515
1516 public void maybeStartRevealAnimation(Intent intent) {
1517 if (intent == null || mInCallActivity != null) {
1518 return;
1519 }
1520 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1521 if (extras == null) {
1522 // Incoming call, just show the in-call UI directly.
1523 return;
1524 }
1525
1526 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1527 // Account selection dialog will show up so don't show the animation.
1528 return;
1529 }
1530
1531 final PhoneAccountHandle accountHandle =
1532 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1533 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
Eric Erfanianccca3152017-02-22 16:32:36 -08001534
1535 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1536
1537 final Intent activityIntent =
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001538 InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001539 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1540 mContext.startActivity(activityIntent);
1541 }
1542
1543 /**
1544 * Retrieves the current in-call camera manager instance, creating if necessary.
1545 *
1546 * @return The {@link InCallCameraManager}.
1547 */
1548 public InCallCameraManager getInCallCameraManager() {
1549 synchronized (this) {
1550 if (mInCallCameraManager == null) {
1551 mInCallCameraManager = new InCallCameraManager(mContext);
1552 }
1553
1554 return mInCallCameraManager;
1555 }
1556 }
1557
1558 /**
1559 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1560 *
1561 * @param orientation The screen orientation of the device (one of: {@link
1562 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1563 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1564 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1565 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1566 */
1567 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001568 LogUtil.d(
1569 "InCallPresenter.onDeviceOrientationChange",
1570 "onDeviceOrientationChange: orientation= " + orientation);
Eric Erfanianccca3152017-02-22 16:32:36 -08001571
1572 if (mCallList != null) {
1573 mCallList.notifyCallsOfDeviceRotation(orientation);
1574 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001575 LogUtil.w("InCallPresenter.onDeviceOrientationChange", "CallList is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001576 }
1577
1578 // Notify listeners of device orientation changed.
1579 for (InCallOrientationListener listener : mOrientationListeners) {
1580 listener.onDeviceOrientationChanged(orientation);
1581 }
1582 }
1583
1584 /**
1585 * Configures the in-call UI activity so it can change orientations or not. Enables the
1586 * orientation event listener if allowOrientationChange is true, disables it if false.
1587 *
1588 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1589 * landscape. {@code false} if the in-call UI should be locked in portrait.
1590 */
1591 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1592 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001593 LogUtil.e(
1594 "InCallPresenter.setInCallAllowsOrientationChange",
1595 "InCallActivity is null. Can't set requested orientation.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001596 return;
1597 }
1598 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1599 }
1600
1601 public void enableScreenTimeout(boolean enable) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001602 LogUtil.v("InCallPresenter.enableScreenTimeout", "enableScreenTimeout: value=" + enable);
1603 mScreenTimeoutEnabled = enable;
1604 applyScreenTimeout();
1605 }
1606
1607 private void applyScreenTimeout() {
Eric Erfanianccca3152017-02-22 16:32:36 -08001608 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001609 LogUtil.e("InCallPresenter.applyScreenTimeout", "InCallActivity is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001610 return;
1611 }
1612
1613 final Window window = mInCallActivity.getWindow();
Eric Erfanian2ca43182017-08-31 06:57:16 -07001614 if (mScreenTimeoutEnabled) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001615 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1616 } else {
1617 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1618 }
1619 }
1620
1621 /**
1622 * Hides or shows the conference manager fragment.
1623 *
1624 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1625 * be hidden.
1626 */
1627 public void showConferenceCallManager(boolean show) {
1628 if (mInCallActivity != null) {
1629 mInCallActivity.showConferenceFragment(show);
1630 }
1631 if (!show && mManageConferenceActivity != null) {
1632 mManageConferenceActivity.finish();
1633 }
1634 }
1635
1636 /**
1637 * Determines if the dialpad is visible.
1638 *
1639 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1640 */
1641 public boolean isDialpadVisible() {
1642 if (mInCallActivity == null) {
1643 return false;
1644 }
1645 return mInCallActivity.isDialpadVisible();
1646 }
1647
1648 public ThemeColorManager getThemeColorManager() {
1649 return mThemeColorManager;
1650 }
1651
1652 /** Called when the foreground call changes. */
1653 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1654 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1655 if (mInCallActivity != null) {
1656 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1657 }
1658 }
1659
1660 public InCallActivity getActivity() {
1661 return mInCallActivity;
1662 }
1663
1664 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1665 public void setActivity(InCallActivity inCallActivity) {
1666 if (inCallActivity == null) {
1667 throw new IllegalArgumentException("registerActivity cannot be called with null");
1668 }
1669 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001670 LogUtil.w(
1671 "InCallPresenter.setActivity", "Setting a second activity before destroying the first.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001672 }
1673 updateActivity(inCallActivity);
1674 }
1675
1676 ExternalCallNotifier getExternalCallNotifier() {
1677 return mExternalCallNotifier;
1678 }
1679
1680 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1681 if (mLocalVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001682 boolean isPixel2017 = false;
1683 if (mContext != null) {
1684 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1685 }
1686 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001687 }
1688 return mLocalVideoSurfaceTexture;
1689 }
1690
1691 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1692 if (mRemoteVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001693 boolean isPixel2017 = false;
1694 if (mContext != null) {
1695 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1696 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001697 mRemoteVideoSurfaceTexture =
roldenburg12b50c62017-09-01 14:41:19 -07001698 VideoSurfaceBindings.createRemoteVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001699 }
1700 return mRemoteVideoSurfaceTexture;
1701 }
1702
1703 void cleanupSurfaces() {
1704 if (mRemoteVideoSurfaceTexture != null) {
1705 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1706 mRemoteVideoSurfaceTexture = null;
1707 }
1708 if (mLocalVideoSurfaceTexture != null) {
1709 mLocalVideoSurfaceTexture.setDoneWithSurface();
1710 mLocalVideoSurfaceTexture = null;
1711 }
1712 }
1713
1714 /** All the main states of InCallActivity. */
1715 public enum InCallState {
1716 // InCall Screen is off and there are no calls
1717 NO_CALLS,
1718
1719 // Incoming-call screen is up
1720 INCOMING,
1721
1722 // In-call experience is showing
1723 INCALL,
1724
1725 // Waiting for user input before placing outgoing call
1726 WAITING_FOR_ACCOUNT,
1727
1728 // UI is starting up but no call has been initiated yet.
1729 // The UI is waiting for Telecom to respond.
1730 PENDING_OUTGOING,
1731
1732 // User is dialing out
1733 OUTGOING;
1734
1735 public boolean isIncoming() {
1736 return (this == INCOMING);
1737 }
1738
1739 public boolean isConnectingOrConnected() {
1740 return (this == INCOMING || this == OUTGOING || this == INCALL);
1741 }
1742 }
1743
1744 /** Interface implemented by classes that need to know about the InCall State. */
1745 public interface InCallStateListener {
1746
1747 // TODO: Enhance state to contain the call objects instead of passing CallList
1748 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1749 }
1750
1751 public interface IncomingCallListener {
1752
1753 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1754 }
1755
1756 public interface CanAddCallListener {
1757
1758 void onCanAddCallChanged(boolean canAddCall);
1759 }
1760
1761 public interface InCallDetailsListener {
1762
1763 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1764 }
1765
1766 public interface InCallOrientationListener {
1767
1768 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1769 }
1770
1771 /**
1772 * Interface implemented by classes that need to know about events which occur within the In-Call
1773 * UI. Used as a means of communicating between fragments that make up the UI.
1774 */
1775 public interface InCallEventListener {
1776
1777 void onFullscreenModeChanged(boolean isFullscreenMode);
1778 }
1779
1780 public interface InCallUiListener {
1781
1782 void onUiShowing(boolean showing);
1783 }
twyen8efb4952017-10-06 16:35:54 -07001784
1785 private class InCallUiLockImpl implements InCallUiLock {
1786 private final String tag;
1787
1788 private InCallUiLockImpl(String tag) {
1789 this.tag = tag;
1790 }
1791
1792 @MainThread
1793 @Override
1794 public void release() {
1795 Assert.isMainThread();
1796 releaseInCallUiLock(InCallUiLockImpl.this);
1797 }
1798
1799 @Override
1800 public String toString() {
1801 return "InCallUiLock[" + tag + "]";
1802 }
1803 }
1804
1805 @MainThread
1806 public InCallUiLock acquireInCallUiLock(String tag) {
1807 Assert.isMainThread();
1808 InCallUiLock lock = new InCallUiLockImpl(tag);
1809 mInCallUiLocks.add(lock);
1810 return lock;
1811 }
1812
1813 @MainThread
1814 private void releaseInCallUiLock(InCallUiLock lock) {
1815 Assert.isMainThread();
1816 LogUtil.i("InCallPresenter.releaseInCallUiLock", "releasing %s", lock);
1817 mInCallUiLocks.remove(lock);
1818 if (mInCallUiLocks.isEmpty()) {
1819 LogUtil.i("InCallPresenter.releaseInCallUiLock", "all locks released");
1820 if (mInCallState == InCallState.NO_CALLS) {
1821 LogUtil.i("InCallPresenter.releaseInCallUiLock", "no more calls, finishing UI");
1822 attemptFinishActivity();
1823 attemptCleanup();
1824 }
1825 }
1826 }
1827
1828 @MainThread
1829 public boolean isInCallUiLocked() {
1830 Assert.isMainThread();
1831 if (mInCallUiLocks.isEmpty()) {
1832 return false;
1833 }
1834 for (InCallUiLock lock : mInCallUiLocks) {
1835 LogUtil.i("InCallPresenter.isInCallUiLocked", "still locked by %s", lock);
1836 }
1837 return true;
1838 }
1839
1840 private final Set<InCallUiLock> mInCallUiLocks = new ArraySet<>();
Eric Erfanianccca3152017-02-22 16:32:36 -08001841}