blob: 6c1c13027482eb61deae7cd77946d76c32a5c4c4 [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;
yueg77cb8e52017-10-27 16:42:51 -070031import android.telecom.CallAudioState;
Eric Erfanianccca3152017-02-22 16:32:36 -080032import android.telecom.DisconnectCause;
33import android.telecom.PhoneAccount;
34import android.telecom.PhoneAccountHandle;
35import android.telecom.TelecomManager;
36import android.telecom.VideoProfile;
37import android.telephony.PhoneStateListener;
38import android.telephony.TelephonyManager;
twyen8efb4952017-10-06 16:35:54 -070039import android.util.ArraySet;
Eric Erfanianccca3152017-02-22 16:32:36 -080040import android.view.Window;
41import android.view.WindowManager;
Eric Erfanianccca3152017-02-22 16:32:36 -080042import com.android.contacts.common.compat.CallCompat;
43import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler;
44import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler.OnCheckBlockedListener;
Eric Erfanian83b20212017-05-31 08:53:10 -070045import com.android.dialer.blocking.FilteredNumberCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080046import com.android.dialer.blocking.FilteredNumbersUtil;
twyen8efb4952017-10-06 16:35:54 -070047import com.android.dialer.common.Assert;
Eric Erfanianccca3152017-02-22 16:32:36 -080048import com.android.dialer.common.LogUtil;
zachh6a4cebd2017-10-24 17:10:06 -070049import com.android.dialer.common.concurrent.DialerExecutorComponent;
Eric Erfaniand8046e52017-04-06 09:41:50 -070050import com.android.dialer.enrichedcall.EnrichedCallComponent;
Eric Erfanian10b34a52017-05-04 08:23:17 -070051import com.android.dialer.location.GeoUtil;
Eric Erfanian8369df02017-05-03 10:27:13 -070052import com.android.dialer.logging.InteractionEvent;
Eric Erfanianccca3152017-02-22 16:32:36 -080053import com.android.dialer.logging.Logger;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070054import com.android.dialer.postcall.PostCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080055import com.android.dialer.telecom.TelecomUtil;
56import com.android.dialer.util.TouchPointManager;
57import com.android.incallui.InCallOrientationEventListener.ScreenOrientation;
58import com.android.incallui.answerproximitysensor.PseudoScreenState;
yueg77cb8e52017-10-27 16:42:51 -070059import com.android.incallui.audiomode.AudioModeProvider;
Eric Erfanianccca3152017-02-22 16:32:36 -080060import com.android.incallui.call.CallList;
61import com.android.incallui.call.DialerCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080062import com.android.incallui.call.ExternalCallList;
Eric Erfanianccca3152017-02-22 16:32:36 -080063import com.android.incallui.call.TelecomAdapter;
Eric Erfanian2ca43182017-08-31 06:57:16 -070064import com.android.incallui.disconnectdialog.DisconnectMessage;
twyen8efb4952017-10-06 16:35:54 -070065import com.android.incallui.incalluilock.InCallUiLock;
Eric Erfanianccca3152017-02-22 16:32:36 -080066import com.android.incallui.latencyreport.LatencyReport;
67import com.android.incallui.legacyblocking.BlockedNumberContentObserver;
68import com.android.incallui.spam.SpamCallListListener;
69import com.android.incallui.util.TelecomCallUtil;
70import com.android.incallui.videosurface.bindings.VideoSurfaceBindings;
71import com.android.incallui.videosurface.protocol.VideoSurfaceTexture;
Eric Erfanian90508232017-03-24 09:31:16 -070072import com.android.incallui.videotech.utils.VideoUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080073import java.util.Collections;
74import java.util.List;
75import java.util.Objects;
76import java.util.Set;
77import java.util.concurrent.ConcurrentHashMap;
78import java.util.concurrent.CopyOnWriteArrayList;
79import java.util.concurrent.atomic.AtomicBoolean;
80
81/**
82 * Takes updates from the CallList and notifies the InCallActivity (UI) of the changes. Responsible
83 * for starting the activity for a new call and finishing the activity when all calls are
84 * disconnected. Creates and manages the in-call state and provides a listener pattern for the
85 * presenters that want to listen in on the in-call state changes. TODO: This class has become more
86 * of a state machine at this point. Consider renaming.
87 */
yueg77cb8e52017-10-27 16:42:51 -070088public class InCallPresenter implements CallList.Listener, AudioModeProvider.AudioModeListener {
Eric Erfanian2ca43182017-08-31 06:57:16 -070089 private static final String PIXEL2017_SYSTEM_FEATURE =
90 "com.google.android.feature.PIXEL_2017_EXPERIENCE";
Eric Erfanianccca3152017-02-22 16:32:36 -080091 private static final String EXTRA_FIRST_TIME_SHOWN =
92 "com.android.incallui.intent.extra.FIRST_TIME_SHOWN";
93
94 private static final long BLOCK_QUERY_TIMEOUT_MS = 1000;
95
96 private static final Bundle EMPTY_EXTRAS = new Bundle();
97
98 private static InCallPresenter sInCallPresenter;
99
100 /**
101 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before
102 * resizing, 1 means we only expect a single thread to access the map so make only a single shard
103 */
104 private final Set<InCallStateListener> mListeners =
105 Collections.newSetFromMap(new ConcurrentHashMap<InCallStateListener, Boolean>(8, 0.9f, 1));
106
107 private final List<IncomingCallListener> mIncomingCallListeners = new CopyOnWriteArrayList<>();
108 private final Set<InCallDetailsListener> mDetailsListeners =
109 Collections.newSetFromMap(new ConcurrentHashMap<InCallDetailsListener, Boolean>(8, 0.9f, 1));
110 private final Set<CanAddCallListener> mCanAddCallListeners =
111 Collections.newSetFromMap(new ConcurrentHashMap<CanAddCallListener, Boolean>(8, 0.9f, 1));
112 private final Set<InCallUiListener> mInCallUiListeners =
113 Collections.newSetFromMap(new ConcurrentHashMap<InCallUiListener, Boolean>(8, 0.9f, 1));
114 private final Set<InCallOrientationListener> mOrientationListeners =
115 Collections.newSetFromMap(
116 new ConcurrentHashMap<InCallOrientationListener, Boolean>(8, 0.9f, 1));
117 private final Set<InCallEventListener> mInCallEventListeners =
118 Collections.newSetFromMap(new ConcurrentHashMap<InCallEventListener, Boolean>(8, 0.9f, 1));
119
120 private StatusBarNotifier mStatusBarNotifier;
121 private ExternalCallNotifier mExternalCallNotifier;
122 private ContactInfoCache mContactInfoCache;
123 private Context mContext;
124 private final OnCheckBlockedListener mOnCheckBlockedListener =
125 new OnCheckBlockedListener() {
126 @Override
127 public void onCheckComplete(final Integer id) {
128 if (id != null && id != FilteredNumberAsyncQueryHandler.INVALID_ID) {
129 // Silence the ringer now to prevent ringing and vibration before the call is
130 // terminated when Telecom attempts to add it.
131 TelecomUtil.silenceRinger(mContext);
132 }
133 }
134 };
135 private CallList mCallList;
136 private ExternalCallList mExternalCallList;
137 private InCallActivity mInCallActivity;
138 private ManageConferenceActivity mManageConferenceActivity;
139 private final android.telecom.Call.Callback mCallCallback =
140 new android.telecom.Call.Callback() {
141 @Override
142 public void onPostDialWait(
143 android.telecom.Call telecomCall, String remainingPostDialSequence) {
144 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
145 if (call == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700146 LogUtil.w(
147 "InCallPresenter.onPostDialWait",
148 "DialerCall not found in call list: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800149 return;
150 }
151 onPostDialCharWait(call.getId(), remainingPostDialSequence);
152 }
153
154 @Override
155 public void onDetailsChanged(
156 android.telecom.Call telecomCall, android.telecom.Call.Details details) {
157 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
158 if (call == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700159 LogUtil.w(
160 "InCallPresenter.onDetailsChanged",
161 "DialerCall not found in call list: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800162 return;
163 }
164
165 if (details.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL)
166 && !mExternalCallList.isCallTracked(telecomCall)) {
167
168 // A regular call became an external call so swap call lists.
Eric Erfanian2ca43182017-08-31 06:57:16 -0700169 LogUtil.i("InCallPresenter.onDetailsChanged", "Call became external: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800170 mCallList.onInternalCallMadeExternal(mContext, telecomCall);
171 mExternalCallList.onCallAdded(telecomCall);
172 return;
173 }
174
175 for (InCallDetailsListener listener : mDetailsListeners) {
176 listener.onDetailsChanged(call, details);
177 }
178 }
179
180 @Override
181 public void onConferenceableCallsChanged(
182 android.telecom.Call telecomCall, List<android.telecom.Call> conferenceableCalls) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700183 LogUtil.i(
184 "InCallPresenter.onConferenceableCallsChanged",
185 "onConferenceableCallsChanged: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800186 onDetailsChanged(telecomCall, telecomCall.getDetails());
187 }
188 };
189 private InCallState mInCallState = InCallState.NO_CALLS;
190 private ProximitySensor mProximitySensor;
191 private final PseudoScreenState mPseudoScreenState = new PseudoScreenState();
192 private boolean mServiceConnected;
Eric Erfanianccca3152017-02-22 16:32:36 -0800193 private InCallCameraManager mInCallCameraManager;
194 private FilteredNumberAsyncQueryHandler mFilteredQueryHandler;
195 private CallList.Listener mSpamCallListListener;
196 /** Whether or not we are currently bound and waiting for Telecom to send us a new call. */
197 private boolean mBoundAndWaitingForOutgoingCall;
198 /** Determines if the InCall UI is in fullscreen mode or not. */
199 private boolean mIsFullScreen = false;
200
Eric Erfanian2ca43182017-08-31 06:57:16 -0700201 private boolean mScreenTimeoutEnabled = true;
202
Eric Erfanianccca3152017-02-22 16:32:36 -0800203 private PhoneStateListener mPhoneStateListener =
204 new PhoneStateListener() {
205 @Override
206 public void onCallStateChanged(int state, String incomingNumber) {
207 if (state == TelephonyManager.CALL_STATE_RINGING) {
208 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
209 return;
210 }
211 // Check if the number is blocked, to silence the ringer.
212 String countryIso = GeoUtil.getCurrentCountryIso(mContext);
213 mFilteredQueryHandler.isBlockedNumber(
214 mOnCheckBlockedListener, incomingNumber, countryIso);
215 }
216 }
217 };
218 /**
219 * Is true when the activity has been previously started. Some code needs to know not just if the
220 * activity is currently up, but if it had been previously shown in foreground for this in-call
221 * session (e.g., StatusBarNotifier). This gets reset when the session ends in the tear-down
222 * method.
223 */
224 private boolean mIsActivityPreviouslyStarted = false;
225
226 /** Whether or not InCallService is bound to Telecom. */
227 private boolean mServiceBound = false;
228
229 /**
230 * When configuration changes Android kills the current activity and starts a new one. The flag is
231 * used to check if full clean up is necessary (activity is stopped and new activity won't be
232 * started), or if a new activity will be started right after the current one is destroyed, and
233 * therefore no need in release all resources.
234 */
235 private boolean mIsChangingConfigurations = false;
236
237 private boolean mAwaitingCallListUpdate = false;
238
239 private ExternalCallList.ExternalCallListener mExternalCallListener =
240 new ExternalCallList.ExternalCallListener() {
241
242 @Override
243 public void onExternalCallPulled(android.telecom.Call call) {
244 // Note: keep this code in sync with InCallPresenter#onCallAdded
245 LatencyReport latencyReport = new LatencyReport(call);
246 latencyReport.onCallBlockingDone();
247 // Note: External calls do not require spam checking.
248 mCallList.onCallAdded(mContext, call, latencyReport);
249 call.registerCallback(mCallCallback);
250 }
251
252 @Override
253 public void onExternalCallAdded(android.telecom.Call call) {
254 // No-op
255 }
256
257 @Override
258 public void onExternalCallRemoved(android.telecom.Call call) {
259 // No-op
260 }
261
262 @Override
263 public void onExternalCallUpdated(android.telecom.Call call) {
264 // No-op
265 }
266 };
267
268 private ThemeColorManager mThemeColorManager;
269 private VideoSurfaceTexture mLocalVideoSurfaceTexture;
270 private VideoSurfaceTexture mRemoteVideoSurfaceTexture;
271
Eric Erfanian10b34a52017-05-04 08:23:17 -0700272 /** Inaccessible constructor. Must use getRunningInstance() to get this singleton. */
Eric Erfanianccca3152017-02-22 16:32:36 -0800273 @VisibleForTesting
274 InCallPresenter() {}
275
276 public static synchronized InCallPresenter getInstance() {
277 if (sInCallPresenter == null) {
wangqic8cf79e2017-10-17 09:21:00 -0700278 Trace.beginSection("InCallPresenter.Constructor");
Eric Erfanianccca3152017-02-22 16:32:36 -0800279 sInCallPresenter = new InCallPresenter();
wangqic8cf79e2017-10-17 09:21:00 -0700280 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800281 }
282 return sInCallPresenter;
283 }
284
Eric Erfanian10b34a52017-05-04 08:23:17 -0700285 @VisibleForTesting
286 public static synchronized void setInstanceForTesting(InCallPresenter inCallPresenter) {
287 sInCallPresenter = inCallPresenter;
288 }
289
Eric Erfanianccca3152017-02-22 16:32:36 -0800290 /**
291 * Determines whether or not a call has no valid phone accounts that can be used to make the call
292 * with. Emergency calls do not require a phone account.
293 *
294 * @param call to check accounts for.
295 * @return {@code true} if the call has no call capable phone accounts set, {@code false} if the
296 * call contains a phone account that could be used to initiate it with, or is an emergency
297 * call.
298 */
299 public static boolean isCallWithNoValidAccounts(DialerCall call) {
300 if (call != null && !call.isEmergencyCall()) {
301 Bundle extras = call.getIntentExtras();
302
303 if (extras == null) {
304 extras = EMPTY_EXTRAS;
305 }
306
307 final List<PhoneAccountHandle> phoneAccountHandles =
308 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
309
310 if ((call.getAccountHandle() == null
311 && (phoneAccountHandles == null || phoneAccountHandles.isEmpty()))) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700312 LogUtil.i(
313 "InCallPresenter.isCallWithNoValidAccounts", "No valid accounts for call " + call);
Eric Erfanianccca3152017-02-22 16:32:36 -0800314 return true;
315 }
316 }
317 return false;
318 }
319
320 public InCallState getInCallState() {
321 return mInCallState;
322 }
323
324 public CallList getCallList() {
325 return mCallList;
326 }
327
328 public void setUp(
329 @NonNull Context context,
330 CallList callList,
331 ExternalCallList externalCallList,
332 StatusBarNotifier statusBarNotifier,
333 ExternalCallNotifier externalCallNotifier,
334 ContactInfoCache contactInfoCache,
Eric Erfanian83b20212017-05-31 08:53:10 -0700335 ProximitySensor proximitySensor,
336 FilteredNumberAsyncQueryHandler filteredNumberQueryHandler) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700337 Trace.beginSection("InCallPresenter.setUp");
Eric Erfanianccca3152017-02-22 16:32:36 -0800338 if (mServiceConnected) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700339 LogUtil.i("InCallPresenter.setUp", "New service connection replacing existing one.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800340 if (context != mContext || callList != mCallList) {
341 throw new IllegalStateException();
342 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700343 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800344 return;
345 }
346
347 Objects.requireNonNull(context);
348 mContext = context;
349
350 mContactInfoCache = contactInfoCache;
351
352 mStatusBarNotifier = statusBarNotifier;
353 mExternalCallNotifier = externalCallNotifier;
354 addListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -0700355 EnrichedCallComponent.get(mContext)
356 .getEnrichedCallManager()
357 .registerStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -0800358
359 mProximitySensor = proximitySensor;
360 addListener(mProximitySensor);
361
wangqi8d662ca2017-10-26 11:27:19 -0700362 if (mThemeColorManager == null) {
363 mThemeColorManager =
364 new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources()));
365 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800366
367 mCallList = callList;
368 mExternalCallList = externalCallList;
369 externalCallList.addExternalCallListener(mExternalCallNotifier);
370 externalCallList.addExternalCallListener(mExternalCallListener);
371
372 // This only gets called by the service so this is okay.
373 mServiceConnected = true;
374
375 // The final thing we do in this set up is add ourselves as a listener to CallList. This
376 // will kick off an update and the whole process can start.
377 mCallList.addListener(this);
378
379 // Create spam call list listener and add it to the list of listeners
zachh6a4cebd2017-10-24 17:10:06 -0700380 mSpamCallListListener =
381 new SpamCallListListener(
382 context, DialerExecutorComponent.get(context).dialerExecutorFactory());
Eric Erfanianccca3152017-02-22 16:32:36 -0800383 mCallList.addListener(mSpamCallListListener);
384
385 VideoPauseController.getInstance().setUp(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800386
Eric Erfanian83b20212017-05-31 08:53:10 -0700387 mFilteredQueryHandler = filteredNumberQueryHandler;
Eric Erfanianccca3152017-02-22 16:32:36 -0800388 mContext
389 .getSystemService(TelephonyManager.class)
390 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
391
yueg77cb8e52017-10-27 16:42:51 -0700392 AudioModeProvider.getInstance().addListener(this);
393
Eric Erfanian2ca43182017-08-31 06:57:16 -0700394 LogUtil.d("InCallPresenter.setUp", "Finished InCallPresenter.setUp");
395 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800396 }
397
398 /**
399 * Called when the telephony service has disconnected from us. This will happen when there are no
400 * more active calls. However, we may still want to continue showing the UI for certain cases like
401 * showing "Call Ended". What we really want is to wait for the activity and the service to both
402 * disconnect before we tear things down. This method sets a serviceConnected boolean and calls a
403 * secondary method that performs the aforementioned logic.
404 */
405 public void tearDown() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700406 LogUtil.d("InCallPresenter.tearDown", "tearDown");
Eric Erfanianccca3152017-02-22 16:32:36 -0800407 mCallList.clearOnDisconnect();
408
409 mServiceConnected = false;
410
411 mContext
412 .getSystemService(TelephonyManager.class)
413 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
414
415 attemptCleanup();
416 VideoPauseController.getInstance().tearDown();
yueg77cb8e52017-10-27 16:42:51 -0700417 AudioModeProvider.getInstance().removeListener(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800418 }
419
420 private void attemptFinishActivity() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700421 mScreenTimeoutEnabled = true;
Eric Erfanianccca3152017-02-22 16:32:36 -0800422 final boolean doFinish = (mInCallActivity != null && isActivityStarted());
Eric Erfanian2ca43182017-08-31 06:57:16 -0700423 LogUtil.i("InCallPresenter.attemptFinishActivity", "Hide in call UI: " + doFinish);
Eric Erfanianccca3152017-02-22 16:32:36 -0800424 if (doFinish) {
425 mInCallActivity.setExcludeFromRecents(true);
426 mInCallActivity.finish();
Eric Erfanianccca3152017-02-22 16:32:36 -0800427 }
428 }
429
430 /**
431 * Called when the UI ends. Attempts to tear down everything if necessary. See {@link #tearDown()}
432 * for more insight on the tear-down process.
433 */
434 public void unsetActivity(InCallActivity inCallActivity) {
435 if (inCallActivity == null) {
436 throw new IllegalArgumentException("unregisterActivity cannot be called with null");
437 }
438 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700439 LogUtil.i(
440 "InCallPresenter.unsetActivity", "No InCallActivity currently set, no need to unset.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800441 return;
442 }
443 if (mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700444 LogUtil.w(
445 "InCallPresenter.unsetActivity",
Eric Erfanianccca3152017-02-22 16:32:36 -0800446 "Second instance of InCallActivity is trying to unregister when another"
447 + " instance is active. Ignoring.");
448 return;
449 }
450 updateActivity(null);
451 }
452
453 /**
454 * Updates the current instance of {@link InCallActivity} with the provided one. If a {@code null}
455 * activity is provided, it means that the activity was finished and we should attempt to cleanup.
456 */
457 private void updateActivity(InCallActivity inCallActivity) {
wangqi9982f0d2017-10-11 17:46:07 -0700458 Trace.beginSection("InCallPresenter.updateActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -0800459 boolean updateListeners = false;
460 boolean doAttemptCleanup = false;
461
462 if (inCallActivity != null) {
463 if (mInCallActivity == null) {
Eric Erfanian938468d2017-10-24 14:05:52 -0700464 mContext = inCallActivity.getApplicationContext();
Eric Erfanianccca3152017-02-22 16:32:36 -0800465 updateListeners = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700466 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized");
Eric Erfanianccca3152017-02-22 16:32:36 -0800467 } else {
468 // since setActivity is called onStart(), it can be called multiple times.
469 // This is fine and ignorable, but we do not want to update the world every time
470 // this happens (like going to/from background) so we do not set updateListeners.
471 }
472
473 mInCallActivity = inCallActivity;
474 mInCallActivity.setExcludeFromRecents(false);
475
476 // By the time the UI finally comes up, the call may already be disconnected.
477 // If that's the case, we may need to show an error dialog.
478 if (mCallList != null && mCallList.getDisconnectedCall() != null) {
479 maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
480 }
481
482 // When the UI comes up, we need to first check the in-call state.
483 // If we are showing NO_CALLS, that means that a call probably connected and
484 // then immediately disconnected before the UI was able to come up.
485 // If we dont have any calls, start tearing down the UI instead.
486 // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
487 // it has been set.
488 if (mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700489 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized, but no calls left. Shut down");
Eric Erfanianccca3152017-02-22 16:32:36 -0800490 attemptFinishActivity();
wangqi9982f0d2017-10-11 17:46:07 -0700491 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800492 return;
493 }
494 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700495 LogUtil.i("InCallPresenter.updateActivity", "UI Destroyed");
Eric Erfanianccca3152017-02-22 16:32:36 -0800496 updateListeners = true;
497 mInCallActivity = null;
498
499 // We attempt cleanup for the destroy case but only after we recalculate the state
500 // to see if we need to come back up or stay shut down. This is why we do the
501 // cleanup after the call to onCallListChange() instead of directly here.
502 doAttemptCleanup = true;
503 }
504
505 // Messages can come from the telephony layer while the activity is coming up
506 // and while the activity is going down. So in both cases we need to recalculate what
507 // state we should be in after they complete.
508 // Examples: (1) A new incoming call could come in and then get disconnected before
509 // the activity is created.
510 // (2) All calls could disconnect and then get a new incoming call before the
511 // activity is destroyed.
512 //
Eric Erfanian938468d2017-10-24 14:05:52 -0700513 // a bug - We previously had a check for mServiceConnected here as well, but there are
Eric Erfanianccca3152017-02-22 16:32:36 -0800514 // cases where we need to recalculate the current state even if the service in not
515 // connected. In particular the case where startOrFinish() is called while the app is
516 // already finish()ing. In that case, we skip updating the state with the knowledge that
517 // we will check again once the activity has finished. That means we have to recalculate the
518 // state here even if the service is disconnected since we may not have finished a state
519 // transition while finish()ing.
520 if (updateListeners) {
521 onCallListChange(mCallList);
522 }
523
524 if (doAttemptCleanup) {
525 attemptCleanup();
526 }
wangqi9982f0d2017-10-11 17:46:07 -0700527 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800528 }
529
530 public void setManageConferenceActivity(
531 @Nullable ManageConferenceActivity manageConferenceActivity) {
532 mManageConferenceActivity = manageConferenceActivity;
533 }
534
535 public void onBringToForeground(boolean showDialpad) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700536 LogUtil.i("InCallPresenter.onBringToForeground", "Bringing UI to foreground.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800537 bringToForeground(showDialpad);
538 }
539
540 public void onCallAdded(final android.telecom.Call call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700541 Trace.beginSection("InCallPresenter.onCallAdded");
Eric Erfanianccca3152017-02-22 16:32:36 -0800542 LatencyReport latencyReport = new LatencyReport(call);
543 if (shouldAttemptBlocking(call)) {
544 maybeBlockCall(call, latencyReport);
545 } else {
546 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
547 mExternalCallList.onCallAdded(call);
548 } else {
549 latencyReport.onCallBlockingDone();
550 mCallList.onCallAdded(mContext, call, latencyReport);
551 }
552 }
553
554 // Since a call has been added we are no longer waiting for Telecom to send us a call.
555 setBoundAndWaitingForOutgoingCall(false, null);
556 call.registerCallback(mCallCallback);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700557 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800558 }
559
560 private boolean shouldAttemptBlocking(android.telecom.Call call) {
561 if (call.getState() != android.telecom.Call.STATE_RINGING) {
562 return false;
563 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700564 if (!UserManagerCompat.isUserUnlocked(mContext)) {
565 LogUtil.i(
566 "InCallPresenter.shouldAttemptBlocking",
567 "not attempting to block incoming call because user is locked");
568 return false;
569 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800570 if (TelecomCallUtil.isEmergencyCall(call)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700571 LogUtil.i(
572 "InCallPresenter.shouldAttemptBlocking",
573 "Not attempting to block incoming emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800574 return false;
575 }
576 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700577 LogUtil.i(
578 "InCallPresenter.shouldAttemptBlocking",
579 "Not attempting to block incoming call due to recent emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800580 return false;
581 }
582 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
583 return false;
584 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700585 if (FilteredNumberCompat.useNewFiltering(mContext)) {
586 LogUtil.i(
587 "InCallPresenter.shouldAttemptBlocking",
588 "not attempting to block incoming call because framework blocking is in use");
589 return false;
590 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800591 return true;
592 }
593
594 /**
595 * Checks whether a call should be blocked, and blocks it if so. Otherwise, it adds the call to
596 * the CallList so it can proceed as normal. There is a timeout, so if the function for checking
597 * whether a function is blocked does not return in a reasonable time, we proceed with adding the
598 * call anyways.
599 */
600 private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) {
601 final String countryIso = GeoUtil.getCurrentCountryIso(mContext);
602 final String number = TelecomCallUtil.getNumber(call);
603 final long timeAdded = System.currentTimeMillis();
604
605 // Though AtomicBoolean's can be scary, don't fear, as in this case it is only used on the
606 // main UI thread. It is needed so we can change its value within different scopes, since
607 // that cannot be done with a final boolean.
608 final AtomicBoolean hasTimedOut = new AtomicBoolean(false);
609
610 final Handler handler = new Handler();
611
612 // Proceed if the query is slow; the call may still be blocked after the query returns.
613 final Runnable runnable =
614 new Runnable() {
615 @Override
616 public void run() {
617 hasTimedOut.set(true);
618 latencyReport.onCallBlockingDone();
619 mCallList.onCallAdded(mContext, call, latencyReport);
620 }
621 };
622 handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS);
623
624 OnCheckBlockedListener onCheckBlockedListener =
625 new OnCheckBlockedListener() {
626 @Override
627 public void onCheckComplete(final Integer id) {
628 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700629 LogUtil.i("InCallPresenter.onCheckComplete", "torn down, not adding call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800630 return;
631 }
632 if (!hasTimedOut.get()) {
633 handler.removeCallbacks(runnable);
634 }
635 if (id == null) {
636 if (!hasTimedOut.get()) {
637 latencyReport.onCallBlockingDone();
638 mCallList.onCallAdded(mContext, call, latencyReport);
639 }
640 } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700641 LogUtil.d(
642 "InCallPresenter.onCheckComplete", "invalid number, skipping block checking");
Eric Erfanianccca3152017-02-22 16:32:36 -0800643 if (!hasTimedOut.get()) {
644 handler.removeCallbacks(runnable);
645
646 latencyReport.onCallBlockingDone();
647 mCallList.onCallAdded(mContext, call, latencyReport);
648 }
649 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700650 LogUtil.i(
651 "InCallPresenter.onCheckComplete", "Rejecting incoming call from blocked number");
Eric Erfanianccca3152017-02-22 16:32:36 -0800652 call.reject(false, null);
653 Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED);
654
655 /*
656 * If mContext is null, then the InCallPresenter was torn down before the
657 * block check had a chance to complete. The context is no longer valid, so
658 * don't attempt to remove the call log entry.
659 */
660 if (mContext == null) {
661 return;
662 }
663 // Register observer to update the call log.
664 // BlockedNumberContentObserver will unregister after successful log or timeout.
665 BlockedNumberContentObserver contentObserver =
666 new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded);
667 contentObserver.register();
668 }
669 }
670 };
671
672 mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso);
673 }
674
675 public void onCallRemoved(android.telecom.Call call) {
676 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
677 mExternalCallList.onCallRemoved(call);
678 } else {
679 mCallList.onCallRemoved(mContext, call);
680 call.unregisterCallback(mCallCallback);
681 }
682 }
683
684 public void onCanAddCallChanged(boolean canAddCall) {
685 for (CanAddCallListener listener : mCanAddCallListeners) {
686 listener.onCanAddCallChanged(canAddCall);
687 }
688 }
689
690 @Override
691 public void onWiFiToLteHandover(DialerCall call) {
692 if (mInCallActivity != null) {
693 mInCallActivity.onWiFiToLteHandover(call);
694 }
695 }
696
697 @Override
698 public void onHandoverToWifiFailed(DialerCall call) {
699 if (mInCallActivity != null) {
700 mInCallActivity.onHandoverToWifiFailed(call);
701 }
702 }
703
Eric Erfanianc857f902017-05-15 14:05:33 -0700704 @Override
705 public void onInternationalCallOnWifi(@NonNull DialerCall call) {
706 LogUtil.enterBlock("InCallPresenter.onInternationalCallOnWifi");
707 if (mInCallActivity != null) {
708 mInCallActivity.onInternationalCallOnWifi(call);
709 }
710 }
711
Eric Erfanianccca3152017-02-22 16:32:36 -0800712 /**
713 * Called when there is a change to the call list. Sets the In-Call state for the entire in-call
714 * app based on the information it gets from CallList. Dispatches the in-call state to all
715 * listeners. Can trigger the creation or destruction of the UI based on the states that is
716 * calculates.
717 */
718 @Override
719 public void onCallListChange(CallList callList) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700720 Trace.beginSection("InCallPresenter.onCallListChange");
Eric Erfanianccca3152017-02-22 16:32:36 -0800721 if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) {
722 mAwaitingCallListUpdate = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700723 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800724 return;
725 }
726 if (callList == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700727 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800728 return;
729 }
730
731 mAwaitingCallListUpdate = false;
732
733 InCallState newState = getPotentialStateFromCallList(callList);
734 InCallState oldState = mInCallState;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700735 LogUtil.d(
736 "InCallPresenter.onCallListChange",
737 "onCallListChange oldState= " + oldState + " newState=" + newState);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700738
739 // If the user placed a call and was asked to choose the account, but then pressed "Home", the
740 // incall activity for that call will still exist (even if it's not visible). In the case of
741 // an incoming call in that situation, just disconnect that "waiting for account" call and
742 // dismiss the dialog. The same activity will be reused to handle the new incoming call. See
Eric Erfanian938468d2017-10-24 14:05:52 -0700743 // a bug for more details.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700744 DialerCall waitingForAccountCall;
745 if (newState == InCallState.INCOMING
746 && (waitingForAccountCall = callList.getWaitingForAccountCall()) != null) {
747 waitingForAccountCall.disconnect();
Eric Erfanian2ca43182017-08-31 06:57:16 -0700748 // The InCallActivity might be destroyed or not started yet at this point.
749 if (isActivityStarted()) {
750 mInCallActivity.dismissPendingDialogs();
751 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700752 }
753
Eric Erfanianccca3152017-02-22 16:32:36 -0800754 newState = startOrFinishUi(newState);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700755 LogUtil.d(
756 "InCallPresenter.onCallListChange", "onCallListChange newState changed to " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800757
758 // Set the new state before announcing it to the world
Eric Erfanian2ca43182017-08-31 06:57:16 -0700759 LogUtil.i(
760 "InCallPresenter.onCallListChange",
761 "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800762 mInCallState = newState;
763
764 // notify listeners of new state
765 for (InCallStateListener listener : mListeners) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700766 LogUtil.d(
767 "InCallPresenter.onCallListChange",
768 "Notify " + listener + " of state " + mInCallState.toString());
Eric Erfanianccca3152017-02-22 16:32:36 -0800769 listener.onStateChange(oldState, mInCallState, callList);
770 }
771
772 if (isActivityStarted()) {
773 final boolean hasCall =
774 callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null;
775 mInCallActivity.dismissKeyguard(hasCall);
776 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700777 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800778 }
779
780 /** Called when there is a new incoming call. */
781 @Override
782 public void onIncomingCall(DialerCall call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700783 Trace.beginSection("InCallPresenter.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800784 InCallState newState = startOrFinishUi(InCallState.INCOMING);
785 InCallState oldState = mInCallState;
786
Eric Erfanian2ca43182017-08-31 06:57:16 -0700787 LogUtil.i(
788 "InCallPresenter.onIncomingCall", "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800789 mInCallState = newState;
790
wangqicf61ca02017-08-31 15:32:55 -0700791 Trace.beginSection("listener.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800792 for (IncomingCallListener listener : mIncomingCallListeners) {
793 listener.onIncomingCall(oldState, mInCallState, call);
794 }
wangqicf61ca02017-08-31 15:32:55 -0700795 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800796
wangqicf61ca02017-08-31 15:32:55 -0700797 Trace.beginSection("onPrimaryCallStateChanged");
Eric Erfanianccca3152017-02-22 16:32:36 -0800798 if (mInCallActivity != null) {
799 // Re-evaluate which fragment is being shown.
800 mInCallActivity.onPrimaryCallStateChanged();
801 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700802 Trace.endSection();
wangqicf61ca02017-08-31 15:32:55 -0700803 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800804 }
805
806 @Override
807 public void onUpgradeToVideo(DialerCall call) {
Eric Erfanian90508232017-03-24 09:31:16 -0700808 if (VideoUtils.hasReceivedVideoUpgradeRequest(call.getVideoTech().getSessionModificationState())
Eric Erfanianccca3152017-02-22 16:32:36 -0800809 && mInCallState == InCallPresenter.InCallState.INCOMING) {
810 LogUtil.i(
811 "InCallPresenter.onUpgradeToVideo",
812 "rejecting upgrade request due to existing incoming call");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700813 call.getVideoTech().declineVideoRequest();
Eric Erfanianccca3152017-02-22 16:32:36 -0800814 }
815
816 if (mInCallActivity != null) {
817 // Re-evaluate which fragment is being shown.
818 mInCallActivity.onPrimaryCallStateChanged();
819 }
820 }
821
822 @Override
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700823 public void onSessionModificationStateChange(DialerCall call) {
824 int newState = call.getVideoTech().getSessionModificationState();
Eric Erfanianccca3152017-02-22 16:32:36 -0800825 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
826 if (mProximitySensor == null) {
827 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
828 return;
829 }
830 mProximitySensor.setIsAttemptingVideoCall(
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700831 call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest());
Eric Erfanianccca3152017-02-22 16:32:36 -0800832 if (mInCallActivity != null) {
833 // Re-evaluate which fragment is being shown.
834 mInCallActivity.onPrimaryCallStateChanged();
835 }
836 }
837
838 /**
839 * Called when a call becomes disconnected. Called everytime an existing call changes from being
840 * connected (incoming/outgoing/active) to disconnected.
841 */
842 @Override
843 public void onDisconnect(DialerCall call) {
844 maybeShowErrorDialogOnDisconnect(call);
845
846 // We need to do the run the same code as onCallListChange.
847 onCallListChange(mCallList);
848
849 if (isActivityStarted()) {
850 mInCallActivity.dismissKeyguard(false);
851 }
852
853 if (call.isEmergencyCall()) {
854 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
855 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800856
Eric Erfanianfc37b022017-03-21 10:11:17 -0700857 if (!mCallList.hasLiveCall()
858 && !call.getLogState().isIncoming
Eric Erfanian10b34a52017-05-04 08:23:17 -0700859 && !isSecretCode(call.getNumber())
wangqi9982f0d2017-10-11 17:46:07 -0700860 && !call.isVoiceMailNumber()) {
Eric Erfanian10b34a52017-05-04 08:23:17 -0700861 PostCall.onCallDisconnected(mContext, call.getNumber(), call.getConnectTimeMillis());
Eric Erfanianccca3152017-02-22 16:32:36 -0800862 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800863 }
864
Eric Erfanian10b34a52017-05-04 08:23:17 -0700865 private boolean isSecretCode(@Nullable String number) {
866 return number != null
867 && (number.length() <= 8 || number.startsWith("*#*#") || number.endsWith("#*#*"));
868 }
869
Eric Erfanianccca3152017-02-22 16:32:36 -0800870 /** Given the call list, return the state in which the in-call screen should be. */
871 public InCallState getPotentialStateFromCallList(CallList callList) {
872
873 InCallState newState = InCallState.NO_CALLS;
874
875 if (callList == null) {
876 return newState;
877 }
878 if (callList.getIncomingCall() != null) {
879 newState = InCallState.INCOMING;
880 } else if (callList.getWaitingForAccountCall() != null) {
881 newState = InCallState.WAITING_FOR_ACCOUNT;
882 } else if (callList.getPendingOutgoingCall() != null) {
883 newState = InCallState.PENDING_OUTGOING;
884 } else if (callList.getOutgoingCall() != null) {
885 newState = InCallState.OUTGOING;
886 } else if (callList.getActiveCall() != null
887 || callList.getBackgroundCall() != null
888 || callList.getDisconnectedCall() != null
889 || callList.getDisconnectingCall() != null) {
890 newState = InCallState.INCALL;
891 }
892
893 if (newState == InCallState.NO_CALLS) {
894 if (mBoundAndWaitingForOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700895 return InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800896 }
897 }
898
899 return newState;
900 }
901
902 public boolean isBoundAndWaitingForOutgoingCall() {
903 return mBoundAndWaitingForOutgoingCall;
904 }
905
906 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700907 LogUtil.i(
908 "InCallPresenter.setBoundAndWaitingForOutgoingCall",
909 "setBoundAndWaitingForOutgoingCall: " + isBound);
Eric Erfanianccca3152017-02-22 16:32:36 -0800910 mBoundAndWaitingForOutgoingCall = isBound;
911 mThemeColorManager.setPendingPhoneAccountHandle(handle);
912 if (isBound && mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700913 mInCallState = InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800914 }
915 }
916
917 public void onShrinkAnimationComplete() {
918 if (mAwaitingCallListUpdate) {
919 onCallListChange(mCallList);
920 }
921 }
922
923 public void addIncomingCallListener(IncomingCallListener listener) {
924 Objects.requireNonNull(listener);
925 mIncomingCallListeners.add(listener);
926 }
927
928 public void removeIncomingCallListener(IncomingCallListener listener) {
929 if (listener != null) {
930 mIncomingCallListeners.remove(listener);
931 }
932 }
933
934 public void addListener(InCallStateListener listener) {
935 Objects.requireNonNull(listener);
936 mListeners.add(listener);
937 }
938
939 public void removeListener(InCallStateListener listener) {
940 if (listener != null) {
941 mListeners.remove(listener);
942 }
943 }
944
945 public void addDetailsListener(InCallDetailsListener listener) {
946 Objects.requireNonNull(listener);
947 mDetailsListeners.add(listener);
948 }
949
950 public void removeDetailsListener(InCallDetailsListener listener) {
951 if (listener != null) {
952 mDetailsListeners.remove(listener);
953 }
954 }
955
956 public void addCanAddCallListener(CanAddCallListener listener) {
957 Objects.requireNonNull(listener);
958 mCanAddCallListeners.add(listener);
959 }
960
961 public void removeCanAddCallListener(CanAddCallListener listener) {
962 if (listener != null) {
963 mCanAddCallListeners.remove(listener);
964 }
965 }
966
967 public void addOrientationListener(InCallOrientationListener listener) {
968 Objects.requireNonNull(listener);
969 mOrientationListeners.add(listener);
970 }
971
972 public void removeOrientationListener(InCallOrientationListener listener) {
973 if (listener != null) {
974 mOrientationListeners.remove(listener);
975 }
976 }
977
978 public void addInCallEventListener(InCallEventListener listener) {
979 Objects.requireNonNull(listener);
980 mInCallEventListeners.add(listener);
981 }
982
983 public void removeInCallEventListener(InCallEventListener listener) {
984 if (listener != null) {
985 mInCallEventListeners.remove(listener);
986 }
987 }
988
989 public ProximitySensor getProximitySensor() {
990 return mProximitySensor;
991 }
992
993 public PseudoScreenState getPseudoScreenState() {
994 return mPseudoScreenState;
995 }
996
997 /** Returns true if the incall app is the foreground application. */
998 public boolean isShowingInCallUi() {
999 if (!isActivityStarted()) {
1000 return false;
1001 }
1002 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
1003 return true;
1004 }
1005 return mInCallActivity.isVisible();
1006 }
1007
1008 /**
1009 * Returns true if the activity has been created and is running. Returns true as long as activity
1010 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
1011 * (not in foreground).
1012 */
1013 public boolean isActivityStarted() {
1014 return (mInCallActivity != null
1015 && !mInCallActivity.isDestroyed()
1016 && !mInCallActivity.isFinishing());
1017 }
1018
1019 /**
1020 * Determines if the In-Call app is currently changing configuration.
1021 *
1022 * @return {@code true} if the In-Call app is changing configuration.
1023 */
1024 public boolean isChangingConfigurations() {
1025 return mIsChangingConfigurations;
1026 }
1027
1028 /**
1029 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
1030 * screen orientation).
1031 */
1032 /*package*/
1033 void updateIsChangingConfigurations() {
1034 mIsChangingConfigurations = false;
1035 if (mInCallActivity != null) {
1036 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
1037 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001038 LogUtil.v(
1039 "InCallPresenter.updateIsChangingConfigurations",
1040 "updateIsChangingConfigurations = " + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001041 }
1042
1043 /** Called when the activity goes in/out of the foreground. */
1044 public void onUiShowing(boolean showing) {
1045 // We need to update the notification bar when we leave the UI because that
1046 // could trigger it to show again.
1047 if (mStatusBarNotifier != null) {
wangqic8cf79e2017-10-17 09:21:00 -07001048 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001049 }
1050
1051 if (mProximitySensor != null) {
1052 mProximitySensor.onInCallShowing(showing);
1053 }
1054
1055 Intent broadcastIntent = Bindings.get(mContext).getUiReadyBroadcastIntent(mContext);
1056 if (broadcastIntent != null) {
1057 broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
1058
1059 if (showing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001060 LogUtil.d("InCallPresenter.onUiShowing", "Sending sticky broadcast: ", broadcastIntent);
Eric Erfanianccca3152017-02-22 16:32:36 -08001061 mContext.sendStickyBroadcast(broadcastIntent);
1062 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001063 LogUtil.d("InCallPresenter.onUiShowing", "Removing sticky broadcast: ", broadcastIntent);
Eric Erfanianccca3152017-02-22 16:32:36 -08001064 mContext.removeStickyBroadcast(broadcastIntent);
1065 }
1066 }
1067
1068 if (showing) {
1069 mIsActivityPreviouslyStarted = true;
1070 } else {
1071 updateIsChangingConfigurations();
1072 }
1073
1074 for (InCallUiListener listener : mInCallUiListeners) {
1075 listener.onUiShowing(showing);
1076 }
1077
1078 if (mInCallActivity != null) {
1079 // Re-evaluate which fragment is being shown.
1080 mInCallActivity.onPrimaryCallStateChanged();
1081 }
1082 }
1083
Eric Erfanian2ca43182017-08-31 06:57:16 -07001084 public void refreshUi() {
1085 if (mInCallActivity != null) {
1086 // Re-evaluate which fragment is being shown.
1087 mInCallActivity.onPrimaryCallStateChanged();
1088 }
1089 }
1090
Eric Erfanianccca3152017-02-22 16:32:36 -08001091 public void addInCallUiListener(InCallUiListener listener) {
1092 mInCallUiListeners.add(listener);
1093 }
1094
1095 public boolean removeInCallUiListener(InCallUiListener listener) {
1096 return mInCallUiListeners.remove(listener);
1097 }
1098
1099 /*package*/
1100 void onActivityStarted() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001101 LogUtil.d("InCallPresenter.onActivityStarted", "onActivityStarted");
Eric Erfanianccca3152017-02-22 16:32:36 -08001102 notifyVideoPauseController(true);
Eric Erfanian2ca43182017-08-31 06:57:16 -07001103 applyScreenTimeout();
Eric Erfanianccca3152017-02-22 16:32:36 -08001104 }
1105
1106 /*package*/
1107 void onActivityStopped() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001108 LogUtil.d("InCallPresenter.onActivityStopped", "onActivityStopped");
Eric Erfanianccca3152017-02-22 16:32:36 -08001109 notifyVideoPauseController(false);
1110 }
1111
1112 private void notifyVideoPauseController(boolean showing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001113 LogUtil.d(
1114 "InCallPresenter.notifyVideoPauseController",
1115 "mIsChangingConfigurations=" + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001116 if (!mIsChangingConfigurations) {
1117 VideoPauseController.getInstance().onUiShowing(showing);
1118 }
1119 }
1120
1121 /** Brings the app into the foreground if possible. */
1122 public void bringToForeground(boolean showDialpad) {
1123 // Before we bring the incall UI to the foreground, we check to see if:
1124 // 1. It is not currently in the foreground
1125 // 2. We are in a state where we want to show the incall ui (i.e. there are calls to
1126 // be displayed)
1127 // If the activity hadn't actually been started previously, yet there are still calls
1128 // present (e.g. a call was accepted by a bluetooth or wired headset), we want to
1129 // bring it up the UI regardless.
1130 if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001131 showInCall(showDialpad, false /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001132 }
1133 }
1134
1135 public void onPostDialCharWait(String callId, String chars) {
1136 if (isActivityStarted()) {
1137 mInCallActivity.showPostCharWaitDialog(callId, chars);
1138 }
1139 }
1140
1141 /**
1142 * Handles the green CALL key while in-call.
1143 *
1144 * @return true if we consumed the event.
1145 */
1146 public boolean handleCallKey() {
1147 LogUtil.v("InCallPresenter.handleCallKey", null);
1148
1149 // The green CALL button means either "Answer", "Unhold", or
1150 // "Swap calls", or can be a no-op, depending on the current state
1151 // of the Phone.
1152
1153 /** INCOMING CALL */
1154 final CallList calls = mCallList;
1155 final DialerCall incomingCall = calls.getIncomingCall();
1156 LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall);
1157
1158 // (1) Attempt to answer a call
1159 if (incomingCall != null) {
1160 incomingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
1161 return true;
1162 }
1163
1164 /** STATE_ACTIVE CALL */
1165 final DialerCall activeCall = calls.getActiveCall();
1166 if (activeCall != null) {
1167 // TODO: This logic is repeated from CallButtonPresenter.java. We should
1168 // consolidate this logic.
1169 final boolean canMerge =
1170 activeCall.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
1171 final boolean canSwap =
1172 activeCall.can(android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
1173
Eric Erfanian2ca43182017-08-31 06:57:16 -07001174 LogUtil.v(
1175 "InCallPresenter.handleCallKey",
1176 "activeCall: " + activeCall + ", canMerge: " + canMerge + ", canSwap: " + canSwap);
Eric Erfanianccca3152017-02-22 16:32:36 -08001177
1178 // (2) Attempt actions on conference calls
1179 if (canMerge) {
1180 TelecomAdapter.getInstance().merge(activeCall.getId());
1181 return true;
1182 } else if (canSwap) {
1183 TelecomAdapter.getInstance().swap(activeCall.getId());
1184 return true;
1185 }
1186 }
1187
1188 /** BACKGROUND CALL */
1189 final DialerCall heldCall = calls.getBackgroundCall();
1190 if (heldCall != null) {
1191 // We have a hold call so presumeable it will always support HOLD...but
1192 // there is no harm in double checking.
1193 final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
1194
Eric Erfanian2ca43182017-08-31 06:57:16 -07001195 LogUtil.v("InCallPresenter.handleCallKey", "heldCall: " + heldCall + ", canHold: " + canHold);
Eric Erfanianccca3152017-02-22 16:32:36 -08001196
1197 // (4) unhold call
1198 if (heldCall.getState() == DialerCall.State.ONHOLD && canHold) {
1199 heldCall.unhold();
1200 return true;
1201 }
1202 }
1203
1204 // Always consume hard keys
1205 return true;
1206 }
1207
Eric Erfanianccca3152017-02-22 16:32:36 -08001208 /** Clears the previous fullscreen state. */
1209 public void clearFullscreen() {
1210 mIsFullScreen = false;
1211 }
1212
1213 /**
1214 * Changes the fullscreen mode of the in-call UI.
1215 *
1216 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1217 * otherwise.
1218 */
1219 public void setFullScreen(boolean isFullScreen) {
1220 setFullScreen(isFullScreen, false /* force */);
1221 }
1222
1223 /**
1224 * Changes the fullscreen mode of the in-call UI.
1225 *
1226 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1227 * otherwise.
1228 * @param force {@code true} if fullscreen mode should be set regardless of its current state.
1229 */
1230 public void setFullScreen(boolean isFullScreen, boolean force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001231 LogUtil.i("InCallPresenter.setFullScreen", "setFullScreen = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001232
1233 // As a safeguard, ensure we cannot enter fullscreen if the dialpad is shown.
1234 if (isDialpadVisible()) {
1235 isFullScreen = false;
Eric Erfanian2ca43182017-08-31 06:57:16 -07001236 LogUtil.v(
1237 "InCallPresenter.setFullScreen",
1238 "setFullScreen overridden as dialpad is shown = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001239 }
1240
1241 if (mIsFullScreen == isFullScreen && !force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001242 LogUtil.v("InCallPresenter.setFullScreen", "setFullScreen ignored as already in that state.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001243 return;
1244 }
1245 mIsFullScreen = isFullScreen;
1246 notifyFullscreenModeChange(mIsFullScreen);
1247 }
1248
1249 /**
1250 * @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
1251 * otherwise.
1252 */
1253 public boolean isFullscreen() {
1254 return mIsFullScreen;
1255 }
1256
1257 /**
1258 * Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
1259 *
1260 * @param isFullscreenMode {@code True} if entering full screen mode.
1261 */
1262 public void notifyFullscreenModeChange(boolean isFullscreenMode) {
1263 for (InCallEventListener listener : mInCallEventListeners) {
1264 listener.onFullscreenModeChanged(isFullscreenMode);
1265 }
1266 }
1267
1268 /**
1269 * For some disconnected causes, we show a dialog. This calls into the activity to show the dialog
1270 * if appropriate for the call.
1271 */
1272 private void maybeShowErrorDialogOnDisconnect(DialerCall call) {
1273 // For newly disconnected calls, we may want to show a dialog on specific error conditions
1274 if (isActivityStarted() && call.getState() == DialerCall.State.DISCONNECTED) {
1275 if (call.getAccountHandle() == null && !call.isConferenceCall()) {
1276 setDisconnectCauseForMissingAccounts(call);
1277 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001278 mInCallActivity.maybeShowErrorDialogOnDisconnect(
1279 new DisconnectMessage(mInCallActivity, call));
Eric Erfanianccca3152017-02-22 16:32:36 -08001280 }
1281 }
1282
1283 /**
1284 * When the state of in-call changes, this is the first method to get called. It determines if the
1285 * UI needs to be started or finished depending on the new state and does it.
1286 */
1287 private InCallState startOrFinishUi(InCallState newState) {
wangqicf61ca02017-08-31 15:32:55 -07001288 Trace.beginSection("InCallPresenter.startOrFinishUi");
Eric Erfanian2ca43182017-08-31 06:57:16 -07001289 LogUtil.d(
1290 "InCallPresenter.startOrFinishUi", "startOrFinishUi: " + mInCallState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -08001291
1292 // TODO: Consider a proper state machine implementation
1293
1294 // If the state isn't changing we have already done any starting/stopping of activities in
1295 // a previous pass...so lets cut out early
1296 if (newState == mInCallState) {
wangqicf61ca02017-08-31 15:32:55 -07001297 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001298 return newState;
1299 }
1300
1301 // A new Incoming call means that the user needs to be notified of the the call (since
1302 // it wasn't them who initiated it). We do this through full screen notifications and
1303 // happens indirectly through {@link StatusBarNotifier}.
1304 //
1305 // The process for incoming calls is as follows:
1306 //
1307 // 1) CallList - Announces existence of new INCOMING call
1308 // 2) InCallPresenter - Gets announcement and calculates that the new InCallState
1309 // - should be set to INCOMING.
1310 // 3) InCallPresenter - This method is called to see if we need to start or finish
1311 // the app given the new state.
1312 // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
1313 // StatusBarNotifier explicitly to issue a FullScreen Notification
1314 // that will either start the InCallActivity or show the user a
1315 // top-level notification dialog if the user is in an immersive app.
1316 // That notification can also start the InCallActivity.
1317 // 5) InCallActivity - Main activity starts up and at the end of its onCreate will
1318 // call InCallPresenter::setActivity() to let the presenter
1319 // know that start-up is complete.
1320 //
1321 // [ AND NOW YOU'RE IN THE CALL. voila! ]
1322 //
1323 // Our app is started using a fullScreen notification. We need to do this whenever
1324 // we get an incoming call. Depending on the current context of the device, either a
1325 // incoming call HUN or the actual InCallActivity will be shown.
1326 final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
1327
1328 // A dialog to show on top of the InCallUI to select a PhoneAccount
1329 final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
1330
1331 // A new outgoing call indicates that the user just now dialed a number and when that
1332 // happens we need to display the screen immediately or show an account picker dialog if
1333 // no default is set. However, if the main InCallUI is already visible, we do not want to
1334 // re-initiate the start-up animation, so we do not need to do anything here.
1335 //
1336 // It is also possible to go into an intermediate state where the call has been initiated
1337 // but Telecom has not yet returned with the details of the call (handle, gateway, etc.).
1338 // This pending outgoing state can also launch the call screen.
1339 //
1340 // This is different from the incoming call sequence because we do not need to shock the
1341 // user with a top-level notification. Just show the call UI normally.
1342 boolean callCardFragmentVisible =
1343 mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible();
1344 final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible;
1345 boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
1346
1347 // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
1348 // outgoing call process, so the UI should be brought up to show an error dialog.
1349 showCallUi |=
1350 (InCallState.PENDING_OUTGOING == mInCallState
1351 && InCallState.INCALL == newState
1352 && !isShowingInCallUi());
1353
1354 // Another exception - InCallActivity is in charge of disconnecting a call with no
1355 // valid accounts set. Bring the UI up if this is true for the current pending outgoing
1356 // call so that:
1357 // 1) The call can be disconnected correctly
1358 // 2) The UI comes up and correctly displays the error dialog.
1359 // TODO: Remove these special case conditions by making InCallPresenter a true state
1360 // machine. Telecom should also be the component responsible for disconnecting a call
1361 // with no valid accounts.
1362 showCallUi |=
1363 InCallState.PENDING_OUTGOING == newState
1364 && mainUiNotVisible
1365 && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
1366
1367 // The only time that we have an instance of mInCallActivity and it isn't started is
1368 // when it is being destroyed. In that case, lets avoid bringing up another instance of
1369 // the activity. When it is finally destroyed, we double check if we should bring it back
1370 // up so we aren't going to lose anything by avoiding a second startup here.
1371 boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
1372 if (activityIsFinishing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001373 LogUtil.i(
1374 "InCallPresenter.startOrFinishUi",
1375 "Undo the state change: " + newState + " -> " + mInCallState);
wangqicf61ca02017-08-31 15:32:55 -07001376 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001377 return mInCallState;
1378 }
1379
1380 // We're about the bring up the in-call UI for outgoing and incoming call. If we still have
1381 // dialogs up, we need to clear them out before showing in-call screen. This is necessary
1382 // to fix the bug that dialog will show up when data reaches limit even after makeing new
1383 // outgoing call after user ignore it by pressing home button.
1384 if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING)
1385 && !showCallUi
1386 && isActivityStarted()) {
1387 mInCallActivity.dismissPendingDialogs();
1388 }
1389
1390 if (showCallUi || showAccountPicker) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001391 LogUtil.i("InCallPresenter.startOrFinishUi", "Start in call UI");
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001392 showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001393 } else if (startIncomingCallSequence) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001394 LogUtil.i("InCallPresenter.startOrFinishUi", "Start Full Screen in call UI");
Eric Erfanianccca3152017-02-22 16:32:36 -08001395
wangqic8cf79e2017-10-17 09:21:00 -07001396 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001397 } else if (newState == InCallState.NO_CALLS) {
1398 // The new state is the no calls state. Tear everything down.
1399 attemptFinishActivity();
1400 attemptCleanup();
1401 }
1402
wangqicf61ca02017-08-31 15:32:55 -07001403 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001404 return newState;
1405 }
1406
1407 /**
1408 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1409 * or PhoneAccounts to select from.
1410 */
1411 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1412
1413 Bundle extras = call.getIntentExtras();
1414 // Initialize the extras bundle to avoid NPE
1415 if (extras == null) {
1416 extras = new Bundle();
1417 }
1418
1419 final List<PhoneAccountHandle> phoneAccountHandles =
1420 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1421
1422 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1423 String scheme = call.getHandle().getScheme();
1424 final String errorMsg =
1425 PhoneAccount.SCHEME_TEL.equals(scheme)
1426 ? mContext.getString(R.string.callFailed_simError)
1427 : mContext.getString(R.string.incall_error_supp_service_unknown);
1428 DisconnectCause disconnectCause =
1429 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1430 call.setDisconnectCause(disconnectCause);
1431 }
1432 }
1433
Eric Erfanianccca3152017-02-22 16:32:36 -08001434 /**
1435 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1436 * Calling classes should use this as an indication whether to interact with the
1437 * InCallPresenter or not.
1438 */
1439 public boolean isReadyForTearDown() {
1440 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1441 }
1442
1443 /**
1444 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1445 */
1446 private void attemptCleanup() {
1447 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001448 LogUtil.i("InCallPresenter.attemptCleanup", "Cleaning up");
Eric Erfanianccca3152017-02-22 16:32:36 -08001449
1450 cleanupSurfaces();
1451
1452 mIsActivityPreviouslyStarted = false;
1453 mIsChangingConfigurations = false;
1454
1455 // blow away stale contact info so that we get fresh data on
1456 // the next set of calls
1457 if (mContactInfoCache != null) {
1458 mContactInfoCache.clearCache();
1459 }
1460 mContactInfoCache = null;
1461
1462 if (mProximitySensor != null) {
1463 removeListener(mProximitySensor);
1464 mProximitySensor.tearDown();
1465 }
1466 mProximitySensor = null;
1467
1468 if (mStatusBarNotifier != null) {
1469 removeListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -07001470 EnrichedCallComponent.get(mContext)
1471 .getEnrichedCallManager()
1472 .unregisterStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -08001473 }
Eric Erfaniand8046e52017-04-06 09:41:50 -07001474
Eric Erfanianccca3152017-02-22 16:32:36 -08001475 if (mExternalCallNotifier != null && mExternalCallList != null) {
1476 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1477 }
1478 mStatusBarNotifier = null;
1479
1480 if (mCallList != null) {
1481 mCallList.removeListener(this);
1482 mCallList.removeListener(mSpamCallListListener);
1483 }
1484 mCallList = null;
1485
1486 mContext = null;
1487 mInCallActivity = null;
1488 mManageConferenceActivity = null;
1489
1490 mListeners.clear();
1491 mIncomingCallListeners.clear();
1492 mDetailsListeners.clear();
1493 mCanAddCallListeners.clear();
1494 mOrientationListeners.clear();
1495 mInCallEventListeners.clear();
1496 mInCallUiListeners.clear();
twyen8efb4952017-10-06 16:35:54 -07001497 if (!mInCallUiLocks.isEmpty()) {
1498 LogUtil.e("InCallPresenter.attemptCleanup", "held in call locks: " + mInCallUiLocks);
1499 mInCallUiLocks.clear();
1500 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001501 LogUtil.d("InCallPresenter.attemptCleanup", "finished");
Eric Erfanianccca3152017-02-22 16:32:36 -08001502 }
1503 }
1504
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001505 public void showInCall(boolean showDialpad, boolean newOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001506 LogUtil.i("InCallPresenter.showInCall", "Showing InCallActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -08001507 mContext.startActivity(
1508 InCallActivity.getIntent(
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001509 mContext, showDialpad, newOutgoingCall, false /* forFullScreen */));
Eric Erfanianccca3152017-02-22 16:32:36 -08001510 }
1511
1512 public void onServiceBind() {
1513 mServiceBound = true;
1514 }
1515
1516 public void onServiceUnbind() {
1517 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1518 mServiceBound = false;
1519 }
1520
1521 public boolean isServiceBound() {
1522 return mServiceBound;
1523 }
1524
1525 public void maybeStartRevealAnimation(Intent intent) {
1526 if (intent == null || mInCallActivity != null) {
1527 return;
1528 }
1529 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1530 if (extras == null) {
1531 // Incoming call, just show the in-call UI directly.
1532 return;
1533 }
1534
1535 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1536 // Account selection dialog will show up so don't show the animation.
1537 return;
1538 }
1539
1540 final PhoneAccountHandle accountHandle =
1541 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1542 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
Eric Erfanianccca3152017-02-22 16:32:36 -08001543
1544 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1545
1546 final Intent activityIntent =
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001547 InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001548 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1549 mContext.startActivity(activityIntent);
1550 }
1551
1552 /**
1553 * Retrieves the current in-call camera manager instance, creating if necessary.
1554 *
1555 * @return The {@link InCallCameraManager}.
1556 */
1557 public InCallCameraManager getInCallCameraManager() {
1558 synchronized (this) {
1559 if (mInCallCameraManager == null) {
1560 mInCallCameraManager = new InCallCameraManager(mContext);
1561 }
1562
1563 return mInCallCameraManager;
1564 }
1565 }
1566
1567 /**
1568 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1569 *
1570 * @param orientation The screen orientation of the device (one of: {@link
1571 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1572 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1573 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1574 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1575 */
1576 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001577 LogUtil.d(
1578 "InCallPresenter.onDeviceOrientationChange",
1579 "onDeviceOrientationChange: orientation= " + orientation);
Eric Erfanianccca3152017-02-22 16:32:36 -08001580
1581 if (mCallList != null) {
1582 mCallList.notifyCallsOfDeviceRotation(orientation);
1583 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001584 LogUtil.w("InCallPresenter.onDeviceOrientationChange", "CallList is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001585 }
1586
1587 // Notify listeners of device orientation changed.
1588 for (InCallOrientationListener listener : mOrientationListeners) {
1589 listener.onDeviceOrientationChanged(orientation);
1590 }
1591 }
1592
1593 /**
1594 * Configures the in-call UI activity so it can change orientations or not. Enables the
1595 * orientation event listener if allowOrientationChange is true, disables it if false.
1596 *
1597 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1598 * landscape. {@code false} if the in-call UI should be locked in portrait.
1599 */
1600 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1601 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001602 LogUtil.e(
1603 "InCallPresenter.setInCallAllowsOrientationChange",
1604 "InCallActivity is null. Can't set requested orientation.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001605 return;
1606 }
1607 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1608 }
1609
1610 public void enableScreenTimeout(boolean enable) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001611 LogUtil.v("InCallPresenter.enableScreenTimeout", "enableScreenTimeout: value=" + enable);
1612 mScreenTimeoutEnabled = enable;
1613 applyScreenTimeout();
1614 }
1615
1616 private void applyScreenTimeout() {
Eric Erfanianccca3152017-02-22 16:32:36 -08001617 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001618 LogUtil.e("InCallPresenter.applyScreenTimeout", "InCallActivity is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001619 return;
1620 }
1621
1622 final Window window = mInCallActivity.getWindow();
Eric Erfanian2ca43182017-08-31 06:57:16 -07001623 if (mScreenTimeoutEnabled) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001624 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1625 } else {
1626 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1627 }
1628 }
1629
1630 /**
1631 * Hides or shows the conference manager fragment.
1632 *
1633 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1634 * be hidden.
1635 */
1636 public void showConferenceCallManager(boolean show) {
1637 if (mInCallActivity != null) {
1638 mInCallActivity.showConferenceFragment(show);
1639 }
1640 if (!show && mManageConferenceActivity != null) {
1641 mManageConferenceActivity.finish();
1642 }
1643 }
1644
1645 /**
1646 * Determines if the dialpad is visible.
1647 *
1648 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1649 */
1650 public boolean isDialpadVisible() {
1651 if (mInCallActivity == null) {
1652 return false;
1653 }
1654 return mInCallActivity.isDialpadVisible();
1655 }
1656
1657 public ThemeColorManager getThemeColorManager() {
1658 return mThemeColorManager;
1659 }
1660
wangqi8d662ca2017-10-26 11:27:19 -07001661 @VisibleForTesting
1662 public void setThemeColorManager(ThemeColorManager themeColorManager) {
1663 mThemeColorManager = themeColorManager;
1664 }
1665
Eric Erfanianccca3152017-02-22 16:32:36 -08001666 /** Called when the foreground call changes. */
1667 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1668 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1669 if (mInCallActivity != null) {
1670 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1671 }
1672 }
1673
1674 public InCallActivity getActivity() {
1675 return mInCallActivity;
1676 }
1677
1678 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1679 public void setActivity(InCallActivity inCallActivity) {
1680 if (inCallActivity == null) {
1681 throw new IllegalArgumentException("registerActivity cannot be called with null");
1682 }
1683 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001684 LogUtil.w(
1685 "InCallPresenter.setActivity", "Setting a second activity before destroying the first.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001686 }
1687 updateActivity(inCallActivity);
1688 }
1689
1690 ExternalCallNotifier getExternalCallNotifier() {
1691 return mExternalCallNotifier;
1692 }
1693
1694 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1695 if (mLocalVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001696 boolean isPixel2017 = false;
1697 if (mContext != null) {
1698 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1699 }
1700 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001701 }
1702 return mLocalVideoSurfaceTexture;
1703 }
1704
1705 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1706 if (mRemoteVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001707 boolean isPixel2017 = false;
1708 if (mContext != null) {
1709 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1710 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001711 mRemoteVideoSurfaceTexture =
roldenburg12b50c62017-09-01 14:41:19 -07001712 VideoSurfaceBindings.createRemoteVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001713 }
1714 return mRemoteVideoSurfaceTexture;
1715 }
1716
1717 void cleanupSurfaces() {
1718 if (mRemoteVideoSurfaceTexture != null) {
1719 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1720 mRemoteVideoSurfaceTexture = null;
1721 }
1722 if (mLocalVideoSurfaceTexture != null) {
1723 mLocalVideoSurfaceTexture.setDoneWithSurface();
1724 mLocalVideoSurfaceTexture = null;
1725 }
1726 }
1727
yueg77cb8e52017-10-27 16:42:51 -07001728 @Override
1729 public void onAudioStateChanged(CallAudioState audioState) {
1730 if (mStatusBarNotifier != null) {
1731 mStatusBarNotifier.updateNotification();
1732 }
1733 }
1734
Eric Erfanianccca3152017-02-22 16:32:36 -08001735 /** All the main states of InCallActivity. */
1736 public enum InCallState {
1737 // InCall Screen is off and there are no calls
1738 NO_CALLS,
1739
1740 // Incoming-call screen is up
1741 INCOMING,
1742
1743 // In-call experience is showing
1744 INCALL,
1745
1746 // Waiting for user input before placing outgoing call
1747 WAITING_FOR_ACCOUNT,
1748
1749 // UI is starting up but no call has been initiated yet.
1750 // The UI is waiting for Telecom to respond.
1751 PENDING_OUTGOING,
1752
1753 // User is dialing out
1754 OUTGOING;
1755
1756 public boolean isIncoming() {
1757 return (this == INCOMING);
1758 }
1759
1760 public boolean isConnectingOrConnected() {
1761 return (this == INCOMING || this == OUTGOING || this == INCALL);
1762 }
1763 }
1764
1765 /** Interface implemented by classes that need to know about the InCall State. */
1766 public interface InCallStateListener {
1767
1768 // TODO: Enhance state to contain the call objects instead of passing CallList
1769 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1770 }
1771
1772 public interface IncomingCallListener {
1773
1774 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1775 }
1776
1777 public interface CanAddCallListener {
1778
1779 void onCanAddCallChanged(boolean canAddCall);
1780 }
1781
1782 public interface InCallDetailsListener {
1783
1784 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1785 }
1786
1787 public interface InCallOrientationListener {
1788
1789 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1790 }
1791
1792 /**
1793 * Interface implemented by classes that need to know about events which occur within the In-Call
1794 * UI. Used as a means of communicating between fragments that make up the UI.
1795 */
1796 public interface InCallEventListener {
1797
1798 void onFullscreenModeChanged(boolean isFullscreenMode);
1799 }
1800
1801 public interface InCallUiListener {
1802
1803 void onUiShowing(boolean showing);
1804 }
twyen8efb4952017-10-06 16:35:54 -07001805
1806 private class InCallUiLockImpl implements InCallUiLock {
1807 private final String tag;
1808
1809 private InCallUiLockImpl(String tag) {
1810 this.tag = tag;
1811 }
1812
1813 @MainThread
1814 @Override
1815 public void release() {
1816 Assert.isMainThread();
1817 releaseInCallUiLock(InCallUiLockImpl.this);
1818 }
1819
1820 @Override
1821 public String toString() {
1822 return "InCallUiLock[" + tag + "]";
1823 }
1824 }
1825
1826 @MainThread
1827 public InCallUiLock acquireInCallUiLock(String tag) {
1828 Assert.isMainThread();
1829 InCallUiLock lock = new InCallUiLockImpl(tag);
1830 mInCallUiLocks.add(lock);
1831 return lock;
1832 }
1833
1834 @MainThread
1835 private void releaseInCallUiLock(InCallUiLock lock) {
1836 Assert.isMainThread();
1837 LogUtil.i("InCallPresenter.releaseInCallUiLock", "releasing %s", lock);
1838 mInCallUiLocks.remove(lock);
1839 if (mInCallUiLocks.isEmpty()) {
1840 LogUtil.i("InCallPresenter.releaseInCallUiLock", "all locks released");
1841 if (mInCallState == InCallState.NO_CALLS) {
1842 LogUtil.i("InCallPresenter.releaseInCallUiLock", "no more calls, finishing UI");
1843 attemptFinishActivity();
1844 attemptCleanup();
1845 }
1846 }
1847 }
1848
1849 @MainThread
1850 public boolean isInCallUiLocked() {
1851 Assert.isMainThread();
1852 if (mInCallUiLocks.isEmpty()) {
1853 return false;
1854 }
1855 for (InCallUiLock lock : mInCallUiLocks) {
1856 LogUtil.i("InCallPresenter.isInCallUiLocked", "still locked by %s", lock);
1857 }
1858 return true;
1859 }
1860
1861 private final Set<InCallUiLock> mInCallUiLocks = new ArraySet<>();
Eric Erfanianccca3152017-02-22 16:32:36 -08001862}