blob: d0e3fb47730ea804e29fa1fb106e60d69e7267e7 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 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
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Wale Ogunwale59507092018-10-29 09:00:30 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto
86 .PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
89 .MODE;
90import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
91 .PACKAGE;
92import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
93import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
94import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
95import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
96import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
97import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
98import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
113import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
114import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
115import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
116import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700117import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
118import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
119import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
120import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
122import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700123import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
124import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
wilsonshihe7903ea2018-09-26 16:17:59 +0800125import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
126import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
127import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700128
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.annotation.Nullable;
132import android.annotation.UserIdInt;
133import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700134import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700135import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.ActivityOptions;
137import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700138import android.app.ActivityThread;
139import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700141import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700142import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700143import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.IApplicationThread;
145import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Evan Rosky4505b352018-09-06 11:20:40 -0700247import com.android.server.AppOpsService;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800249import com.android.server.DisplayThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700277import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700279import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700280import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400282import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700285import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Map;
287import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288
289/**
290 * System service for managing activities and their containers (task, stacks, displays,... ).
291 *
292 * {@hide}
293 */
294public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700295 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700297 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
298 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
299 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
300 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
301 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700302 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700307 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308
Wale Ogunwale98875612018-10-12 07:53:02 -0700309 /** Used to indicate that an app transition should be animated. */
310 static final boolean ANIMATE = true;
311
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700312 /** Hardware-reported OpenGLES version. */
313 final int GL_ES_VERSION;
314
Wale Ogunwale31913b52018-10-13 08:29:31 -0700315 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
316 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
317 public static final String DUMP_LASTANR_CMD = "lastanr" ;
318 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
319 public static final String DUMP_STARTER_CMD = "starter" ;
320 public static final String DUMP_CONTAINERS_CMD = "containers" ;
321 public static final String DUMP_RECENTS_CMD = "recents" ;
322 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
323
Wale Ogunwale64258362018-10-16 15:13:37 -0700324 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
325 public static final int RELAUNCH_REASON_NONE = 0;
326 /** This activity is being relaunched due to windowing mode change. */
327 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
328 /** This activity is being relaunched due to a free-resize operation. */
329 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
330
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700331 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700332
Wale Ogunwalef6733932018-06-27 05:14:34 -0700333 /**
334 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
335 * change at runtime. Use mContext for non-UI purposes.
336 */
337 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700338 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700339 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700342 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700343 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800344 @VisibleForTesting
345 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 PowerManagerInternal mPowerManagerInternal;
347 private UsageStatsManagerInternal mUsageStatsInternal;
348
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700349 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 IntentFirewall mIntentFirewall;
351
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700352 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800353 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700354 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700356 private UserManagerService mUserManager;
357 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700358 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700359 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
360 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700361 /** All processes currently running that might have a window organized by name. */
362 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700363 /** All processes we currently have running mapped by pid */
364 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700365 /** This is the process holding what we currently consider to be the "home" activity. */
366 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700367 /** The currently running heavy-weight process, if any. */
368 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700369 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700370 /**
371 * This is the process holding the activity the user last visited that is in a different process
372 * from the one they are currently in.
373 */
374 WindowProcessController mPreviousProcess;
375 /** The time at which the previous process was last visible. */
376 long mPreviousProcessVisibleTime;
377
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 /** List of intents that were used to start the most recent tasks. */
379 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700380 /** State of external calls telling us if the device is awake or asleep. */
381 private boolean mKeyguardShown = false;
382
383 // Wrapper around VoiceInteractionServiceManager
384 private AssistUtils mAssistUtils;
385
386 // VoiceInteraction session ID that changes for each new request except when
387 // being called for multi-window assist in a single session.
388 private int mViSessionId = 1000;
389
390 // How long to wait in getAssistContextExtras for the activity and foreground services
391 // to respond with the result.
392 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
393
394 // How long top wait when going through the modern assist (which doesn't need to block
395 // on getting this result before starting to launch its UI).
396 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
397
398 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
399 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
400
Alison Cichowlas3e340502018-08-07 17:15:01 -0400401 // Permission tokens are used to temporarily granted a trusted app the ability to call
402 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
403 // showing any appropriate error messages to the user.
404 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
405 10 * MINUTE_IN_MILLIS;
406
407 // How long before the service actually expires a token. This is slightly longer than
408 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
409 // expiration exception.
410 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
411 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
412
413 // How long the service will remember expired tokens, for the purpose of providing error
414 // messaging when a client uses an expired token.
415 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
416 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
417
418 // Activity tokens of system activities that are delegating their call to
419 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
420 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
421
422 // Permission tokens that have expired, but we remember for error reporting.
423 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
424
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700425 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
426
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700427 // Keeps track of the active voice interaction service component, notified from
428 // VoiceInteractionManagerService
429 ComponentName mActiveVoiceInteractionServiceComponent;
430
Wale Ogunwalee2172292018-10-25 10:11:10 -0700431 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700432 KeyguardController mKeyguardController;
433 private final ClientLifecycleManager mLifecycleManager;
434 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700435 /** The controller for all operations related to locktask. */
436 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700437 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700438
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700439 boolean mSuppressResizeConfigChanges;
440
441 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
442 new UpdateConfigurationResult();
443
444 static final class UpdateConfigurationResult {
445 // Configuration changes that were updated.
446 int changes;
447 // If the activity was relaunched to match the new configuration.
448 boolean activityRelaunched;
449
450 void reset() {
451 changes = 0;
452 activityRelaunched = false;
453 }
454 }
455
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700456 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700457 private int mConfigurationSeq;
458 // To cache the list of supported system locales
459 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700460
461 /**
462 * Temp object used when global and/or display override configuration is updated. It is also
463 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
464 * anyone...
465 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700466 private Configuration mTempConfig = new Configuration();
467
Wale Ogunwalef6733932018-06-27 05:14:34 -0700468 /** Temporary to avoid allocations. */
469 final StringBuilder mStringBuilder = new StringBuilder(256);
470
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700471 // Amount of time after a call to stopAppSwitches() during which we will
472 // prevent further untrusted switches from happening.
473 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
474
475 /**
476 * The time at which we will allow normal application switches again,
477 * after a call to {@link #stopAppSwitches()}.
478 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700479 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 /**
481 * This is set to true after the first switch after mAppSwitchesAllowedTime
482 * is set; any switches after that will clear the time.
483 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700484 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485
486 IActivityController mController = null;
487 boolean mControllerIsAMonkey = false;
488
Wale Ogunwale214f3482018-10-04 11:00:47 -0700489 final int mFactoryTest;
490
491 /** Used to control how we initialize the service. */
492 ComponentName mTopComponent;
493 String mTopAction = Intent.ACTION_MAIN;
494 String mTopData;
495
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800496 /** Profiling app information. */
497 String mProfileApp = null;
498 WindowProcessController mProfileProc = null;
499 ProfilerInfo mProfilerInfo = null;
500
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700502 * Dump of the activity state at the time of the last ANR. Cleared after
503 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
504 */
505 String mLastANRState;
506
507 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 * Used to retain an update lock when the foreground activity is in
509 * immersive mode.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
513 /**
514 * Packages that are being allowed to perform unrestricted app switches. Mapping is
515 * User -> Type -> uid.
516 */
517 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
518
519 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700520 private int mThumbnailWidth;
521 private int mThumbnailHeight;
522 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523
524 /**
525 * Flag that indicates if multi-window is enabled.
526 *
527 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
528 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
529 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
530 * At least one of the forms of multi-window must be enabled in order for this flag to be
531 * initialized to 'true'.
532 *
533 * @see #mSupportsSplitScreenMultiWindow
534 * @see #mSupportsFreeformWindowManagement
535 * @see #mSupportsPictureInPicture
536 * @see #mSupportsMultiDisplay
537 */
538 boolean mSupportsMultiWindow;
539 boolean mSupportsSplitScreenMultiWindow;
540 boolean mSupportsFreeformWindowManagement;
541 boolean mSupportsPictureInPicture;
542 boolean mSupportsMultiDisplay;
543 boolean mForceResizableActivities;
544
545 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
546
547 // VR Vr2d Display Id.
548 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700549
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 /**
551 * Set while we are wanting to sleep, to prevent any
552 * activities from being started/resumed.
553 *
554 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
555 *
556 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
557 * while in the sleep state until there is a pending transition out of sleep, in which case
558 * mSleeping is set to false, and remains false while awake.
559 *
560 * Whether mSleeping can quickly toggled between true/false without the device actually
561 * display changing states is undefined.
562 */
563 private boolean mSleeping = false;
564
565 /**
566 * The process state used for processes that are running the top activities.
567 * This changes between TOP and TOP_SLEEPING to following mSleeping.
568 */
569 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
570
571 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
572 // automatically. Important for devices without direct input devices.
573 private boolean mShowDialogs = true;
574
575 /** Set if we are shutting down the system, similar to sleeping. */
576 boolean mShuttingDown = false;
577
578 /**
579 * We want to hold a wake lock while running a voice interaction session, since
580 * this may happen with the screen off and we need to keep the CPU running to
581 * be able to continue to interact with the user.
582 */
583 PowerManager.WakeLock mVoiceWakeLock;
584
585 /**
586 * Set while we are running a voice interaction. This overrides sleeping while it is active.
587 */
588 IVoiceInteractionSession mRunningVoice;
589
590 /**
591 * The last resumed activity. This is identical to the current resumed activity most
592 * of the time but could be different when we're pausing one activity before we resume
593 * another activity.
594 */
595 ActivityRecord mLastResumedActivity;
596
597 /**
598 * The activity that is currently being traced as the active resumed activity.
599 *
600 * @see #updateResumedAppTrace
601 */
602 private @Nullable ActivityRecord mTracedResumedActivity;
603
604 /** If non-null, we are tracking the time the user spends in the currently focused app. */
605 AppTimeTracker mCurAppTimeTracker;
606
Wale Ogunwale008163e2018-07-23 23:11:08 -0700607 private AppWarnings mAppWarnings;
608
Wale Ogunwale53783742018-09-16 10:21:51 -0700609 /**
610 * Packages that the user has asked to have run in screen size
611 * compatibility mode instead of filling the screen.
612 */
613 CompatModePackages mCompatModePackages;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 private FontScaleSettingObserver mFontScaleSettingObserver;
616
617 private final class FontScaleSettingObserver extends ContentObserver {
618 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
619 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
620
621 public FontScaleSettingObserver() {
622 super(mH);
623 final ContentResolver resolver = mContext.getContentResolver();
624 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
625 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
626 UserHandle.USER_ALL);
627 }
628
629 @Override
630 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
631 if (mFontScaleUri.equals(uri)) {
632 updateFontScaleIfNeeded(userId);
633 } else if (mHideErrorDialogsUri.equals(uri)) {
634 synchronized (mGlobalLock) {
635 updateShouldShowDialogsLocked(getGlobalConfiguration());
636 }
637 }
638 }
639 }
640
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700641 ActivityTaskManagerService(Context context) {
642 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700643 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700644 mSystemThread = ActivityThread.currentActivityThread();
645 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700646 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800647 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700648 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700649 }
650
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700651 public void onSystemReady() {
652 synchronized (mGlobalLock) {
653 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
654 PackageManager.FEATURE_CANT_SAVE_STATE);
655 mAssistUtils = new AssistUtils(mContext);
656 mVrController.onSystemReady();
657 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700658 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700659 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700660 }
661
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700662 public void onInitPowerManagement() {
663 synchronized (mGlobalLock) {
664 mStackSupervisor.initPowerManagement();
665 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
666 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
667 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
668 mVoiceWakeLock.setReferenceCounted(false);
669 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 mFontScaleSettingObserver = new FontScaleSettingObserver();
674 }
675
Wale Ogunwale59507092018-10-29 09:00:30 -0700676 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700677 final boolean freeformWindowManagement =
678 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
679 || Settings.Global.getInt(
680 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
681
682 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
683 final boolean supportsPictureInPicture = supportsMultiWindow &&
684 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
685 final boolean supportsSplitScreenMultiWindow =
686 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
687 final boolean supportsMultiDisplay = mContext.getPackageManager()
688 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700689 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
690 final boolean forceResizable = Settings.Global.getInt(
691 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700692 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700693
694 // Transfer any global setting for forcing RTL layout, into a System Property
695 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
696
697 final Configuration configuration = new Configuration();
698 Settings.System.getConfiguration(resolver, configuration);
699 if (forceRtl) {
700 // This will take care of setting the correct layout direction flags
701 configuration.setLayoutDirection(configuration.locale);
702 }
703
704 synchronized (mGlobalLock) {
705 mForceResizableActivities = forceResizable;
706 final boolean multiWindowFormEnabled = freeformWindowManagement
707 || supportsSplitScreenMultiWindow
708 || supportsPictureInPicture
709 || supportsMultiDisplay;
710 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
711 mSupportsMultiWindow = true;
712 mSupportsFreeformWindowManagement = freeformWindowManagement;
713 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
714 mSupportsPictureInPicture = supportsPictureInPicture;
715 mSupportsMultiDisplay = supportsMultiDisplay;
716 } else {
717 mSupportsMultiWindow = false;
718 mSupportsFreeformWindowManagement = false;
719 mSupportsSplitScreenMultiWindow = false;
720 mSupportsPictureInPicture = false;
721 mSupportsMultiDisplay = false;
722 }
723 mWindowManager.setForceResizableTasks(mForceResizableActivities);
724 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700725 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
726 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700727 // This happens before any activities are started, so we can change global configuration
728 // in-place.
729 updateConfigurationLocked(configuration, null, true);
730 final Configuration globalConfig = getGlobalConfiguration();
731 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
732
733 // Load resources only after the current configuration has been set.
734 final Resources res = mContext.getResources();
735 mThumbnailWidth = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_width);
737 mThumbnailHeight = res.getDimensionPixelSize(
738 com.android.internal.R.dimen.thumbnail_height);
739
740 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
741 mFullscreenThumbnailScale = (float) res
742 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
743 (float) globalConfig.screenWidthDp;
744 } else {
745 mFullscreenThumbnailScale = res.getFraction(
746 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
747 }
748 }
749 }
750
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800751 public WindowManagerGlobalLock getGlobalLock() {
752 return mGlobalLock;
753 }
754
755 public void setActivityManagerService(IntentFirewall intentFirewall,
756 PendingIntentController intentController) {
757 mH = new H();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700758 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700759 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700760 final File systemDir = SystemServiceManager.ensureSystemDir();
761 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
762 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700763 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700764
765 mTempConfig.setToDefaults();
766 mTempConfig.setLocales(LocaleList.getDefault());
767 mConfigurationSeq = mTempConfig.seq = 1;
768 mStackSupervisor = createStackSupervisor();
769 mStackSupervisor.onConfigurationChanged(mTempConfig);
770
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700771 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700773 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700775 mRecentTasks = createRecentTasks();
776 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700777 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700778 mKeyguardController = mStackSupervisor.getKeyguardController();
779 }
780
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700781 public void onActivityManagerInternalAdded() {
782 synchronized (mGlobalLock) {
783 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
784 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
785 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700786 }
787
Yunfan Chen75157d72018-07-27 14:47:21 +0900788 int increaseConfigurationSeqLocked() {
789 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
790 return mConfigurationSeq;
791 }
792
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700793 protected ActivityStackSupervisor createStackSupervisor() {
794 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
795 supervisor.initialize();
796 return supervisor;
797 }
798
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700799 public void setWindowManager(WindowManagerService wm) {
800 synchronized (mGlobalLock) {
801 mWindowManager = wm;
802 mLockTaskController.setWindowManager(wm);
803 mStackSupervisor.setWindowManager(wm);
804 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700805 }
806
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700807 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
808 synchronized (mGlobalLock) {
809 mUsageStatsInternal = usageStatsManager;
810 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 }
812
Wale Ogunwalef6733932018-06-27 05:14:34 -0700813 UserManagerService getUserManager() {
814 if (mUserManager == null) {
815 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
816 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
817 }
818 return mUserManager;
819 }
820
821 AppOpsService getAppOpsService() {
822 if (mAppOpsService == null) {
823 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
824 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
825 }
826 return mAppOpsService;
827 }
828
829 boolean hasUserRestriction(String restriction, int userId) {
830 return getUserManager().hasUserRestriction(restriction, userId);
831 }
832
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700833 protected RecentTasks createRecentTasks() {
834 return new RecentTasks(this, mStackSupervisor);
835 }
836
837 RecentTasks getRecentTasks() {
838 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700839 }
840
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 ClientLifecycleManager getLifecycleManager() {
842 return mLifecycleManager;
843 }
844
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700845 ActivityStartController getActivityStartController() {
846 return mActivityStartController;
847 }
848
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700849 TaskChangeNotificationController getTaskChangeNotificationController() {
850 return mTaskChangeNotificationController;
851 }
852
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700853 LockTaskController getLockTaskController() {
854 return mLockTaskController;
855 }
856
Yunfan Chen75157d72018-07-27 14:47:21 +0900857 /**
858 * Return the global configuration used by the process corresponding to the input pid. This is
859 * usually the global configuration with some overrides specific to that process.
860 */
861 Configuration getGlobalConfigurationForCallingPid() {
862 final int pid = Binder.getCallingPid();
863 if (pid == MY_PID || pid < 0) {
864 return getGlobalConfiguration();
865 }
866 synchronized (mGlobalLock) {
867 final WindowProcessController app = mPidMap.get(pid);
868 return app != null ? app.getConfiguration() : getGlobalConfiguration();
869 }
870 }
871
872 /**
873 * Return the device configuration info used by the process corresponding to the input pid.
874 * The value is consistent with the global configuration for the process.
875 */
876 @Override
877 public ConfigurationInfo getDeviceConfigurationInfo() {
878 ConfigurationInfo config = new ConfigurationInfo();
879 synchronized (mGlobalLock) {
880 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
881 config.reqTouchScreen = globalConfig.touchscreen;
882 config.reqKeyboardType = globalConfig.keyboard;
883 config.reqNavigation = globalConfig.navigation;
884 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
885 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
886 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
887 }
888 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
889 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
890 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
891 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700892 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900893 }
894 return config;
895 }
896
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700897 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700898 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700899 }
900
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700901 public static final class Lifecycle extends SystemService {
902 private final ActivityTaskManagerService mService;
903
904 public Lifecycle(Context context) {
905 super(context);
906 mService = new ActivityTaskManagerService(context);
907 }
908
909 @Override
910 public void onStart() {
911 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700912 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700913 }
914
Garfield Tan891146c2018-10-09 12:14:00 -0700915 @Override
916 public void onUnlockUser(int userId) {
917 synchronized (mService.getGlobalLock()) {
918 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
919 }
920 }
921
922 @Override
923 public void onCleanupUser(int userId) {
924 synchronized (mService.getGlobalLock()) {
925 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
926 }
927 }
928
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700929 public ActivityTaskManagerService getService() {
930 return mService;
931 }
932 }
933
934 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700935 public final int startActivity(IApplicationThread caller, String callingPackage,
936 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
937 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
938 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
939 resultWho, requestCode, startFlags, profilerInfo, bOptions,
940 UserHandle.getCallingUserId());
941 }
942
943 @Override
944 public final int startActivities(IApplicationThread caller, String callingPackage,
945 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
946 int userId) {
947 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700948 enforceNotIsolatedCaller(reason);
949 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700950 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700951 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100952 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
953 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700954 }
955
956 @Override
957 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
958 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
959 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
960 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
961 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
962 true /*validateIncomingUser*/);
963 }
964
965 int startActivityAsUser(IApplicationThread caller, String callingPackage,
966 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
967 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
968 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700969 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700970
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700971 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700972 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
973
974 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700975 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700976 .setCaller(caller)
977 .setCallingPackage(callingPackage)
978 .setResolvedType(resolvedType)
979 .setResultTo(resultTo)
980 .setResultWho(resultWho)
981 .setRequestCode(requestCode)
982 .setStartFlags(startFlags)
983 .setProfilerInfo(profilerInfo)
984 .setActivityOptions(bOptions)
985 .setMayWait(userId)
986 .execute();
987
988 }
989
990 @Override
991 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
992 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700993 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
994 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700995 // Refuse possible leaked file descriptors
996 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
997 throw new IllegalArgumentException("File descriptors passed in Intent");
998 }
999
1000 if (!(target instanceof PendingIntentRecord)) {
1001 throw new IllegalArgumentException("Bad PendingIntent object");
1002 }
1003
1004 PendingIntentRecord pir = (PendingIntentRecord)target;
1005
1006 synchronized (mGlobalLock) {
1007 // If this is coming from the currently resumed activity, it is
1008 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001009 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001010 if (stack.mResumedActivity != null &&
1011 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001012 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 }
1014 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 }
1018
1019 @Override
1020 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1021 Bundle bOptions) {
1022 // Refuse possible leaked file descriptors
1023 if (intent != null && intent.hasFileDescriptors()) {
1024 throw new IllegalArgumentException("File descriptors passed in Intent");
1025 }
1026 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1027
1028 synchronized (mGlobalLock) {
1029 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1030 if (r == null) {
1031 SafeActivityOptions.abort(options);
1032 return false;
1033 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001034 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 // The caller is not running... d'oh!
1036 SafeActivityOptions.abort(options);
1037 return false;
1038 }
1039 intent = new Intent(intent);
1040 // The caller is not allowed to change the data.
1041 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1042 // And we are resetting to find the next component...
1043 intent.setComponent(null);
1044
1045 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1046
1047 ActivityInfo aInfo = null;
1048 try {
1049 List<ResolveInfo> resolves =
1050 AppGlobals.getPackageManager().queryIntentActivities(
1051 intent, r.resolvedType,
1052 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1053 UserHandle.getCallingUserId()).getList();
1054
1055 // Look for the original activity in the list...
1056 final int N = resolves != null ? resolves.size() : 0;
1057 for (int i=0; i<N; i++) {
1058 ResolveInfo rInfo = resolves.get(i);
1059 if (rInfo.activityInfo.packageName.equals(r.packageName)
1060 && rInfo.activityInfo.name.equals(r.info.name)) {
1061 // We found the current one... the next matching is
1062 // after it.
1063 i++;
1064 if (i<N) {
1065 aInfo = resolves.get(i).activityInfo;
1066 }
1067 if (debug) {
1068 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1069 + "/" + r.info.name);
1070 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1071 ? "null" : aInfo.packageName + "/" + aInfo.name));
1072 }
1073 break;
1074 }
1075 }
1076 } catch (RemoteException e) {
1077 }
1078
1079 if (aInfo == null) {
1080 // Nobody who is next!
1081 SafeActivityOptions.abort(options);
1082 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1083 return false;
1084 }
1085
1086 intent.setComponent(new ComponentName(
1087 aInfo.applicationInfo.packageName, aInfo.name));
1088 intent.setFlags(intent.getFlags()&~(
1089 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1090 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1091 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1092 FLAG_ACTIVITY_NEW_TASK));
1093
1094 // Okay now we need to start the new activity, replacing the currently running activity.
1095 // This is a little tricky because we want to start the new one as if the current one is
1096 // finished, but not finish the current one first so that there is no flicker.
1097 // And thus...
1098 final boolean wasFinishing = r.finishing;
1099 r.finishing = true;
1100
1101 // Propagate reply information over to the new activity.
1102 final ActivityRecord resultTo = r.resultTo;
1103 final String resultWho = r.resultWho;
1104 final int requestCode = r.requestCode;
1105 r.resultTo = null;
1106 if (resultTo != null) {
1107 resultTo.removeResultsLocked(r, resultWho, requestCode);
1108 }
1109
1110 final long origId = Binder.clearCallingIdentity();
1111 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001112 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001114 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001115 .setResolvedType(r.resolvedType)
1116 .setActivityInfo(aInfo)
1117 .setResultTo(resultTo != null ? resultTo.appToken : null)
1118 .setResultWho(resultWho)
1119 .setRequestCode(requestCode)
1120 .setCallingPid(-1)
1121 .setCallingUid(r.launchedFromUid)
1122 .setCallingPackage(r.launchedFromPackage)
1123 .setRealCallingPid(-1)
1124 .setRealCallingUid(r.launchedFromUid)
1125 .setActivityOptions(options)
1126 .execute();
1127 Binder.restoreCallingIdentity(origId);
1128
1129 r.finishing = wasFinishing;
1130 if (res != ActivityManager.START_SUCCESS) {
1131 return false;
1132 }
1133 return true;
1134 }
1135 }
1136
1137 @Override
1138 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1139 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1140 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1141 final WaitResult res = new WaitResult();
1142 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001143 enforceNotIsolatedCaller("startActivityAndWait");
1144 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1145 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001146 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001147 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001148 .setCaller(caller)
1149 .setCallingPackage(callingPackage)
1150 .setResolvedType(resolvedType)
1151 .setResultTo(resultTo)
1152 .setResultWho(resultWho)
1153 .setRequestCode(requestCode)
1154 .setStartFlags(startFlags)
1155 .setActivityOptions(bOptions)
1156 .setMayWait(userId)
1157 .setProfilerInfo(profilerInfo)
1158 .setWaitResult(res)
1159 .execute();
1160 }
1161 return res;
1162 }
1163
1164 @Override
1165 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1166 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1167 int startFlags, Configuration config, Bundle bOptions, int userId) {
1168 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001169 enforceNotIsolatedCaller("startActivityWithConfig");
1170 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1171 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001172 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001173 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001174 .setCaller(caller)
1175 .setCallingPackage(callingPackage)
1176 .setResolvedType(resolvedType)
1177 .setResultTo(resultTo)
1178 .setResultWho(resultWho)
1179 .setRequestCode(requestCode)
1180 .setStartFlags(startFlags)
1181 .setGlobalConfiguration(config)
1182 .setActivityOptions(bOptions)
1183 .setMayWait(userId)
1184 .execute();
1185 }
1186 }
1187
Alison Cichowlas3e340502018-08-07 17:15:01 -04001188
1189 @Override
1190 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1191 int callingUid = Binder.getCallingUid();
1192 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1193 throw new SecurityException("Only the system process can request a permission token, "
1194 + "received request from uid: " + callingUid);
1195 }
1196 IBinder permissionToken = new Binder();
1197 synchronized (mGlobalLock) {
1198 mStartActivitySources.put(permissionToken, delegatorToken);
1199 }
1200
1201 Message expireMsg = PooledLambda.obtainMessage(
1202 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1203 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1204
1205 Message forgetMsg = PooledLambda.obtainMessage(
1206 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1207 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1208
1209 return permissionToken;
1210 }
1211
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 @Override
1213 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1214 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001215 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1216 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001217 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001218 // permission grants) as any app that may launch one of your own activities. So we only
1219 // allow this in two cases:
1220 // 1) The caller is an activity that is part of the core framework, and then only when it
1221 // is running as the system.
1222 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1223 // can only be requested by a system activity, which may then delegate this call to
1224 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 final ActivityRecord sourceRecord;
1226 final int targetUid;
1227 final String targetPackage;
1228 final boolean isResolver;
1229 synchronized (mGlobalLock) {
1230 if (resultTo == null) {
1231 throw new SecurityException("Must be called from an activity");
1232 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001233 final IBinder sourceToken;
1234 if (permissionToken != null) {
1235 // To even attempt to use a permissionToken, an app must also have this signature
1236 // permission.
1237 mAmInternal.enforceCallingPermission(
1238 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1239 "startActivityAsCaller");
1240 // If called with a permissionToken, we want the sourceRecord from the delegator
1241 // activity that requested this token.
1242 sourceToken = mStartActivitySources.remove(permissionToken);
1243 if (sourceToken == null) {
1244 // Invalid permissionToken, check if it recently expired.
1245 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1246 throw new SecurityException("Called with expired permission token: "
1247 + permissionToken);
1248 } else {
1249 throw new SecurityException("Called with invalid permission token: "
1250 + permissionToken);
1251 }
1252 }
1253 } else {
1254 // This method was called directly by the source.
1255 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001256 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001257
1258 sourceRecord = mStackSupervisor.isInAnyStackLocked(sourceToken);
1259 if (sourceRecord == null) {
1260 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001261 }
1262 if (sourceRecord.app == null) {
1263 throw new SecurityException("Called without a process attached to activity");
1264 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001265
1266 // Whether called directly or from a delegate, the source activity must be from the
1267 // android package.
1268 if (!sourceRecord.info.packageName.equals("android")) {
1269 throw new SecurityException("Must be called from an activity that is "
1270 + "declared in the android package");
1271 }
1272
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001273 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 // This is still okay, as long as this activity is running under the
1275 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001276 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001277 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001278 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 + " must be system uid or original calling uid "
1280 + sourceRecord.launchedFromUid);
1281 }
1282 }
1283 if (ignoreTargetSecurity) {
1284 if (intent.getComponent() == null) {
1285 throw new SecurityException(
1286 "Component must be specified with ignoreTargetSecurity");
1287 }
1288 if (intent.getSelector() != null) {
1289 throw new SecurityException(
1290 "Selector not allowed with ignoreTargetSecurity");
1291 }
1292 }
1293 targetUid = sourceRecord.launchedFromUid;
1294 targetPackage = sourceRecord.launchedFromPackage;
1295 isResolver = sourceRecord.isResolverOrChildActivity();
1296 }
1297
1298 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001299 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001300 }
1301
1302 // TODO: Switch to user app stacks here.
1303 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001304 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001305 .setCallingUid(targetUid)
1306 .setCallingPackage(targetPackage)
1307 .setResolvedType(resolvedType)
1308 .setResultTo(resultTo)
1309 .setResultWho(resultWho)
1310 .setRequestCode(requestCode)
1311 .setStartFlags(startFlags)
1312 .setActivityOptions(bOptions)
1313 .setMayWait(userId)
1314 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1315 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1316 .execute();
1317 } catch (SecurityException e) {
1318 // XXX need to figure out how to propagate to original app.
1319 // A SecurityException here is generally actually a fault of the original
1320 // calling activity (such as a fairly granting permissions), so propagate it
1321 // back to them.
1322 /*
1323 StringBuilder msg = new StringBuilder();
1324 msg.append("While launching");
1325 msg.append(intent.toString());
1326 msg.append(": ");
1327 msg.append(e.getMessage());
1328 */
1329 throw e;
1330 }
1331 }
1332
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001333 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1334 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1335 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1336 }
1337
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 @Override
1339 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1340 Intent intent, String resolvedType, IVoiceInteractionSession session,
1341 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1342 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001343 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 if (session == null || interactor == null) {
1345 throw new NullPointerException("null session or interactor");
1346 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001347 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001349 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 .setCallingUid(callingUid)
1351 .setCallingPackage(callingPackage)
1352 .setResolvedType(resolvedType)
1353 .setVoiceSession(session)
1354 .setVoiceInteractor(interactor)
1355 .setStartFlags(startFlags)
1356 .setProfilerInfo(profilerInfo)
1357 .setActivityOptions(bOptions)
1358 .setMayWait(userId)
1359 .execute();
1360 }
1361
1362 @Override
1363 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1364 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001365 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1366 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001368 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 .setCallingUid(callingUid)
1370 .setCallingPackage(callingPackage)
1371 .setResolvedType(resolvedType)
1372 .setActivityOptions(bOptions)
1373 .setMayWait(userId)
1374 .execute();
1375 }
1376
1377 @Override
1378 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1379 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001380 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 final int callingPid = Binder.getCallingPid();
1382 final long origId = Binder.clearCallingIdentity();
1383 try {
1384 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001385 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1386 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387
1388 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001389 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1390 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1392 recentsUid, assistDataReceiver);
1393 }
1394 } finally {
1395 Binder.restoreCallingIdentity(origId);
1396 }
1397 }
1398
1399 @Override
1400 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001401 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 "startActivityFromRecents()");
1403
1404 final int callingPid = Binder.getCallingPid();
1405 final int callingUid = Binder.getCallingUid();
1406 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1407 final long origId = Binder.clearCallingIdentity();
1408 try {
1409 synchronized (mGlobalLock) {
1410 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1411 safeOptions);
1412 }
1413 } finally {
1414 Binder.restoreCallingIdentity(origId);
1415 }
1416 }
1417
1418 /**
1419 * This is the internal entry point for handling Activity.finish().
1420 *
1421 * @param token The Binder token referencing the Activity we want to finish.
1422 * @param resultCode Result code, if any, from this Activity.
1423 * @param resultData Result data (Intent), if any, from this Activity.
1424 * @param finishTask Whether to finish the task associated with this Activity.
1425 *
1426 * @return Returns true if the activity successfully finished, or false if it is still running.
1427 */
1428 @Override
1429 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1430 int finishTask) {
1431 // Refuse possible leaked file descriptors
1432 if (resultData != null && resultData.hasFileDescriptors()) {
1433 throw new IllegalArgumentException("File descriptors passed in Intent");
1434 }
1435
1436 synchronized (mGlobalLock) {
1437 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1438 if (r == null) {
1439 return true;
1440 }
1441 // Keep track of the root activity of the task before we finish it
1442 TaskRecord tr = r.getTask();
1443 ActivityRecord rootR = tr.getRootActivity();
1444 if (rootR == null) {
1445 Slog.w(TAG, "Finishing task with all activities already finished");
1446 }
1447 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1448 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001449 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450 return false;
1451 }
1452
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1454 // We should consolidate.
1455 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 // Find the first activity that is not finishing.
1457 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1458 if (next != null) {
1459 // ask watcher if this is allowed
1460 boolean resumeOK = true;
1461 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001462 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001464 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 Watchdog.getInstance().setActivityController(null);
1466 }
1467
1468 if (!resumeOK) {
1469 Slog.i(TAG, "Not finishing activity because controller resumed");
1470 return false;
1471 }
1472 }
1473 }
1474 final long origId = Binder.clearCallingIdentity();
1475 try {
1476 boolean res;
1477 final boolean finishWithRootActivity =
1478 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1479 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1480 || (finishWithRootActivity && r == rootR)) {
1481 // If requested, remove the task that is associated to this activity only if it
1482 // was the root activity in the task. The result code and data is ignored
1483 // because we don't support returning them across task boundaries. Also, to
1484 // keep backwards compatibility we remove the task from recents when finishing
1485 // task with root activity.
1486 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1487 finishWithRootActivity, "finish-activity");
1488 if (!res) {
1489 Slog.i(TAG, "Removing task failed to finish activity");
1490 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001491 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001492 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 } else {
1494 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1495 resultData, "app-request", true);
1496 if (!res) {
1497 Slog.i(TAG, "Failed to finish by app-request");
1498 }
1499 }
1500 return res;
1501 } finally {
1502 Binder.restoreCallingIdentity(origId);
1503 }
1504 }
1505 }
1506
1507 @Override
1508 public boolean finishActivityAffinity(IBinder token) {
1509 synchronized (mGlobalLock) {
1510 final long origId = Binder.clearCallingIdentity();
1511 try {
1512 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1513 if (r == null) {
1514 return false;
1515 }
1516
1517 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1518 // can finish.
1519 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001520 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 return false;
1522 }
1523 return task.getStack().finishActivityAffinityLocked(r);
1524 } finally {
1525 Binder.restoreCallingIdentity(origId);
1526 }
1527 }
1528 }
1529
1530 @Override
1531 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1532 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001533 try {
1534 WindowProcessController proc = null;
1535 synchronized (mGlobalLock) {
1536 ActivityStack stack = ActivityRecord.getStackLocked(token);
1537 if (stack == null) {
1538 return;
1539 }
1540 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1541 false /* fromTimeout */, false /* processPausingActivities */, config);
1542 if (r != null) {
1543 proc = r.app;
1544 }
1545 if (stopProfiling && proc != null) {
1546 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 }
1548 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001549 } finally {
1550 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 }
1553
1554 @Override
1555 public final void activityResumed(IBinder token) {
1556 final long origId = Binder.clearCallingIdentity();
1557 synchronized (mGlobalLock) {
1558 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001559 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 }
1561 Binder.restoreCallingIdentity(origId);
1562 }
1563
1564 @Override
1565 public final void activityPaused(IBinder token) {
1566 final long origId = Binder.clearCallingIdentity();
1567 synchronized (mGlobalLock) {
1568 ActivityStack stack = ActivityRecord.getStackLocked(token);
1569 if (stack != null) {
1570 stack.activityPausedLocked(token, false);
1571 }
1572 }
1573 Binder.restoreCallingIdentity(origId);
1574 }
1575
1576 @Override
1577 public final void activityStopped(IBinder token, Bundle icicle,
1578 PersistableBundle persistentState, CharSequence description) {
1579 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1580
1581 // Refuse possible leaked file descriptors
1582 if (icicle != null && icicle.hasFileDescriptors()) {
1583 throw new IllegalArgumentException("File descriptors passed in Bundle");
1584 }
1585
1586 final long origId = Binder.clearCallingIdentity();
1587
1588 synchronized (mGlobalLock) {
1589 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1590 if (r != null) {
1591 r.activityStoppedLocked(icicle, persistentState, description);
1592 }
1593 }
1594
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001595 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596
1597 Binder.restoreCallingIdentity(origId);
1598 }
1599
1600 @Override
1601 public final void activityDestroyed(IBinder token) {
1602 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1603 synchronized (mGlobalLock) {
1604 ActivityStack stack = ActivityRecord.getStackLocked(token);
1605 if (stack != null) {
1606 stack.activityDestroyedLocked(token, "activityDestroyed");
1607 }
1608 }
1609 }
1610
1611 @Override
1612 public final void activityRelaunched(IBinder token) {
1613 final long origId = Binder.clearCallingIdentity();
1614 synchronized (mGlobalLock) {
1615 mStackSupervisor.activityRelaunchedLocked(token);
1616 }
1617 Binder.restoreCallingIdentity(origId);
1618 }
1619
1620 public final void activitySlept(IBinder token) {
1621 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1622
1623 final long origId = Binder.clearCallingIdentity();
1624
1625 synchronized (mGlobalLock) {
1626 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1627 if (r != null) {
1628 mStackSupervisor.activitySleptLocked(r);
1629 }
1630 }
1631
1632 Binder.restoreCallingIdentity(origId);
1633 }
1634
1635 @Override
1636 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1637 synchronized (mGlobalLock) {
1638 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1639 if (r == null) {
1640 return;
1641 }
1642 final long origId = Binder.clearCallingIdentity();
1643 try {
1644 r.setRequestedOrientation(requestedOrientation);
1645 } finally {
1646 Binder.restoreCallingIdentity(origId);
1647 }
1648 }
1649 }
1650
1651 @Override
1652 public int getRequestedOrientation(IBinder token) {
1653 synchronized (mGlobalLock) {
1654 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1655 if (r == null) {
1656 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1657 }
1658 return r.getRequestedOrientation();
1659 }
1660 }
1661
1662 @Override
1663 public void setImmersive(IBinder token, boolean immersive) {
1664 synchronized (mGlobalLock) {
1665 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1666 if (r == null) {
1667 throw new IllegalArgumentException();
1668 }
1669 r.immersive = immersive;
1670
1671 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001672 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001674 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 }
1676 }
1677 }
1678
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001679 void applyUpdateLockStateLocked(ActivityRecord r) {
1680 // Modifications to the UpdateLock state are done on our handler, outside
1681 // the activity manager's locks. The new state is determined based on the
1682 // state *now* of the relevant activity record. The object is passed to
1683 // the handler solely for logging detail, not to be consulted/modified.
1684 final boolean nextState = r != null && r.immersive;
1685 mH.post(() -> {
1686 if (mUpdateLock.isHeld() != nextState) {
1687 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1688 "Applying new update lock state '" + nextState + "' for " + r);
1689 if (nextState) {
1690 mUpdateLock.acquire();
1691 } else {
1692 mUpdateLock.release();
1693 }
1694 }
1695 });
1696 }
1697
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 @Override
1699 public boolean isImmersive(IBinder token) {
1700 synchronized (mGlobalLock) {
1701 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1702 if (r == null) {
1703 throw new IllegalArgumentException();
1704 }
1705 return r.immersive;
1706 }
1707 }
1708
1709 @Override
1710 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001711 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001713 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 return (r != null) ? r.immersive : false;
1715 }
1716 }
1717
1718 @Override
1719 public void overridePendingTransition(IBinder token, String packageName,
1720 int enterAnim, int exitAnim) {
1721 synchronized (mGlobalLock) {
1722 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1723 if (self == null) {
1724 return;
1725 }
1726
1727 final long origId = Binder.clearCallingIdentity();
1728
1729 if (self.isState(
1730 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001731 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1732 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 }
1734
1735 Binder.restoreCallingIdentity(origId);
1736 }
1737 }
1738
1739 @Override
1740 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001741 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001743 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001744 if (r == null) {
1745 return ActivityManager.COMPAT_MODE_UNKNOWN;
1746 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001747 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 }
1749 }
1750
1751 @Override
1752 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001753 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001754 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001755 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001757 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001758 if (r == null) {
1759 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1760 return;
1761 }
1762 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001763 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 }
1765 }
1766
1767 @Override
1768 public int getLaunchedFromUid(IBinder activityToken) {
1769 ActivityRecord srec;
1770 synchronized (mGlobalLock) {
1771 srec = ActivityRecord.forTokenLocked(activityToken);
1772 }
1773 if (srec == null) {
1774 return -1;
1775 }
1776 return srec.launchedFromUid;
1777 }
1778
1779 @Override
1780 public String getLaunchedFromPackage(IBinder activityToken) {
1781 ActivityRecord srec;
1782 synchronized (mGlobalLock) {
1783 srec = ActivityRecord.forTokenLocked(activityToken);
1784 }
1785 if (srec == null) {
1786 return null;
1787 }
1788 return srec.launchedFromPackage;
1789 }
1790
1791 @Override
1792 public boolean convertFromTranslucent(IBinder token) {
1793 final long origId = Binder.clearCallingIdentity();
1794 try {
1795 synchronized (mGlobalLock) {
1796 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1797 if (r == null) {
1798 return false;
1799 }
1800 final boolean translucentChanged = r.changeWindowTranslucency(true);
1801 if (translucentChanged) {
1802 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1803 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001804 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 return translucentChanged;
1806 }
1807 } finally {
1808 Binder.restoreCallingIdentity(origId);
1809 }
1810 }
1811
1812 @Override
1813 public boolean convertToTranslucent(IBinder token, Bundle options) {
1814 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1815 final long origId = Binder.clearCallingIdentity();
1816 try {
1817 synchronized (mGlobalLock) {
1818 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1819 if (r == null) {
1820 return false;
1821 }
1822 final TaskRecord task = r.getTask();
1823 int index = task.mActivities.lastIndexOf(r);
1824 if (index > 0) {
1825 ActivityRecord under = task.mActivities.get(index - 1);
1826 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1827 }
1828 final boolean translucentChanged = r.changeWindowTranslucency(false);
1829 if (translucentChanged) {
1830 r.getStack().convertActivityToTranslucent(r);
1831 }
1832 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001833 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 return translucentChanged;
1835 }
1836 } finally {
1837 Binder.restoreCallingIdentity(origId);
1838 }
1839 }
1840
1841 @Override
1842 public void notifyActivityDrawn(IBinder token) {
1843 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1844 synchronized (mGlobalLock) {
1845 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1846 if (r != null) {
1847 r.getStack().notifyActivityDrawnLocked(r);
1848 }
1849 }
1850 }
1851
1852 @Override
1853 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1854 synchronized (mGlobalLock) {
1855 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1856 if (r == null) {
1857 return;
1858 }
1859 r.reportFullyDrawnLocked(restoredFromBundle);
1860 }
1861 }
1862
1863 @Override
1864 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1865 synchronized (mGlobalLock) {
1866 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1867 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1868 return stack.mDisplayId;
1869 }
1870 return DEFAULT_DISPLAY;
1871 }
1872 }
1873
1874 @Override
1875 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 long ident = Binder.clearCallingIdentity();
1878 try {
1879 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001880 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 if (focusedStack != null) {
1882 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1883 }
1884 return null;
1885 }
1886 } finally {
1887 Binder.restoreCallingIdentity(ident);
1888 }
1889 }
1890
1891 @Override
1892 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001893 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1895 final long callingId = Binder.clearCallingIdentity();
1896 try {
1897 synchronized (mGlobalLock) {
1898 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1899 if (stack == null) {
1900 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1901 return;
1902 }
1903 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001904 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001905 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908 } finally {
1909 Binder.restoreCallingIdentity(callingId);
1910 }
1911 }
1912
1913 @Override
1914 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1917 final long callingId = Binder.clearCallingIdentity();
1918 try {
1919 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001920 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1921 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 if (task == null) {
1923 return;
1924 }
1925 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001926 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001927 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 }
1930 } finally {
1931 Binder.restoreCallingIdentity(callingId);
1932 }
1933 }
1934
1935 @Override
1936 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 synchronized (mGlobalLock) {
1939 final long ident = Binder.clearCallingIdentity();
1940 try {
1941 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1942 "remove-task");
1943 } finally {
1944 Binder.restoreCallingIdentity(ident);
1945 }
1946 }
1947 }
1948
1949 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001950 public void removeAllVisibleRecentTasks() {
1951 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1952 synchronized (mGlobalLock) {
1953 final long ident = Binder.clearCallingIdentity();
1954 try {
1955 getRecentTasks().removeAllVisibleTasks();
1956 } finally {
1957 Binder.restoreCallingIdentity(ident);
1958 }
1959 }
1960 }
1961
1962 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1964 synchronized (mGlobalLock) {
1965 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1966 if (srec != null) {
1967 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1968 }
1969 }
1970 return false;
1971 }
1972
1973 @Override
1974 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1975 Intent resultData) {
1976
1977 synchronized (mGlobalLock) {
1978 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1979 if (r != null) {
1980 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1981 }
1982 return false;
1983 }
1984 }
1985
1986 /**
1987 * Attempts to move a task backwards in z-order (the order of activities within the task is
1988 * unchanged).
1989 *
1990 * There are several possible results of this call:
1991 * - if the task is locked, then we will show the lock toast
1992 * - if there is a task behind the provided task, then that task is made visible and resumed as
1993 * this task is moved to the back
1994 * - otherwise, if there are no other tasks in the stack:
1995 * - if this task is in the pinned stack, then we remove the stack completely, which will
1996 * have the effect of moving the task to the top or bottom of the fullscreen stack
1997 * (depending on whether it is visible)
1998 * - otherwise, we simply return home and hide this task
1999 *
2000 * @param token A reference to the activity we wish to move
2001 * @param nonRoot If false then this only works if the activity is the root
2002 * of a task; if true it will work for any activity in a task.
2003 * @return Returns true if the move completed, false if not.
2004 */
2005 @Override
2006 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002007 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 synchronized (mGlobalLock) {
2009 final long origId = Binder.clearCallingIdentity();
2010 try {
2011 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
2012 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2013 if (task != null) {
2014 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2015 }
2016 } finally {
2017 Binder.restoreCallingIdentity(origId);
2018 }
2019 }
2020 return false;
2021 }
2022
2023 @Override
2024 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002025 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 long ident = Binder.clearCallingIdentity();
2027 Rect rect = new Rect();
2028 try {
2029 synchronized (mGlobalLock) {
2030 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2031 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2032 if (task == null) {
2033 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2034 return rect;
2035 }
2036 if (task.getStack() != null) {
2037 // Return the bounds from window manager since it will be adjusted for various
2038 // things like the presense of a docked stack for tasks that aren't resizeable.
2039 task.getWindowContainerBounds(rect);
2040 } else {
2041 // Task isn't in window manager yet since it isn't associated with a stack.
2042 // Return the persist value from activity manager
2043 if (!task.matchParentBounds()) {
2044 rect.set(task.getBounds());
2045 } else if (task.mLastNonFullscreenBounds != null) {
2046 rect.set(task.mLastNonFullscreenBounds);
2047 }
2048 }
2049 }
2050 } finally {
2051 Binder.restoreCallingIdentity(ident);
2052 }
2053 return rect;
2054 }
2055
2056 @Override
2057 public ActivityManager.TaskDescription getTaskDescription(int id) {
2058 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002059 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
2061 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
2062 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2063 if (tr != null) {
2064 return tr.lastTaskDescription;
2065 }
2066 }
2067 return null;
2068 }
2069
2070 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002071 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2072 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2073 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2074 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2075 return;
2076 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002077 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002078 synchronized (mGlobalLock) {
2079 final long ident = Binder.clearCallingIdentity();
2080 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002081 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2082 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002083 if (task == null) {
2084 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2085 return;
2086 }
2087
2088 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2089 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2090
2091 if (!task.isActivityTypeStandardOrUndefined()) {
2092 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2093 + " non-standard task " + taskId + " to windowing mode="
2094 + windowingMode);
2095 }
2096
2097 final ActivityStack stack = task.getStack();
2098 if (toTop) {
2099 stack.moveToFront("setTaskWindowingMode", task);
2100 }
2101 stack.setWindowingMode(windowingMode);
2102 } finally {
2103 Binder.restoreCallingIdentity(ident);
2104 }
2105 }
2106 }
2107
2108 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002110 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 ActivityRecord r = getCallingRecordLocked(token);
2112 return r != null ? r.info.packageName : null;
2113 }
2114 }
2115
2116 @Override
2117 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002118 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 ActivityRecord r = getCallingRecordLocked(token);
2120 return r != null ? r.intent.getComponent() : null;
2121 }
2122 }
2123
2124 private ActivityRecord getCallingRecordLocked(IBinder token) {
2125 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2126 if (r == null) {
2127 return null;
2128 }
2129 return r.resultTo;
2130 }
2131
2132 @Override
2133 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002134 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002135
2136 synchronized (mGlobalLock) {
2137 final long origId = Binder.clearCallingIdentity();
2138 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002139 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 } finally {
2141 Binder.restoreCallingIdentity(origId);
2142 }
2143 }
2144 }
2145
2146 /**
2147 * TODO: Add mController hook
2148 */
2149 @Override
2150 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002151 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002152
2153 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2154 synchronized (mGlobalLock) {
2155 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2156 false /* fromRecents */);
2157 }
2158 }
2159
2160 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2161 boolean fromRecents) {
2162
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002163 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 Binder.getCallingUid(), -1, -1, "Task to front")) {
2165 SafeActivityOptions.abort(options);
2166 return;
2167 }
2168 final long origId = Binder.clearCallingIdentity();
2169 try {
2170 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2171 if (task == null) {
2172 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002173 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 return;
2175 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002176 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002178 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 return;
2180 }
2181 ActivityOptions realOptions = options != null
2182 ? options.getOptions(mStackSupervisor)
2183 : null;
2184 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2185 false /* forceNonResizable */);
2186
2187 final ActivityRecord topActivity = task.getTopActivity();
2188 if (topActivity != null) {
2189
2190 // We are reshowing a task, use a starting window to hide the initial draw delay
2191 // so the transition can start earlier.
2192 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2193 true /* taskSwitch */, fromRecents);
2194 }
2195 } finally {
2196 Binder.restoreCallingIdentity(origId);
2197 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 }
2199
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2201 int callingPid, int callingUid, String name) {
2202 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2203 return true;
2204 }
2205
2206 if (getRecentTasks().isCallerRecents(sourceUid)) {
2207 return true;
2208 }
2209
2210 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2211 if (perm == PackageManager.PERMISSION_GRANTED) {
2212 return true;
2213 }
2214 if (checkAllowAppSwitchUid(sourceUid)) {
2215 return true;
2216 }
2217
2218 // If the actual IPC caller is different from the logical source, then
2219 // also see if they are allowed to control app switches.
2220 if (callingUid != -1 && callingUid != sourceUid) {
2221 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2222 if (perm == PackageManager.PERMISSION_GRANTED) {
2223 return true;
2224 }
2225 if (checkAllowAppSwitchUid(callingUid)) {
2226 return true;
2227 }
2228 }
2229
2230 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2231 return false;
2232 }
2233
2234 private boolean checkAllowAppSwitchUid(int uid) {
2235 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2236 if (types != null) {
2237 for (int i = types.size() - 1; i >= 0; i--) {
2238 if (types.valueAt(i).intValue() == uid) {
2239 return true;
2240 }
2241 }
2242 }
2243 return false;
2244 }
2245
2246 @Override
2247 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2248 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2249 "setActivityController()");
2250 synchronized (mGlobalLock) {
2251 mController = controller;
2252 mControllerIsAMonkey = imAMonkey;
2253 Watchdog.getInstance().setActivityController(controller);
2254 }
2255 }
2256
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002257 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002258 synchronized (mGlobalLock) {
2259 return mController != null && mControllerIsAMonkey;
2260 }
2261 }
2262
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002263 @Override
2264 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2265 synchronized (mGlobalLock) {
2266 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2267 }
2268 }
2269
2270 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2272 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2273 }
2274
2275 @Override
2276 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2277 @WindowConfiguration.ActivityType int ignoreActivityType,
2278 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2279 final int callingUid = Binder.getCallingUid();
2280 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2281
2282 synchronized (mGlobalLock) {
2283 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2284
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002286 callingUid);
2287 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2288 ignoreWindowingMode, callingUid, allowed);
2289 }
2290
2291 return list;
2292 }
2293
2294 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2296 synchronized (mGlobalLock) {
2297 final long origId = Binder.clearCallingIdentity();
2298 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2299 if (r != null) {
2300 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2301 }
2302 Binder.restoreCallingIdentity(origId);
2303 }
2304 }
2305
2306 @Override
2307 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002308 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002309 ActivityStack stack = ActivityRecord.getStackLocked(token);
2310 if (stack != null) {
2311 return stack.willActivityBeVisibleLocked(token);
2312 }
2313 return false;
2314 }
2315 }
2316
2317 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002318 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002319 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002320 synchronized (mGlobalLock) {
2321 final long ident = Binder.clearCallingIdentity();
2322 try {
2323 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2324 if (task == null) {
2325 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2326 return;
2327 }
2328
2329 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2330 + " to stackId=" + stackId + " toTop=" + toTop);
2331
2332 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2333 if (stack == null) {
2334 throw new IllegalStateException(
2335 "moveTaskToStack: No stack for stackId=" + stackId);
2336 }
2337 if (!stack.isActivityTypeStandardOrUndefined()) {
2338 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2339 + taskId + " to stack " + stackId);
2340 }
2341 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002342 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002343 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2344 }
2345 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2346 "moveTaskToStack");
2347 } finally {
2348 Binder.restoreCallingIdentity(ident);
2349 }
2350 }
2351 }
2352
2353 @Override
2354 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2355 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002356 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002357
2358 final long ident = Binder.clearCallingIdentity();
2359 try {
2360 synchronized (mGlobalLock) {
2361 if (animate) {
2362 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2363 if (stack == null) {
2364 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2365 return;
2366 }
2367 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2368 throw new IllegalArgumentException("Stack: " + stackId
2369 + " doesn't support animated resize.");
2370 }
2371 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2372 animationDuration, false /* fromFullscreen */);
2373 } else {
2374 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2375 if (stack == null) {
2376 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2377 return;
2378 }
2379 mStackSupervisor.resizeStackLocked(stack, destBounds,
2380 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2381 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2382 }
2383 }
2384 } finally {
2385 Binder.restoreCallingIdentity(ident);
2386 }
2387 }
2388
2389 /**
2390 * Moves the specified task to the primary-split-screen stack.
2391 *
2392 * @param taskId Id of task to move.
2393 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2394 * exist already. See
2395 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2396 * and
2397 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2398 * @param toTop If the task and stack should be moved to the top.
2399 * @param animate Whether we should play an animation for the moving the task.
2400 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2401 * stack. Pass {@code null} to use default bounds.
2402 * @param showRecents If the recents activity should be shown on the other side of the task
2403 * going into split-screen mode.
2404 */
2405 @Override
2406 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2407 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002408 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002409 "setTaskWindowingModeSplitScreenPrimary()");
2410 synchronized (mGlobalLock) {
2411 final long ident = Binder.clearCallingIdentity();
2412 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002413 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2414 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002415 if (task == null) {
2416 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2417 return false;
2418 }
2419 if (DEBUG_STACK) Slog.d(TAG_STACK,
2420 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2421 + " to createMode=" + createMode + " toTop=" + toTop);
2422 if (!task.isActivityTypeStandardOrUndefined()) {
2423 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2424 + " non-standard task " + taskId + " to split-screen windowing mode");
2425 }
2426
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002427 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002428 final int windowingMode = task.getWindowingMode();
2429 final ActivityStack stack = task.getStack();
2430 if (toTop) {
2431 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2432 }
2433 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002434 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2435 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002436 return windowingMode != task.getWindowingMode();
2437 } finally {
2438 Binder.restoreCallingIdentity(ident);
2439 }
2440 }
2441 }
2442
2443 /**
2444 * Removes stacks in the input windowing modes from the system if they are of activity type
2445 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2446 */
2447 @Override
2448 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002449 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002450 "removeStacksInWindowingModes()");
2451
2452 synchronized (mGlobalLock) {
2453 final long ident = Binder.clearCallingIdentity();
2454 try {
2455 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2456 } finally {
2457 Binder.restoreCallingIdentity(ident);
2458 }
2459 }
2460 }
2461
2462 @Override
2463 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002464 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002465 "removeStacksWithActivityTypes()");
2466
2467 synchronized (mGlobalLock) {
2468 final long ident = Binder.clearCallingIdentity();
2469 try {
2470 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2471 } finally {
2472 Binder.restoreCallingIdentity(ident);
2473 }
2474 }
2475 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002476
2477 @Override
2478 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2479 int userId) {
2480 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002481 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2482 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002483 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002484 final boolean detailed = checkGetTasksPermission(
2485 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2486 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002487 == PackageManager.PERMISSION_GRANTED;
2488
2489 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002490 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002491 callingUid);
2492 }
2493 }
2494
2495 @Override
2496 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002497 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002498 long ident = Binder.clearCallingIdentity();
2499 try {
2500 synchronized (mGlobalLock) {
2501 return mStackSupervisor.getAllStackInfosLocked();
2502 }
2503 } finally {
2504 Binder.restoreCallingIdentity(ident);
2505 }
2506 }
2507
2508 @Override
2509 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002510 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002511 long ident = Binder.clearCallingIdentity();
2512 try {
2513 synchronized (mGlobalLock) {
2514 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2515 }
2516 } finally {
2517 Binder.restoreCallingIdentity(ident);
2518 }
2519 }
2520
2521 @Override
2522 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002523 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524 final long callingUid = Binder.getCallingUid();
2525 final long origId = Binder.clearCallingIdentity();
2526 try {
2527 synchronized (mGlobalLock) {
2528 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2531 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2532 }
2533 } finally {
2534 Binder.restoreCallingIdentity(origId);
2535 }
2536 }
2537
2538 @Override
2539 public void startLockTaskModeByToken(IBinder token) {
2540 synchronized (mGlobalLock) {
2541 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2542 if (r == null) {
2543 return;
2544 }
2545 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2546 }
2547 }
2548
2549 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002550 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002551 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002552 // This makes inner call to look as if it was initiated by system.
2553 long ident = Binder.clearCallingIdentity();
2554 try {
2555 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002556 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2557 MATCH_TASK_IN_STACKS_ONLY);
2558 if (task == null) {
2559 return;
2560 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002561
2562 // When starting lock task mode the stack must be in front and focused
2563 task.getStack().moveToFront("startSystemLockTaskMode");
2564 startLockTaskModeLocked(task, true /* isSystemCaller */);
2565 }
2566 } finally {
2567 Binder.restoreCallingIdentity(ident);
2568 }
2569 }
2570
2571 @Override
2572 public void stopLockTaskModeByToken(IBinder token) {
2573 synchronized (mGlobalLock) {
2574 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2575 if (r == null) {
2576 return;
2577 }
2578 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2579 }
2580 }
2581
2582 /**
2583 * This API should be called by SystemUI only when user perform certain action to dismiss
2584 * lock task mode. We should only dismiss pinned lock task mode in this case.
2585 */
2586 @Override
2587 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002588 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002589 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2590 }
2591
2592 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2593 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2594 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2595 return;
2596 }
2597
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002598 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 if (stack == null || task != stack.topTask()) {
2600 throw new IllegalArgumentException("Invalid task, not in foreground");
2601 }
2602
2603 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2604 // system or a specific app.
2605 // * System-initiated requests will only start the pinned mode (screen pinning)
2606 // * App-initiated requests
2607 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2608 // - will start the pinned mode, otherwise
2609 final int callingUid = Binder.getCallingUid();
2610 long ident = Binder.clearCallingIdentity();
2611 try {
2612 // When a task is locked, dismiss the pinned stack if it exists
2613 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2614
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002615 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002616 } finally {
2617 Binder.restoreCallingIdentity(ident);
2618 }
2619 }
2620
2621 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2622 final int callingUid = Binder.getCallingUid();
2623 long ident = Binder.clearCallingIdentity();
2624 try {
2625 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002626 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002627 }
2628 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2629 // task and jumping straight into a call in the case of emergency call back.
2630 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2631 if (tm != null) {
2632 tm.showInCallScreen(false);
2633 }
2634 } finally {
2635 Binder.restoreCallingIdentity(ident);
2636 }
2637 }
2638
2639 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002640 public void updateLockTaskPackages(int userId, String[] packages) {
2641 final int callingUid = Binder.getCallingUid();
2642 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2643 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2644 "updateLockTaskPackages()");
2645 }
2646 synchronized (this) {
2647 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2648 + Arrays.toString(packages));
2649 getLockTaskController().updateLockTaskPackages(userId, packages);
2650 }
2651 }
2652
2653 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 public boolean isInLockTaskMode() {
2655 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2656 }
2657
2658 @Override
2659 public int getLockTaskModeState() {
2660 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002661 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002662 }
2663 }
2664
2665 @Override
2666 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2667 synchronized (mGlobalLock) {
2668 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2669 if (r != null) {
2670 r.setTaskDescription(td);
2671 final TaskRecord task = r.getTask();
2672 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002673 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 }
2675 }
2676 }
2677
2678 @Override
2679 public Bundle getActivityOptions(IBinder token) {
2680 final long origId = Binder.clearCallingIdentity();
2681 try {
2682 synchronized (mGlobalLock) {
2683 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2684 if (r != null) {
2685 final ActivityOptions activityOptions = r.takeOptionsLocked();
2686 return activityOptions == null ? null : activityOptions.toBundle();
2687 }
2688 return null;
2689 }
2690 } finally {
2691 Binder.restoreCallingIdentity(origId);
2692 }
2693 }
2694
2695 @Override
2696 public List<IBinder> getAppTasks(String callingPackage) {
2697 int callingUid = Binder.getCallingUid();
2698 long ident = Binder.clearCallingIdentity();
2699 try {
2700 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002701 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002702 }
2703 } finally {
2704 Binder.restoreCallingIdentity(ident);
2705 }
2706 }
2707
2708 @Override
2709 public void finishVoiceTask(IVoiceInteractionSession session) {
2710 synchronized (mGlobalLock) {
2711 final long origId = Binder.clearCallingIdentity();
2712 try {
2713 // TODO: VI Consider treating local voice interactions and voice tasks
2714 // differently here
2715 mStackSupervisor.finishVoiceTask(session);
2716 } finally {
2717 Binder.restoreCallingIdentity(origId);
2718 }
2719 }
2720
2721 }
2722
2723 @Override
2724 public boolean isTopOfTask(IBinder token) {
2725 synchronized (mGlobalLock) {
2726 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002727 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002728 }
2729 }
2730
2731 @Override
2732 public void notifyLaunchTaskBehindComplete(IBinder token) {
2733 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2734 }
2735
2736 @Override
2737 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002738 mH.post(() -> {
2739 synchronized (mGlobalLock) {
2740 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002741 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002742 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002743 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002744 } catch (RemoteException e) {
2745 }
2746 }
2747 }
2748
2749 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 }
2751
2752 /** Called from an app when assist data is ready. */
2753 @Override
2754 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2755 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002757 synchronized (pae) {
2758 pae.result = extras;
2759 pae.structure = structure;
2760 pae.content = content;
2761 if (referrer != null) {
2762 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2763 }
2764 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002765 // Pre-fill the task/activity component for all assist data receivers
2766 structure.setTaskId(pae.activity.getTask().taskId);
2767 structure.setActivityComponent(pae.activity.realActivity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 structure.setHomeActivity(pae.isHome);
2769 }
2770 pae.haveResult = true;
2771 pae.notifyAll();
2772 if (pae.intent == null && pae.receiver == null) {
2773 // Caller is just waiting for the result.
2774 return;
2775 }
2776 }
2777 // We are now ready to launch the assist activity.
2778 IAssistDataReceiver sendReceiver = null;
2779 Bundle sendBundle = null;
2780 synchronized (mGlobalLock) {
2781 buildAssistBundleLocked(pae, extras);
2782 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002783 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 if (!exists) {
2785 // Timed out.
2786 return;
2787 }
2788
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002789 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 // Caller wants result sent back to them.
2791 sendBundle = new Bundle();
2792 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2793 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2794 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2795 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2796 }
2797 }
2798 if (sendReceiver != null) {
2799 try {
2800 sendReceiver.onHandleAssistData(sendBundle);
2801 } catch (RemoteException e) {
2802 }
2803 return;
2804 }
2805
2806 final long ident = Binder.clearCallingIdentity();
2807 try {
2808 if (TextUtils.equals(pae.intent.getAction(),
2809 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2810 pae.intent.putExtras(pae.extras);
2811 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2812 } else {
2813 pae.intent.replaceExtras(pae.extras);
2814 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2815 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2816 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002817 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818
2819 try {
2820 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2821 } catch (ActivityNotFoundException e) {
2822 Slog.w(TAG, "No activity to handle assist action.", e);
2823 }
2824 }
2825 } finally {
2826 Binder.restoreCallingIdentity(ident);
2827 }
2828 }
2829
2830 @Override
2831 public int addAppTask(IBinder activityToken, Intent intent,
2832 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2833 final int callingUid = Binder.getCallingUid();
2834 final long callingIdent = Binder.clearCallingIdentity();
2835
2836 try {
2837 synchronized (mGlobalLock) {
2838 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2839 if (r == null) {
2840 throw new IllegalArgumentException("Activity does not exist; token="
2841 + activityToken);
2842 }
2843 ComponentName comp = intent.getComponent();
2844 if (comp == null) {
2845 throw new IllegalArgumentException("Intent " + intent
2846 + " must specify explicit component");
2847 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002848 if (thumbnail.getWidth() != mThumbnailWidth
2849 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 throw new IllegalArgumentException("Bad thumbnail size: got "
2851 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002852 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 }
2854 if (intent.getSelector() != null) {
2855 intent.setSelector(null);
2856 }
2857 if (intent.getSourceBounds() != null) {
2858 intent.setSourceBounds(null);
2859 }
2860 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2861 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2862 // The caller has added this as an auto-remove task... that makes no
2863 // sense, so turn off auto-remove.
2864 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2865 }
2866 }
2867 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2868 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2869 if (ainfo.applicationInfo.uid != callingUid) {
2870 throw new SecurityException(
2871 "Can't add task for another application: target uid="
2872 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2873 }
2874
2875 final ActivityStack stack = r.getStack();
2876 final TaskRecord task = stack.createTaskRecord(
2877 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2878 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002879 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 // The app has too many tasks already and we can't add any more
2881 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2882 return INVALID_TASK_ID;
2883 }
2884 task.lastTaskDescription.copyFrom(description);
2885
2886 // TODO: Send the thumbnail to WM to store it.
2887
2888 return task.taskId;
2889 }
2890 } finally {
2891 Binder.restoreCallingIdentity(callingIdent);
2892 }
2893 }
2894
2895 @Override
2896 public Point getAppTaskThumbnailSize() {
2897 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002898 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899 }
2900 }
2901
2902 @Override
2903 public void setTaskResizeable(int taskId, int resizeableMode) {
2904 synchronized (mGlobalLock) {
2905 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2906 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2907 if (task == null) {
2908 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2909 return;
2910 }
2911 task.setResizeMode(resizeableMode);
2912 }
2913 }
2914
2915 @Override
2916 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002917 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 long ident = Binder.clearCallingIdentity();
2919 try {
2920 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002921 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2922 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 if (task == null) {
2924 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2925 return;
2926 }
2927 // Place the task in the right stack if it isn't there already based on
2928 // the requested bounds.
2929 // The stack transition logic is:
2930 // - a null bounds on a freeform task moves that task to fullscreen
2931 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2932 // that task to freeform
2933 // - otherwise the task is not moved
2934 ActivityStack stack = task.getStack();
2935 if (!task.getWindowConfiguration().canResizeTask()) {
2936 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2937 }
2938 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2939 stack = stack.getDisplay().getOrCreateStack(
2940 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2941 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2942 stack = stack.getDisplay().getOrCreateStack(
2943 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2944 }
2945
2946 // Reparent the task to the right stack if necessary
2947 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2948 if (stack != task.getStack()) {
2949 // Defer resume until the task is resized below
2950 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2951 DEFER_RESUME, "resizeTask");
2952 preserveWindow = false;
2953 }
2954
2955 // After reparenting (which only resizes the task to the stack bounds), resize the
2956 // task to the actual bounds provided
2957 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2958 }
2959 } finally {
2960 Binder.restoreCallingIdentity(ident);
2961 }
2962 }
2963
2964 @Override
2965 public boolean releaseActivityInstance(IBinder token) {
2966 synchronized (mGlobalLock) {
2967 final long origId = Binder.clearCallingIdentity();
2968 try {
2969 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2970 if (r == null) {
2971 return false;
2972 }
2973 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2974 } finally {
2975 Binder.restoreCallingIdentity(origId);
2976 }
2977 }
2978 }
2979
2980 @Override
2981 public void releaseSomeActivities(IApplicationThread appInt) {
2982 synchronized (mGlobalLock) {
2983 final long origId = Binder.clearCallingIdentity();
2984 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002985 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2987 } finally {
2988 Binder.restoreCallingIdentity(origId);
2989 }
2990 }
2991 }
2992
2993 @Override
2994 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002995 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002996 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 != PackageManager.PERMISSION_GRANTED) {
2998 throw new SecurityException("Requires permission "
2999 + android.Manifest.permission.DEVICE_POWER);
3000 }
3001
3002 synchronized (mGlobalLock) {
3003 long ident = Binder.clearCallingIdentity();
3004 if (mKeyguardShown != keyguardShowing) {
3005 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003006 final Message msg = PooledLambda.obtainMessage(
3007 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3008 keyguardShowing);
3009 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 }
3011 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003012 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003013 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 } finally {
3015 Binder.restoreCallingIdentity(ident);
3016 }
3017 }
3018
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003019 mH.post(() -> {
3020 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3021 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3022 }
3023 });
3024 }
3025
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003026 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003027 mH.post(() -> {
3028 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3029 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3030 }
3031 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 }
3033
3034 @Override
3035 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003036 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3037 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038
3039 final File passedIconFile = new File(filePath);
3040 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3041 passedIconFile.getName());
3042 if (!legitIconFile.getPath().equals(filePath)
3043 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3044 throw new IllegalArgumentException("Bad file path: " + filePath
3045 + " passed for userId " + userId);
3046 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003047 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003048 }
3049
3050 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003051 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3053 final ActivityOptions activityOptions = safeOptions != null
3054 ? safeOptions.getOptions(mStackSupervisor)
3055 : null;
3056 if (activityOptions == null
3057 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3058 || activityOptions.getCustomInPlaceResId() == 0) {
3059 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3060 "with valid animation");
3061 }
lumark588a3e82018-07-20 18:53:54 +08003062 // Get top display of front most application.
3063 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3064 if (focusedStack != null) {
3065 final DisplayWindowController dwc =
3066 focusedStack.getDisplay().getWindowContainerController();
3067 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3068 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3069 activityOptions.getCustomInPlaceResId());
3070 dwc.executeAppTransition();
3071 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 }
3073
3074 @Override
3075 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003076 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077 synchronized (mGlobalLock) {
3078 final long ident = Binder.clearCallingIdentity();
3079 try {
3080 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3081 if (stack == null) {
3082 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3083 return;
3084 }
3085 if (!stack.isActivityTypeStandardOrUndefined()) {
3086 throw new IllegalArgumentException(
3087 "Removing non-standard stack is not allowed.");
3088 }
3089 mStackSupervisor.removeStack(stack);
3090 } finally {
3091 Binder.restoreCallingIdentity(ident);
3092 }
3093 }
3094 }
3095
3096 @Override
3097 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003098 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099
3100 synchronized (mGlobalLock) {
3101 final long ident = Binder.clearCallingIdentity();
3102 try {
3103 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3104 + " to displayId=" + displayId);
3105 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
3106 } finally {
3107 Binder.restoreCallingIdentity(ident);
3108 }
3109 }
3110 }
3111
3112 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 public void exitFreeformMode(IBinder token) {
3114 synchronized (mGlobalLock) {
3115 long ident = Binder.clearCallingIdentity();
3116 try {
3117 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3118 if (r == null) {
3119 throw new IllegalArgumentException(
3120 "exitFreeformMode: No activity record matching token=" + token);
3121 }
3122
3123 final ActivityStack stack = r.getStack();
3124 if (stack == null || !stack.inFreeformWindowingMode()) {
3125 throw new IllegalStateException(
3126 "exitFreeformMode: You can only go fullscreen from freeform.");
3127 }
3128
3129 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3130 } finally {
3131 Binder.restoreCallingIdentity(ident);
3132 }
3133 }
3134 }
3135
3136 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3137 @Override
3138 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003139 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003141 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003142 }
3143
3144 /** Unregister a task stack listener so that it stops receiving callbacks. */
3145 @Override
3146 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003147 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003149 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 }
3151
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 @Override
3153 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3154 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3155 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3156 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3157 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3158 }
3159
3160 @Override
3161 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3162 IBinder activityToken, int flags) {
3163 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3164 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3165 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3166 }
3167
3168 @Override
3169 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3170 Bundle args) {
3171 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3172 true /* focused */, true /* newSessionId */, userHandle, args,
3173 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3174 }
3175
3176 @Override
3177 public Bundle getAssistContextExtras(int requestType) {
3178 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3179 null, null, true /* focused */, true /* newSessionId */,
3180 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3181 if (pae == null) {
3182 return null;
3183 }
3184 synchronized (pae) {
3185 while (!pae.haveResult) {
3186 try {
3187 pae.wait();
3188 } catch (InterruptedException e) {
3189 }
3190 }
3191 }
3192 synchronized (mGlobalLock) {
3193 buildAssistBundleLocked(pae, pae.result);
3194 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003195 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197 return pae.extras;
3198 }
3199
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003200 /**
3201 * Binder IPC calls go through the public entry point.
3202 * This can be called with or without the global lock held.
3203 */
3204 private static int checkCallingPermission(String permission) {
3205 return checkPermission(
3206 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3207 }
3208
3209 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003210 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003211 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3212 mAmInternal.enforceCallingPermission(permission, func);
3213 }
3214 }
3215
3216 @VisibleForTesting
3217 int checkGetTasksPermission(String permission, int pid, int uid) {
3218 return checkPermission(permission, pid, uid);
3219 }
3220
3221 static int checkPermission(String permission, int pid, int uid) {
3222 if (permission == null) {
3223 return PackageManager.PERMISSION_DENIED;
3224 }
3225 return checkComponentPermission(permission, pid, uid, -1, true);
3226 }
3227
Wale Ogunwale214f3482018-10-04 11:00:47 -07003228 public static int checkComponentPermission(String permission, int pid, int uid,
3229 int owningUid, boolean exported) {
3230 return ActivityManagerService.checkComponentPermission(
3231 permission, pid, uid, owningUid, exported);
3232 }
3233
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003234 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3235 if (getRecentTasks().isCallerRecents(callingUid)) {
3236 // Always allow the recents component to get tasks
3237 return true;
3238 }
3239
3240 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3241 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3242 if (!allowed) {
3243 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3244 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3245 // Temporary compatibility: some existing apps on the system image may
3246 // still be requesting the old permission and not switched to the new
3247 // one; if so, we'll still allow them full access. This means we need
3248 // to see if they are holding the old permission and are a system app.
3249 try {
3250 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3251 allowed = true;
3252 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3253 + " is using old GET_TASKS but privileged; allowing");
3254 }
3255 } catch (RemoteException e) {
3256 }
3257 }
3258 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3259 + " does not hold REAL_GET_TASKS; limiting output");
3260 }
3261 return allowed;
3262 }
3263
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3265 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3266 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3267 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003268 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003269 "enqueueAssistContext()");
3270
3271 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003272 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003273 if (activity == null) {
3274 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3275 return null;
3276 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003277 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003278 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3279 return null;
3280 }
3281 if (focused) {
3282 if (activityToken != null) {
3283 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3284 if (activity != caller) {
3285 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3286 + " is not current top " + activity);
3287 return null;
3288 }
3289 }
3290 } else {
3291 activity = ActivityRecord.forTokenLocked(activityToken);
3292 if (activity == null) {
3293 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3294 + " couldn't be found");
3295 return null;
3296 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003297 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003298 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3299 return null;
3300 }
3301 }
3302
3303 PendingAssistExtras pae;
3304 Bundle extras = new Bundle();
3305 if (args != null) {
3306 extras.putAll(args);
3307 }
3308 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003309 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310
3311 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3312 userHandle);
3313 pae.isHome = activity.isActivityTypeHome();
3314
3315 // Increment the sessionId if necessary
3316 if (newSessionId) {
3317 mViSessionId++;
3318 }
3319 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003320 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3321 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003323 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 } catch (RemoteException e) {
3325 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3326 return null;
3327 }
3328 return pae;
3329 }
3330 }
3331
3332 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3333 if (result != null) {
3334 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3335 }
3336 if (pae.hint != null) {
3337 pae.extras.putBoolean(pae.hint, true);
3338 }
3339 }
3340
3341 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3342 IAssistDataReceiver receiver;
3343 synchronized (mGlobalLock) {
3344 mPendingAssistExtras.remove(pae);
3345 receiver = pae.receiver;
3346 }
3347 if (receiver != null) {
3348 // Caller wants result sent back to them.
3349 Bundle sendBundle = new Bundle();
3350 // At least return the receiver extras
3351 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3352 try {
3353 pae.receiver.onHandleAssistData(sendBundle);
3354 } catch (RemoteException e) {
3355 }
3356 }
3357 }
3358
3359 public class PendingAssistExtras extends Binder implements Runnable {
3360 public final ActivityRecord activity;
3361 public boolean isHome;
3362 public final Bundle extras;
3363 public final Intent intent;
3364 public final String hint;
3365 public final IAssistDataReceiver receiver;
3366 public final int userHandle;
3367 public boolean haveResult = false;
3368 public Bundle result = null;
3369 public AssistStructure structure = null;
3370 public AssistContent content = null;
3371 public Bundle receiverExtras;
3372
3373 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3374 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3375 int _userHandle) {
3376 activity = _activity;
3377 extras = _extras;
3378 intent = _intent;
3379 hint = _hint;
3380 receiver = _receiver;
3381 receiverExtras = _receiverExtras;
3382 userHandle = _userHandle;
3383 }
3384
3385 @Override
3386 public void run() {
3387 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3388 synchronized (this) {
3389 haveResult = true;
3390 notifyAll();
3391 }
3392 pendingAssistExtrasTimedOut(this);
3393 }
3394 }
3395
3396 @Override
3397 public boolean isAssistDataAllowedOnCurrentActivity() {
3398 int userId;
3399 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003400 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3402 return false;
3403 }
3404
3405 final ActivityRecord activity = focusedStack.getTopActivity();
3406 if (activity == null) {
3407 return false;
3408 }
3409 userId = activity.userId;
3410 }
3411 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3412 }
3413
3414 @Override
3415 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3416 long ident = Binder.clearCallingIdentity();
3417 try {
3418 synchronized (mGlobalLock) {
3419 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003420 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 if (top != caller) {
3422 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3423 + " is not current top " + top);
3424 return false;
3425 }
3426 if (!top.nowVisible) {
3427 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3428 + " is not visible");
3429 return false;
3430 }
3431 }
3432 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3433 token);
3434 } finally {
3435 Binder.restoreCallingIdentity(ident);
3436 }
3437 }
3438
3439 @Override
3440 public boolean isRootVoiceInteraction(IBinder token) {
3441 synchronized (mGlobalLock) {
3442 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3443 if (r == null) {
3444 return false;
3445 }
3446 return r.rootVoiceInteraction;
3447 }
3448 }
3449
Wale Ogunwalef6733932018-06-27 05:14:34 -07003450 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3451 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3452 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3453 if (activityToCallback == null) return;
3454 activityToCallback.setVoiceSessionLocked(voiceSession);
3455
3456 // Inform the activity
3457 try {
3458 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3459 voiceInteractor);
3460 long token = Binder.clearCallingIdentity();
3461 try {
3462 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3463 } finally {
3464 Binder.restoreCallingIdentity(token);
3465 }
3466 // TODO: VI Should we cache the activity so that it's easier to find later
3467 // rather than scan through all the stacks and activities?
3468 } catch (RemoteException re) {
3469 activityToCallback.clearVoiceSessionLocked();
3470 // TODO: VI Should this terminate the voice session?
3471 }
3472 }
3473
3474 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3475 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3476 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3477 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3478 boolean wasRunningVoice = mRunningVoice != null;
3479 mRunningVoice = session;
3480 if (!wasRunningVoice) {
3481 mVoiceWakeLock.acquire();
3482 updateSleepIfNeededLocked();
3483 }
3484 }
3485 }
3486
3487 void finishRunningVoiceLocked() {
3488 if (mRunningVoice != null) {
3489 mRunningVoice = null;
3490 mVoiceWakeLock.release();
3491 updateSleepIfNeededLocked();
3492 }
3493 }
3494
3495 @Override
3496 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3497 synchronized (mGlobalLock) {
3498 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3499 if (keepAwake) {
3500 mVoiceWakeLock.acquire();
3501 } else {
3502 mVoiceWakeLock.release();
3503 }
3504 }
3505 }
3506 }
3507
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508 @Override
3509 public ComponentName getActivityClassForToken(IBinder token) {
3510 synchronized (mGlobalLock) {
3511 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3512 if (r == null) {
3513 return null;
3514 }
3515 return r.intent.getComponent();
3516 }
3517 }
3518
3519 @Override
3520 public String getPackageForToken(IBinder token) {
3521 synchronized (mGlobalLock) {
3522 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3523 if (r == null) {
3524 return null;
3525 }
3526 return r.packageName;
3527 }
3528 }
3529
3530 @Override
3531 public void showLockTaskEscapeMessage(IBinder token) {
3532 synchronized (mGlobalLock) {
3533 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3534 if (r == null) {
3535 return;
3536 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003537 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 }
3539 }
3540
3541 @Override
3542 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003543 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003544 final long token = Binder.clearCallingIdentity();
3545 try {
3546 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003547 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 }
3549 } finally {
3550 Binder.restoreCallingIdentity(token);
3551 }
3552 }
3553
3554 /**
3555 * Try to place task to provided position. The final position might be different depending on
3556 * current user and stacks state. The task will be moved to target stack if it's currently in
3557 * different stack.
3558 */
3559 @Override
3560 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003561 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 synchronized (mGlobalLock) {
3563 long ident = Binder.clearCallingIdentity();
3564 try {
3565 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3566 + taskId + " in stackId=" + stackId + " at position=" + position);
3567 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3568 if (task == null) {
3569 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3570 + taskId);
3571 }
3572
3573 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3574
3575 if (stack == null) {
3576 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3577 + stackId);
3578 }
3579 if (!stack.isActivityTypeStandardOrUndefined()) {
3580 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3581 + " the position of task " + taskId + " in/to non-standard stack");
3582 }
3583
3584 // TODO: Have the callers of this API call a separate reparent method if that is
3585 // what they intended to do vs. having this method also do reparenting.
3586 if (task.getStack() == stack) {
3587 // Change position in current stack.
3588 stack.positionChildAt(task, position);
3589 } else {
3590 // Reparent to new stack.
3591 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3592 !DEFER_RESUME, "positionTaskInStack");
3593 }
3594 } finally {
3595 Binder.restoreCallingIdentity(ident);
3596 }
3597 }
3598 }
3599
3600 @Override
3601 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3602 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3603 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3604 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3605 synchronized (mGlobalLock) {
3606 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3607 if (record == null) {
3608 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3609 + "found for: " + token);
3610 }
3611 record.setSizeConfigurations(horizontalSizeConfiguration,
3612 verticalSizeConfigurations, smallestSizeConfigurations);
3613 }
3614 }
3615
3616 /**
3617 * Dismisses split-screen multi-window mode.
3618 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3619 */
3620 @Override
3621 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003622 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003623 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3624 final long ident = Binder.clearCallingIdentity();
3625 try {
3626 synchronized (mGlobalLock) {
3627 final ActivityStack stack =
3628 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3629 if (stack == null) {
3630 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3631 return;
3632 }
3633
3634 if (toTop) {
3635 // Caller wants the current split-screen primary stack to be the top stack after
3636 // it goes fullscreen, so move it to the front.
3637 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003638 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003639 // In this case the current split-screen primary stack shouldn't be the top
3640 // stack after it goes fullscreen, but it current has focus, so we move the
3641 // focus to the top-most split-screen secondary stack next to it.
3642 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3643 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3644 if (otherStack != null) {
3645 otherStack.moveToFront("dismissSplitScreenMode_other");
3646 }
3647 }
3648
Evan Rosky10475742018-09-05 19:02:48 -07003649 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 }
3651 } finally {
3652 Binder.restoreCallingIdentity(ident);
3653 }
3654 }
3655
3656 /**
3657 * Dismisses Pip
3658 * @param animate True if the dismissal should be animated.
3659 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3660 * default animation duration should be used.
3661 */
3662 @Override
3663 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003664 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003665 final long ident = Binder.clearCallingIdentity();
3666 try {
3667 synchronized (mGlobalLock) {
3668 final PinnedActivityStack stack =
3669 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3670 if (stack == null) {
3671 Slog.w(TAG, "dismissPip: pinned stack not found.");
3672 return;
3673 }
3674 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3675 throw new IllegalArgumentException("Stack: " + stack
3676 + " doesn't support animated resize.");
3677 }
3678 if (animate) {
3679 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3680 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3681 } else {
3682 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3683 }
3684 }
3685 } finally {
3686 Binder.restoreCallingIdentity(ident);
3687 }
3688 }
3689
3690 @Override
3691 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003692 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693 synchronized (mGlobalLock) {
3694 mSuppressResizeConfigChanges = suppress;
3695 }
3696 }
3697
3698 /**
3699 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3700 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3701 * activity and clearing the task at the same time.
3702 */
3703 @Override
3704 // TODO: API should just be about changing windowing modes...
3705 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003706 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003707 "moveTasksToFullscreenStack()");
3708 synchronized (mGlobalLock) {
3709 final long origId = Binder.clearCallingIdentity();
3710 try {
3711 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3712 if (stack != null){
3713 if (!stack.isActivityTypeStandardOrUndefined()) {
3714 throw new IllegalArgumentException(
3715 "You can't move tasks from non-standard stacks.");
3716 }
3717 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3718 }
3719 } finally {
3720 Binder.restoreCallingIdentity(origId);
3721 }
3722 }
3723 }
3724
3725 /**
3726 * Moves the top activity in the input stackId to the pinned stack.
3727 *
3728 * @param stackId Id of stack to move the top activity to pinned stack.
3729 * @param bounds Bounds to use for pinned stack.
3730 *
3731 * @return True if the top activity of the input stack was successfully moved to the pinned
3732 * stack.
3733 */
3734 @Override
3735 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003736 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003737 "moveTopActivityToPinnedStack()");
3738 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003739 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3741 + "Device doesn't support picture-in-picture mode");
3742 }
3743
3744 long ident = Binder.clearCallingIdentity();
3745 try {
3746 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3747 } finally {
3748 Binder.restoreCallingIdentity(ident);
3749 }
3750 }
3751 }
3752
3753 @Override
3754 public boolean isInMultiWindowMode(IBinder token) {
3755 final long origId = Binder.clearCallingIdentity();
3756 try {
3757 synchronized (mGlobalLock) {
3758 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3759 if (r == null) {
3760 return false;
3761 }
3762 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3763 return r.inMultiWindowMode();
3764 }
3765 } finally {
3766 Binder.restoreCallingIdentity(origId);
3767 }
3768 }
3769
3770 @Override
3771 public boolean isInPictureInPictureMode(IBinder token) {
3772 final long origId = Binder.clearCallingIdentity();
3773 try {
3774 synchronized (mGlobalLock) {
3775 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3776 }
3777 } finally {
3778 Binder.restoreCallingIdentity(origId);
3779 }
3780 }
3781
3782 private boolean isInPictureInPictureMode(ActivityRecord r) {
3783 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3784 || r.getStack().isInStackLocked(r) == null) {
3785 return false;
3786 }
3787
3788 // If we are animating to fullscreen then we have already dispatched the PIP mode
3789 // changed, so we should reflect that check here as well.
3790 final PinnedActivityStack stack = r.getStack();
3791 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3792 return !windowController.isAnimatingBoundsToFullscreen();
3793 }
3794
3795 @Override
3796 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3797 final long origId = Binder.clearCallingIdentity();
3798 try {
3799 synchronized (mGlobalLock) {
3800 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3801 "enterPictureInPictureMode", token, params);
3802
3803 // If the activity is already in picture in picture mode, then just return early
3804 if (isInPictureInPictureMode(r)) {
3805 return true;
3806 }
3807
3808 // Activity supports picture-in-picture, now check that we can enter PiP at this
3809 // point, if it is
3810 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3811 false /* beforeStopping */)) {
3812 return false;
3813 }
3814
3815 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003816 synchronized (mGlobalLock) {
3817 // Only update the saved args from the args that are set
3818 r.pictureInPictureArgs.copyOnlySet(params);
3819 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3820 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3821 // Adjust the source bounds by the insets for the transition down
3822 final Rect sourceBounds = new Rect(
3823 r.pictureInPictureArgs.getSourceRectHint());
3824 mStackSupervisor.moveActivityToPinnedStackLocked(
3825 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3826 final PinnedActivityStack stack = r.getStack();
3827 stack.setPictureInPictureAspectRatio(aspectRatio);
3828 stack.setPictureInPictureActions(actions);
3829 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3830 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3831 logPictureInPictureArgs(params);
3832 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 };
3834
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003835 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 // If the keyguard is showing or occluded, then try and dismiss it before
3837 // entering picture-in-picture (this will prompt the user to authenticate if the
3838 // device is currently locked).
3839 dismissKeyguard(token, new KeyguardDismissCallback() {
3840 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003841 public void onDismissSucceeded() {
3842 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 }
3844 }, null /* message */);
3845 } else {
3846 // Enter picture in picture immediately otherwise
3847 enterPipRunnable.run();
3848 }
3849 return true;
3850 }
3851 } finally {
3852 Binder.restoreCallingIdentity(origId);
3853 }
3854 }
3855
3856 @Override
3857 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3858 final long origId = Binder.clearCallingIdentity();
3859 try {
3860 synchronized (mGlobalLock) {
3861 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3862 "setPictureInPictureParams", token, params);
3863
3864 // Only update the saved args from the args that are set
3865 r.pictureInPictureArgs.copyOnlySet(params);
3866 if (r.inPinnedWindowingMode()) {
3867 // If the activity is already in picture-in-picture, update the pinned stack now
3868 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3869 // be used the next time the activity enters PiP
3870 final PinnedActivityStack stack = r.getStack();
3871 if (!stack.isAnimatingBoundsToFullscreen()) {
3872 stack.setPictureInPictureAspectRatio(
3873 r.pictureInPictureArgs.getAspectRatio());
3874 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3875 }
3876 }
3877 logPictureInPictureArgs(params);
3878 }
3879 } finally {
3880 Binder.restoreCallingIdentity(origId);
3881 }
3882 }
3883
3884 @Override
3885 public int getMaxNumPictureInPictureActions(IBinder token) {
3886 // Currently, this is a static constant, but later, we may change this to be dependent on
3887 // the context of the activity
3888 return 3;
3889 }
3890
3891 private void logPictureInPictureArgs(PictureInPictureParams params) {
3892 if (params.hasSetActions()) {
3893 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3894 params.getActions().size());
3895 }
3896 if (params.hasSetAspectRatio()) {
3897 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3898 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3899 MetricsLogger.action(lm);
3900 }
3901 }
3902
3903 /**
3904 * Checks the state of the system and the activity associated with the given {@param token} to
3905 * verify that picture-in-picture is supported for that activity.
3906 *
3907 * @return the activity record for the given {@param token} if all the checks pass.
3908 */
3909 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3910 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003911 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 throw new IllegalStateException(caller
3913 + ": Device doesn't support picture-in-picture mode.");
3914 }
3915
3916 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3917 if (r == null) {
3918 throw new IllegalStateException(caller
3919 + ": Can't find activity for token=" + token);
3920 }
3921
3922 if (!r.supportsPictureInPicture()) {
3923 throw new IllegalStateException(caller
3924 + ": Current activity does not support picture-in-picture.");
3925 }
3926
3927 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003928 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 params.getAspectRatio())) {
3930 final float minAspectRatio = mContext.getResources().getFloat(
3931 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3932 final float maxAspectRatio = mContext.getResources().getFloat(
3933 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3934 throw new IllegalArgumentException(String.format(caller
3935 + ": Aspect ratio is too extreme (must be between %f and %f).",
3936 minAspectRatio, maxAspectRatio));
3937 }
3938
3939 // Truncate the number of actions if necessary
3940 params.truncateActions(getMaxNumPictureInPictureActions(token));
3941
3942 return r;
3943 }
3944
3945 @Override
3946 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003947 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 synchronized (mGlobalLock) {
3949 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3950 if (r == null) {
3951 throw new IllegalArgumentException("Activity does not exist; token="
3952 + activityToken);
3953 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003954 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 }
3956 }
3957
3958 @Override
3959 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3960 Rect tempDockedTaskInsetBounds,
3961 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003962 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003963 long ident = Binder.clearCallingIdentity();
3964 try {
3965 synchronized (mGlobalLock) {
3966 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3967 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3968 PRESERVE_WINDOWS);
3969 }
3970 } finally {
3971 Binder.restoreCallingIdentity(ident);
3972 }
3973 }
3974
3975 @Override
3976 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003977 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 final long ident = Binder.clearCallingIdentity();
3979 try {
3980 synchronized (mGlobalLock) {
3981 mStackSupervisor.setSplitScreenResizing(resizing);
3982 }
3983 } finally {
3984 Binder.restoreCallingIdentity(ident);
3985 }
3986 }
3987
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003988 /**
3989 * Check that we have the features required for VR-related API calls, and throw an exception if
3990 * not.
3991 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003992 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003993 if (!mContext.getPackageManager().hasSystemFeature(
3994 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3995 throw new UnsupportedOperationException("VR mode not supported on this device!");
3996 }
3997 }
3998
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003999 @Override
4000 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004001 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002
4003 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4004
4005 ActivityRecord r;
4006 synchronized (mGlobalLock) {
4007 r = ActivityRecord.isInStackLocked(token);
4008 }
4009
4010 if (r == null) {
4011 throw new IllegalArgumentException();
4012 }
4013
4014 int err;
4015 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
4016 VrManagerInternal.NO_ERROR) {
4017 return err;
4018 }
4019
4020 // Clear the binder calling uid since this path may call moveToTask().
4021 final long callingId = Binder.clearCallingIdentity();
4022 try {
4023 synchronized (mGlobalLock) {
4024 r.requestedVrComponent = (enabled) ? packageName : null;
4025
4026 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004027 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004028 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 }
4030 return 0;
4031 }
4032 } finally {
4033 Binder.restoreCallingIdentity(callingId);
4034 }
4035 }
4036
4037 @Override
4038 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4039 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4040 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004041 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4043 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4044 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004045 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 || activity.voiceSession != null) {
4047 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4048 return;
4049 }
4050 if (activity.pendingVoiceInteractionStart) {
4051 Slog.w(TAG, "Pending start of voice interaction already.");
4052 return;
4053 }
4054 activity.pendingVoiceInteractionStart = true;
4055 }
4056 LocalServices.getService(VoiceInteractionManagerInternal.class)
4057 .startLocalVoiceInteraction(callingActivity, options);
4058 }
4059
4060 @Override
4061 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4062 LocalServices.getService(VoiceInteractionManagerInternal.class)
4063 .stopLocalVoiceInteraction(callingActivity);
4064 }
4065
4066 @Override
4067 public boolean supportsLocalVoiceInteraction() {
4068 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4069 .supportsLocalVoiceInteraction();
4070 }
4071
4072 /** Notifies all listeners when the pinned stack animation starts. */
4073 @Override
4074 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004075 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 }
4077
4078 /** Notifies all listeners when the pinned stack animation ends. */
4079 @Override
4080 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004081 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 }
4083
4084 @Override
4085 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004086 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004087 final long ident = Binder.clearCallingIdentity();
4088 try {
4089 synchronized (mGlobalLock) {
4090 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4091 }
4092 } finally {
4093 Binder.restoreCallingIdentity(ident);
4094 }
4095 }
4096
4097 @Override
4098 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004099 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004100
4101 synchronized (mGlobalLock) {
4102 // Check if display is initialized in AM.
4103 if (!mStackSupervisor.isDisplayAdded(displayId)) {
4104 // Call might come when display is not yet added or has already been removed.
4105 if (DEBUG_CONFIGURATION) {
4106 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4107 + displayId);
4108 }
4109 return false;
4110 }
4111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004112 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004114 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 }
4116
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004117 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004118 final Message msg = PooledLambda.obtainMessage(
4119 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4120 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 }
4122
4123 final long origId = Binder.clearCallingIdentity();
4124 try {
4125 if (values != null) {
4126 Settings.System.clearConfiguration(values);
4127 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004128 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4130 return mTmpUpdateConfigurationResult.changes != 0;
4131 } finally {
4132 Binder.restoreCallingIdentity(origId);
4133 }
4134 }
4135 }
4136
4137 @Override
4138 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004139 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140
4141 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004142 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004144 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004145 }
4146
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004148 final Message msg = PooledLambda.obtainMessage(
4149 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4150 DEFAULT_DISPLAY);
4151 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 }
4153
4154 final long origId = Binder.clearCallingIdentity();
4155 try {
4156 if (values != null) {
4157 Settings.System.clearConfiguration(values);
4158 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004159 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 UserHandle.USER_NULL, false /* deferResume */,
4161 mTmpUpdateConfigurationResult);
4162 return mTmpUpdateConfigurationResult.changes != 0;
4163 } finally {
4164 Binder.restoreCallingIdentity(origId);
4165 }
4166 }
4167 }
4168
4169 @Override
4170 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4171 CharSequence message) {
4172 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004173 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4175 }
4176 final long callingId = Binder.clearCallingIdentity();
4177 try {
4178 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004179 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 }
4181 } finally {
4182 Binder.restoreCallingIdentity(callingId);
4183 }
4184 }
4185
4186 @Override
4187 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 "cancelTaskWindowTransition()");
4190 final long ident = Binder.clearCallingIdentity();
4191 try {
4192 synchronized (mGlobalLock) {
4193 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4194 MATCH_TASK_IN_STACKS_ONLY);
4195 if (task == null) {
4196 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4197 return;
4198 }
4199 task.cancelWindowTransition();
4200 }
4201 } finally {
4202 Binder.restoreCallingIdentity(ident);
4203 }
4204 }
4205
4206 @Override
4207 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 final long ident = Binder.clearCallingIdentity();
4210 try {
4211 final TaskRecord task;
4212 synchronized (mGlobalLock) {
4213 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4214 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4215 if (task == null) {
4216 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4217 return null;
4218 }
4219 }
4220 // Don't call this while holding the lock as this operation might hit the disk.
4221 return task.getSnapshot(reducedResolution);
4222 } finally {
4223 Binder.restoreCallingIdentity(ident);
4224 }
4225 }
4226
4227 @Override
4228 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4229 synchronized (mGlobalLock) {
4230 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4231 if (r == null) {
4232 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4233 + token);
4234 return;
4235 }
4236 final long origId = Binder.clearCallingIdentity();
4237 try {
4238 r.setDisablePreviewScreenshots(disable);
4239 } finally {
4240 Binder.restoreCallingIdentity(origId);
4241 }
4242 }
4243 }
4244
4245 /** Return the user id of the last resumed activity. */
4246 @Override
4247 public @UserIdInt
4248 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004249 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4251 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004252 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004255 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 }
4257 }
4258
4259 @Override
4260 public void updateLockTaskFeatures(int userId, int flags) {
4261 final int callingUid = Binder.getCallingUid();
4262 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004263 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004264 "updateLockTaskFeatures()");
4265 }
4266 synchronized (mGlobalLock) {
4267 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4268 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004269 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004270 }
4271 }
4272
4273 @Override
4274 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4275 synchronized (mGlobalLock) {
4276 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4277 if (r == null) {
4278 return;
4279 }
4280 final long origId = Binder.clearCallingIdentity();
4281 try {
4282 r.setShowWhenLocked(showWhenLocked);
4283 } finally {
4284 Binder.restoreCallingIdentity(origId);
4285 }
4286 }
4287 }
4288
4289 @Override
4290 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4291 synchronized (mGlobalLock) {
4292 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4293 if (r == null) {
4294 return;
4295 }
4296 final long origId = Binder.clearCallingIdentity();
4297 try {
4298 r.setTurnScreenOn(turnScreenOn);
4299 } finally {
4300 Binder.restoreCallingIdentity(origId);
4301 }
4302 }
4303 }
4304
4305 @Override
4306 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004307 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 "registerRemoteAnimations");
4309 definition.setCallingPid(Binder.getCallingPid());
4310 synchronized (mGlobalLock) {
4311 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4312 if (r == null) {
4313 return;
4314 }
4315 final long origId = Binder.clearCallingIdentity();
4316 try {
4317 r.registerRemoteAnimations(definition);
4318 } finally {
4319 Binder.restoreCallingIdentity(origId);
4320 }
4321 }
4322 }
4323
4324 @Override
4325 public void registerRemoteAnimationForNextActivityStart(String packageName,
4326 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004327 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 "registerRemoteAnimationForNextActivityStart");
4329 adapter.setCallingPid(Binder.getCallingPid());
4330 synchronized (mGlobalLock) {
4331 final long origId = Binder.clearCallingIdentity();
4332 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004333 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 packageName, adapter);
4335 } finally {
4336 Binder.restoreCallingIdentity(origId);
4337 }
4338 }
4339 }
4340
4341 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4342 @Override
4343 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4344 synchronized (mGlobalLock) {
4345 final long origId = Binder.clearCallingIdentity();
4346 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004347 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 } finally {
4349 Binder.restoreCallingIdentity(origId);
4350 }
4351 }
4352 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004353
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004354 @Override
4355 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004356 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004357 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004358 final int pid = Binder.getCallingPid();
4359 final WindowProcessController wpc = mPidMap.get(pid);
4360 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004361 }
4362 }
4363
4364 @Override
4365 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004367 != PERMISSION_GRANTED) {
4368 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4369 + Binder.getCallingPid()
4370 + ", uid=" + Binder.getCallingUid()
4371 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4372 Slog.w(TAG, msg);
4373 throw new SecurityException(msg);
4374 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004376 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004377 final int pid = Binder.getCallingPid();
4378 final WindowProcessController proc = mPidMap.get(pid);
4379 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004380 }
4381 }
4382
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004383 @Override
4384 public void stopAppSwitches() {
4385 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4386 synchronized (mGlobalLock) {
4387 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4388 mDidAppSwitch = false;
4389 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4390 }
4391 }
4392
4393 @Override
4394 public void resumeAppSwitches() {
4395 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4396 synchronized (mGlobalLock) {
4397 // Note that we don't execute any pending app switches... we will
4398 // let those wait until either the timeout, or the next start
4399 // activity request.
4400 mAppSwitchesAllowedTime = 0;
4401 }
4402 }
4403
4404 void onStartActivitySetDidAppSwitch() {
4405 if (mDidAppSwitch) {
4406 // This is the second allowed switch since we stopped switches, so now just generally
4407 // allow switches. Use case:
4408 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4409 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4410 // anyone to switch again).
4411 mAppSwitchesAllowedTime = 0;
4412 } else {
4413 mDidAppSwitch = true;
4414 }
4415 }
4416
4417 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004418 boolean shouldDisableNonVrUiLocked() {
4419 return mVrController.shouldDisableNonVrUiLocked();
4420 }
4421
Wale Ogunwale53783742018-09-16 10:21:51 -07004422 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004423 // VR apps are expected to run in a main display. If an app is turning on VR for
4424 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4425 // fullscreen stack before enabling VR Mode.
4426 // TODO: The goal of this code is to keep the VR app on the main display. When the
4427 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4428 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4429 // option would be a better choice here.
4430 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4431 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4432 + " to main stack for VR");
4433 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4434 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4435 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4436 }
4437 mH.post(() -> {
4438 if (!mVrController.onVrModeChanged(r)) {
4439 return;
4440 }
4441 synchronized (mGlobalLock) {
4442 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4443 mWindowManager.disableNonVrUi(disableNonVrUi);
4444 if (disableNonVrUi) {
4445 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4446 // then remove the pinned stack.
4447 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4448 }
4449 }
4450 });
4451 }
4452
Wale Ogunwale53783742018-09-16 10:21:51 -07004453 @Override
4454 public int getPackageScreenCompatMode(String packageName) {
4455 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4456 synchronized (mGlobalLock) {
4457 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4458 }
4459 }
4460
4461 @Override
4462 public void setPackageScreenCompatMode(String packageName, int mode) {
4463 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4464 "setPackageScreenCompatMode");
4465 synchronized (mGlobalLock) {
4466 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4467 }
4468 }
4469
4470 @Override
4471 public boolean getPackageAskScreenCompat(String packageName) {
4472 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4473 synchronized (mGlobalLock) {
4474 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4475 }
4476 }
4477
4478 @Override
4479 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4480 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4481 "setPackageAskScreenCompat");
4482 synchronized (mGlobalLock) {
4483 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4484 }
4485 }
4486
Wale Ogunwale64258362018-10-16 15:13:37 -07004487 public static String relaunchReasonToString(int relaunchReason) {
4488 switch (relaunchReason) {
4489 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4490 return "window_resize";
4491 case RELAUNCH_REASON_FREE_RESIZE:
4492 return "free_resize";
4493 default:
4494 return null;
4495 }
4496 }
4497
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004498 ActivityStack getTopDisplayFocusedStack() {
4499 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 }
4501
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004502 /** Pokes the task persister. */
4503 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4504 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4505 }
4506
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004507 boolean isKeyguardLocked() {
4508 return mKeyguardController.isKeyguardLocked();
4509 }
4510
Wale Ogunwale31913b52018-10-13 08:29:31 -07004511 void dumpLastANRLocked(PrintWriter pw) {
4512 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4513 if (mLastANRState == null) {
4514 pw.println(" <no ANR has occurred since boot>");
4515 } else {
4516 pw.println(mLastANRState);
4517 }
4518 }
4519
4520 void dumpLastANRTracesLocked(PrintWriter pw) {
4521 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4522
4523 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4524 if (ArrayUtils.isEmpty(files)) {
4525 pw.println(" <no ANR has occurred since boot>");
4526 return;
4527 }
4528 // Find the latest file.
4529 File latest = null;
4530 for (File f : files) {
4531 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4532 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004533 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004534 }
4535 pw.print("File: ");
4536 pw.print(latest.getName());
4537 pw.println();
4538 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4539 String line;
4540 while ((line = in.readLine()) != null) {
4541 pw.println(line);
4542 }
4543 } catch (IOException e) {
4544 pw.print("Unable to read: ");
4545 pw.print(e);
4546 pw.println();
4547 }
4548 }
4549
4550 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4551 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4552 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4553 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4554 }
4555
4556 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4557 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4558 pw.println(header);
4559
4560 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4561 dumpPackage);
4562 boolean needSep = printedAnything;
4563
4564 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4565 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4566 " ResumedActivity: ");
4567 if (printed) {
4568 printedAnything = true;
4569 needSep = false;
4570 }
4571
4572 if (dumpPackage == null) {
4573 if (needSep) {
4574 pw.println();
4575 }
4576 printedAnything = true;
4577 mStackSupervisor.dump(pw, " ");
4578 }
4579
4580 if (!printedAnything) {
4581 pw.println(" (nothing)");
4582 }
4583 }
4584
4585 void dumpActivityContainersLocked(PrintWriter pw) {
4586 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4587 mStackSupervisor.dumpChildrenNames(pw, " ");
4588 pw.println(" ");
4589 }
4590
4591 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4592 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4593 getActivityStartController().dump(pw, "", dumpPackage);
4594 }
4595
4596 /**
4597 * There are three things that cmd can be:
4598 * - a flattened component name that matches an existing activity
4599 * - the cmd arg isn't the flattened component name of an existing activity:
4600 * dump all activity whose component contains the cmd as a substring
4601 * - A hex number of the ActivityRecord object instance.
4602 *
4603 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4604 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4605 */
4606 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4607 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4608 ArrayList<ActivityRecord> activities;
4609
4610 synchronized (mGlobalLock) {
4611 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4612 dumpFocusedStackOnly);
4613 }
4614
4615 if (activities.size() <= 0) {
4616 return false;
4617 }
4618
4619 String[] newArgs = new String[args.length - opti];
4620 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4621
4622 TaskRecord lastTask = null;
4623 boolean needSep = false;
4624 for (int i = activities.size() - 1; i >= 0; i--) {
4625 ActivityRecord r = activities.get(i);
4626 if (needSep) {
4627 pw.println();
4628 }
4629 needSep = true;
4630 synchronized (mGlobalLock) {
4631 final TaskRecord task = r.getTask();
4632 if (lastTask != task) {
4633 lastTask = task;
4634 pw.print("TASK "); pw.print(lastTask.affinity);
4635 pw.print(" id="); pw.print(lastTask.taskId);
4636 pw.print(" userId="); pw.println(lastTask.userId);
4637 if (dumpAll) {
4638 lastTask.dump(pw, " ");
4639 }
4640 }
4641 }
4642 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4643 }
4644 return true;
4645 }
4646
4647 /**
4648 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4649 * there is a thread associated with the activity.
4650 */
4651 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4652 final ActivityRecord r, String[] args, boolean dumpAll) {
4653 String innerPrefix = prefix + " ";
4654 synchronized (mGlobalLock) {
4655 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4656 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4657 pw.print(" pid=");
4658 if (r.hasProcess()) pw.println(r.app.getPid());
4659 else pw.println("(not running)");
4660 if (dumpAll) {
4661 r.dump(pw, innerPrefix);
4662 }
4663 }
4664 if (r.attachedToProcess()) {
4665 // flush anything that is already in the PrintWriter since the thread is going
4666 // to write to the file descriptor directly
4667 pw.flush();
4668 try {
4669 TransferPipe tp = new TransferPipe();
4670 try {
4671 r.app.getThread().dumpActivity(tp.getWriteFd(),
4672 r.appToken, innerPrefix, args);
4673 tp.go(fd);
4674 } finally {
4675 tp.kill();
4676 }
4677 } catch (IOException e) {
4678 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4679 } catch (RemoteException e) {
4680 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4681 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004682 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004683 }
4684
Wale Ogunwalef6733932018-06-27 05:14:34 -07004685 void writeSleepStateToProto(ProtoOutputStream proto) {
4686 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4687 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4688 st.toString());
4689 }
4690
4691 if (mRunningVoice != null) {
4692 final long vrToken = proto.start(
4693 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4694 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4695 mRunningVoice.toString());
4696 mVoiceWakeLock.writeToProto(
4697 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4698 proto.end(vrToken);
4699 }
4700
4701 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4702 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4703 mShuttingDown);
4704 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004705 }
4706
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004707 int getCurrentUserId() {
4708 return mAmInternal.getCurrentUserId();
4709 }
4710
4711 private void enforceNotIsolatedCaller(String caller) {
4712 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4713 throw new SecurityException("Isolated process not allowed to call " + caller);
4714 }
4715 }
4716
Wale Ogunwalef6733932018-06-27 05:14:34 -07004717 public Configuration getConfiguration() {
4718 Configuration ci;
4719 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004720 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004721 ci.userSetLocale = false;
4722 }
4723 return ci;
4724 }
4725
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004726 /**
4727 * Current global configuration information. Contains general settings for the entire system,
4728 * also corresponds to the merged configuration of the default display.
4729 */
4730 Configuration getGlobalConfiguration() {
4731 return mStackSupervisor.getConfiguration();
4732 }
4733
4734 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4735 boolean initLocale) {
4736 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4737 }
4738
4739 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4740 boolean initLocale, boolean deferResume) {
4741 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4742 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4743 UserHandle.USER_NULL, deferResume);
4744 }
4745
Wale Ogunwale59507092018-10-29 09:00:30 -07004746 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004747 final long origId = Binder.clearCallingIdentity();
4748 try {
4749 synchronized (mGlobalLock) {
4750 updateConfigurationLocked(values, null, false, true, userId,
4751 false /* deferResume */);
4752 }
4753 } finally {
4754 Binder.restoreCallingIdentity(origId);
4755 }
4756 }
4757
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004758 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4759 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4760 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4761 deferResume, null /* result */);
4762 }
4763
4764 /**
4765 * Do either or both things: (1) change the current configuration, and (2)
4766 * make sure the given activity is running with the (now) current
4767 * configuration. Returns true if the activity has been left running, or
4768 * false if <var>starting</var> is being destroyed to match the new
4769 * configuration.
4770 *
4771 * @param userId is only used when persistent parameter is set to true to persist configuration
4772 * for that particular user
4773 */
4774 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4775 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4776 ActivityTaskManagerService.UpdateConfigurationResult result) {
4777 int changes = 0;
4778 boolean kept = true;
4779
4780 if (mWindowManager != null) {
4781 mWindowManager.deferSurfaceLayout();
4782 }
4783 try {
4784 if (values != null) {
4785 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4786 deferResume);
4787 }
4788
4789 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4790 } finally {
4791 if (mWindowManager != null) {
4792 mWindowManager.continueSurfaceLayout();
4793 }
4794 }
4795
4796 if (result != null) {
4797 result.changes = changes;
4798 result.activityRelaunched = !kept;
4799 }
4800 return kept;
4801 }
4802
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004803 /** Update default (global) configuration and notify listeners about changes. */
4804 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4805 boolean persistent, int userId, boolean deferResume) {
4806 mTempConfig.setTo(getGlobalConfiguration());
4807 final int changes = mTempConfig.updateFrom(values);
4808 if (changes == 0) {
4809 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4810 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4811 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4812 // (even if there are no actual changes) to unfreeze the window.
4813 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4814 return 0;
4815 }
4816
4817 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4818 "Updating global configuration to: " + values);
4819
4820 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4821 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4822 values.colorMode,
4823 values.densityDpi,
4824 values.fontScale,
4825 values.hardKeyboardHidden,
4826 values.keyboard,
4827 values.keyboardHidden,
4828 values.mcc,
4829 values.mnc,
4830 values.navigation,
4831 values.navigationHidden,
4832 values.orientation,
4833 values.screenHeightDp,
4834 values.screenLayout,
4835 values.screenWidthDp,
4836 values.smallestScreenWidthDp,
4837 values.touchscreen,
4838 values.uiMode);
4839
4840
4841 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4842 final LocaleList locales = values.getLocales();
4843 int bestLocaleIndex = 0;
4844 if (locales.size() > 1) {
4845 if (mSupportedSystemLocales == null) {
4846 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4847 }
4848 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4849 }
4850 SystemProperties.set("persist.sys.locale",
4851 locales.get(bestLocaleIndex).toLanguageTag());
4852 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004853
4854 final Message m = PooledLambda.obtainMessage(
4855 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4856 locales.get(bestLocaleIndex));
4857 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004858 }
4859
Yunfan Chen75157d72018-07-27 14:47:21 +09004860 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004861
4862 // Update stored global config and notify everyone about the change.
4863 mStackSupervisor.onConfigurationChanged(mTempConfig);
4864
4865 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4866 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004867 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004868
4869 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004870 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004871
4872 AttributeCache ac = AttributeCache.instance();
4873 if (ac != null) {
4874 ac.updateConfiguration(mTempConfig);
4875 }
4876
4877 // Make sure all resources in our process are updated right now, so that anyone who is going
4878 // to retrieve resource values after we return will be sure to get the new ones. This is
4879 // especially important during boot, where the first config change needs to guarantee all
4880 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004881 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004882
4883 // We need another copy of global config because we're scheduling some calls instead of
4884 // running them in place. We need to be sure that object we send will be handled unchanged.
4885 final Configuration configCopy = new Configuration(mTempConfig);
4886 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004887 final Message msg = PooledLambda.obtainMessage(
4888 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4889 this, userId, configCopy);
4890 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004891 }
4892
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004893 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004894 final int pid = mPidMap.keyAt(i);
4895 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004896 if (DEBUG_CONFIGURATION) {
4897 Slog.v(TAG_CONFIGURATION, "Update process config of "
4898 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004899 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004900 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004901 }
4902
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004903 final Message msg = PooledLambda.obtainMessage(
4904 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4905 mAmInternal, changes, initLocale);
4906 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004907
4908 // Override configuration of the default display duplicates global config, so we need to
4909 // update it also. This will also notify WindowManager about changes.
4910 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4911 DEFAULT_DISPLAY);
4912
4913 return changes;
4914 }
4915
4916 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4917 boolean deferResume, int displayId) {
4918 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4919 displayId, null /* result */);
4920 }
4921
4922 /**
4923 * Updates override configuration specific for the selected display. If no config is provided,
4924 * new one will be computed in WM based on current display info.
4925 */
4926 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4927 ActivityRecord starting, boolean deferResume, int displayId,
4928 ActivityTaskManagerService.UpdateConfigurationResult result) {
4929 int changes = 0;
4930 boolean kept = true;
4931
4932 if (mWindowManager != null) {
4933 mWindowManager.deferSurfaceLayout();
4934 }
4935 try {
4936 if (values != null) {
4937 if (displayId == DEFAULT_DISPLAY) {
4938 // Override configuration of the default display duplicates global config, so
4939 // we're calling global config update instead for default display. It will also
4940 // apply the correct override config.
4941 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4942 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4943 } else {
4944 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4945 }
4946 }
4947
4948 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4949 } finally {
4950 if (mWindowManager != null) {
4951 mWindowManager.continueSurfaceLayout();
4952 }
4953 }
4954
4955 if (result != null) {
4956 result.changes = changes;
4957 result.activityRelaunched = !kept;
4958 }
4959 return kept;
4960 }
4961
4962 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4963 int displayId) {
4964 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4965 final int changes = mTempConfig.updateFrom(values);
4966 if (changes != 0) {
4967 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4968 + mTempConfig + " for displayId=" + displayId);
4969 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4970
4971 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4972 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004973 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004974
Wale Ogunwale5c918702018-10-18 11:06:33 -07004975 // Post message to start process to avoid possible deadlock of calling into AMS with
4976 // the ATMS lock held.
4977 final Message msg = PooledLambda.obtainMessage(
4978 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4979 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4980 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004981 }
4982 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004983 return changes;
4984 }
4985
Wale Ogunwalef6733932018-06-27 05:14:34 -07004986 private void updateEventDispatchingLocked(boolean booted) {
4987 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4988 }
4989
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004990 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4991 final ContentResolver resolver = mContext.getContentResolver();
4992 Settings.System.putConfigurationForUser(resolver, config, userId);
4993 }
4994
4995 private void sendLocaleToMountDaemonMsg(Locale l) {
4996 try {
4997 IBinder service = ServiceManager.getService("mount");
4998 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
4999 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5000 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5001 } catch (RemoteException e) {
5002 Log.e(TAG, "Error storing locale for decryption UI", e);
5003 }
5004 }
5005
Alison Cichowlas3e340502018-08-07 17:15:01 -04005006 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5007 mStartActivitySources.remove(permissionToken);
5008 mExpiredStartAsCallerTokens.add(permissionToken);
5009 }
5010
5011 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5012 mExpiredStartAsCallerTokens.remove(permissionToken);
5013 }
5014
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005015 boolean isActivityStartsLoggingEnabled() {
5016 return mAmInternal.isActivityStartsLoggingEnabled();
5017 }
5018
Wale Ogunwalef6733932018-06-27 05:14:34 -07005019 void enableScreenAfterBoot(boolean booted) {
5020 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5021 SystemClock.uptimeMillis());
5022 mWindowManager.enableScreenAfterBoot();
5023
5024 synchronized (mGlobalLock) {
5025 updateEventDispatchingLocked(booted);
5026 }
5027 }
5028
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005029 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5030 if (r == null || !r.hasProcess()) {
5031 return KEY_DISPATCHING_TIMEOUT_MS;
5032 }
5033 return getInputDispatchingTimeoutLocked(r.app);
5034 }
5035
5036 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005037 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005038 }
5039
Wale Ogunwalef6733932018-06-27 05:14:34 -07005040 /**
5041 * Decide based on the configuration whether we should show the ANR,
5042 * crash, etc dialogs. The idea is that if there is no affordance to
5043 * press the on-screen buttons, or the user experience would be more
5044 * greatly impacted than the crash itself, we shouldn't show the dialog.
5045 *
5046 * A thought: SystemUI might also want to get told about this, the Power
5047 * dialog / global actions also might want different behaviors.
5048 */
5049 private void updateShouldShowDialogsLocked(Configuration config) {
5050 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5051 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5052 && config.navigation == Configuration.NAVIGATION_NONAV);
5053 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5054 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5055 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5056 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5057 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5058 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5059 HIDE_ERROR_DIALOGS, 0) != 0;
5060 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5061 }
5062
5063 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5064 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5065 FONT_SCALE, 1.0f, userId);
5066
5067 synchronized (this) {
5068 if (getGlobalConfiguration().fontScale == scaleFactor) {
5069 return;
5070 }
5071
5072 final Configuration configuration
5073 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5074 configuration.fontScale = scaleFactor;
5075 updatePersistentConfiguration(configuration, userId);
5076 }
5077 }
5078
5079 // Actually is sleeping or shutting down or whatever else in the future
5080 // is an inactive state.
5081 boolean isSleepingOrShuttingDownLocked() {
5082 return isSleepingLocked() || mShuttingDown;
5083 }
5084
5085 boolean isSleepingLocked() {
5086 return mSleeping;
5087 }
5088
Riddle Hsu16567132018-08-16 21:37:47 +08005089 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005090 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
5091 final TaskRecord task = r.getTask();
5092 if (task.isActivityTypeStandard()) {
5093 if (mCurAppTimeTracker != r.appTimeTracker) {
5094 // We are switching app tracking. Complete the current one.
5095 if (mCurAppTimeTracker != null) {
5096 mCurAppTimeTracker.stop();
5097 mH.obtainMessage(
5098 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
5099 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
5100 mCurAppTimeTracker = null;
5101 }
5102 if (r.appTimeTracker != null) {
5103 mCurAppTimeTracker = r.appTimeTracker;
5104 startTimeTrackingFocusedActivityLocked();
5105 }
5106 } else {
5107 startTimeTrackingFocusedActivityLocked();
5108 }
5109 } else {
5110 r.appTimeTracker = null;
5111 }
5112 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5113 // TODO: Probably not, because we don't want to resume voice on switching
5114 // back to this activity
5115 if (task.voiceInteractor != null) {
5116 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5117 } else {
5118 finishRunningVoiceLocked();
5119
5120 if (mLastResumedActivity != null) {
5121 final IVoiceInteractionSession session;
5122
5123 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5124 if (lastResumedActivityTask != null
5125 && lastResumedActivityTask.voiceSession != null) {
5126 session = lastResumedActivityTask.voiceSession;
5127 } else {
5128 session = mLastResumedActivity.voiceSession;
5129 }
5130
5131 if (session != null) {
5132 // We had been in a voice interaction session, but now focused has
5133 // move to something different. Just finish the session, we can't
5134 // return to it and retain the proper state and synchronization with
5135 // the voice interaction service.
5136 finishVoiceTask(session);
5137 }
5138 }
5139 }
5140
5141 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5142 mAmInternal.sendForegroundProfileChanged(r.userId);
5143 }
5144 updateResumedAppTrace(r);
5145 mLastResumedActivity = r;
5146
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005147 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005148
5149 applyUpdateLockStateLocked(r);
5150 applyUpdateVrModeLocked(r);
5151
5152 EventLogTags.writeAmSetResumedActivity(
5153 r == null ? -1 : r.userId,
5154 r == null ? "NULL" : r.shortComponentName,
5155 reason);
5156 }
5157
5158 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5159 synchronized (mGlobalLock) {
5160 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5161 updateSleepIfNeededLocked();
5162 return token;
5163 }
5164 }
5165
5166 void updateSleepIfNeededLocked() {
5167 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5168 final boolean wasSleeping = mSleeping;
5169 boolean updateOomAdj = false;
5170
5171 if (!shouldSleep) {
5172 // If wasSleeping is true, we need to wake up activity manager state from when
5173 // we started sleeping. In either case, we need to apply the sleep tokens, which
5174 // will wake up stacks or put them to sleep as appropriate.
5175 if (wasSleeping) {
5176 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005177 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5178 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005179 startTimeTrackingFocusedActivityLocked();
5180 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5181 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5182 }
5183 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5184 if (wasSleeping) {
5185 updateOomAdj = true;
5186 }
5187 } else if (!mSleeping && shouldSleep) {
5188 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005189 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5190 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005191 if (mCurAppTimeTracker != null) {
5192 mCurAppTimeTracker.stop();
5193 }
5194 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5195 mStackSupervisor.goingToSleepLocked();
5196 updateResumedAppTrace(null /* resumed */);
5197 updateOomAdj = true;
5198 }
5199 if (updateOomAdj) {
5200 mH.post(mAmInternal::updateOomAdj);
5201 }
5202 }
5203
5204 void updateOomAdj() {
5205 mH.post(mAmInternal::updateOomAdj);
5206 }
5207
Wale Ogunwale53783742018-09-16 10:21:51 -07005208 void updateCpuStats() {
5209 mH.post(mAmInternal::updateCpuStats);
5210 }
5211
5212 void updateUsageStats(ActivityRecord component, boolean resumed) {
5213 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5214 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5215 mH.sendMessage(m);
5216 }
5217
5218 void setBooting(boolean booting) {
5219 mAmInternal.setBooting(booting);
5220 }
5221
5222 boolean isBooting() {
5223 return mAmInternal.isBooting();
5224 }
5225
5226 void setBooted(boolean booted) {
5227 mAmInternal.setBooted(booted);
5228 }
5229
5230 boolean isBooted() {
5231 return mAmInternal.isBooted();
5232 }
5233
5234 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5235 mH.post(() -> {
5236 if (finishBooting) {
5237 mAmInternal.finishBooting();
5238 }
5239 if (enableScreen) {
5240 mInternal.enableScreenAfterBoot(isBooted());
5241 }
5242 });
5243 }
5244
5245 void setHeavyWeightProcess(ActivityRecord root) {
5246 mHeavyWeightProcess = root.app;
5247 final Message m = PooledLambda.obtainMessage(
5248 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5249 root.app, root.intent, root.userId);
5250 mH.sendMessage(m);
5251 }
5252
5253 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5254 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5255 return;
5256 }
5257
5258 mHeavyWeightProcess = null;
5259 final Message m = PooledLambda.obtainMessage(
5260 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5261 proc.mUserId);
5262 mH.sendMessage(m);
5263 }
5264
5265 private void cancelHeavyWeightProcessNotification(int userId) {
5266 final INotificationManager inm = NotificationManager.getService();
5267 if (inm == null) {
5268 return;
5269 }
5270 try {
5271 inm.cancelNotificationWithTag("android", null,
5272 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5273 } catch (RuntimeException e) {
5274 Slog.w(TAG, "Error canceling notification for service", e);
5275 } catch (RemoteException e) {
5276 }
5277
5278 }
5279
5280 private void postHeavyWeightProcessNotification(
5281 WindowProcessController proc, Intent intent, int userId) {
5282 if (proc == null) {
5283 return;
5284 }
5285
5286 final INotificationManager inm = NotificationManager.getService();
5287 if (inm == null) {
5288 return;
5289 }
5290
5291 try {
5292 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5293 String text = mContext.getString(R.string.heavy_weight_notification,
5294 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5295 Notification notification =
5296 new Notification.Builder(context,
5297 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5298 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5299 .setWhen(0)
5300 .setOngoing(true)
5301 .setTicker(text)
5302 .setColor(mContext.getColor(
5303 com.android.internal.R.color.system_notification_accent_color))
5304 .setContentTitle(text)
5305 .setContentText(
5306 mContext.getText(R.string.heavy_weight_notification_detail))
5307 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5308 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5309 new UserHandle(userId)))
5310 .build();
5311 try {
5312 inm.enqueueNotificationWithTag("android", "android", null,
5313 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5314 } catch (RuntimeException e) {
5315 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5316 } catch (RemoteException e) {
5317 }
5318 } catch (PackageManager.NameNotFoundException e) {
5319 Slog.w(TAG, "Unable to create context for heavy notification", e);
5320 }
5321
5322 }
5323
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005324 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5325 IBinder token, String resultWho, int requestCode, Intent[] intents,
5326 String[] resolvedTypes, int flags, Bundle bOptions) {
5327
5328 ActivityRecord activity = null;
5329 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5330 activity = ActivityRecord.isInStackLocked(token);
5331 if (activity == null) {
5332 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5333 return null;
5334 }
5335 if (activity.finishing) {
5336 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5337 return null;
5338 }
5339 }
5340
5341 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5342 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5343 bOptions);
5344 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5345 if (noCreate) {
5346 return rec;
5347 }
5348 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5349 if (activity.pendingResults == null) {
5350 activity.pendingResults = new HashSet<>();
5351 }
5352 activity.pendingResults.add(rec.ref);
5353 }
5354 return rec;
5355 }
5356
Andrii Kulian52d255c2018-07-13 11:32:19 -07005357 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005359 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5361 mCurAppTimeTracker.start(resumedActivity.packageName);
5362 }
5363 }
5364
5365 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5366 if (mTracedResumedActivity != null) {
5367 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5368 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5369 }
5370 if (resumed != null) {
5371 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5372 constructResumedTraceName(resumed.packageName), 0);
5373 }
5374 mTracedResumedActivity = resumed;
5375 }
5376
5377 private String constructResumedTraceName(String packageName) {
5378 return "focused app: " + packageName;
5379 }
5380
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005381 /** Applies latest configuration and/or visibility updates if needed. */
5382 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5383 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005384 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005385 // mainStack is null during startup.
5386 if (mainStack != null) {
5387 if (changes != 0 && starting == null) {
5388 // If the configuration changed, and the caller is not already
5389 // in the process of starting an activity, then find the top
5390 // activity to check if its configuration needs to change.
5391 starting = mainStack.topRunningActivityLocked();
5392 }
5393
5394 if (starting != null) {
5395 kept = starting.ensureActivityConfiguration(changes,
5396 false /* preserveWindow */);
5397 // And we need to make sure at this point that all other activities
5398 // are made visible with the correct configuration.
5399 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5400 !PRESERVE_WINDOWS);
5401 }
5402 }
5403
5404 return kept;
5405 }
5406
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005407 void scheduleAppGcsLocked() {
5408 mH.post(() -> mAmInternal.scheduleAppGcs());
5409 }
5410
Wale Ogunwale53783742018-09-16 10:21:51 -07005411 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5412 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5413 }
5414
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005415 /**
5416 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5417 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5418 * on demand.
5419 */
5420 IPackageManager getPackageManager() {
5421 return AppGlobals.getPackageManager();
5422 }
5423
5424 PackageManagerInternal getPackageManagerInternalLocked() {
5425 if (mPmInternal == null) {
5426 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5427 }
5428 return mPmInternal;
5429 }
5430
Wale Ogunwale008163e2018-07-23 23:11:08 -07005431 AppWarnings getAppWarningsLocked() {
5432 return mAppWarnings;
5433 }
5434
Wale Ogunwale214f3482018-10-04 11:00:47 -07005435 Intent getHomeIntent() {
5436 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5437 intent.setComponent(mTopComponent);
5438 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5439 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5440 intent.addCategory(Intent.CATEGORY_HOME);
5441 }
5442 return intent;
5443 }
5444
Wale Ogunwale214f3482018-10-04 11:00:47 -07005445 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5446 if (info == null) return null;
5447 ApplicationInfo newInfo = new ApplicationInfo(info);
5448 newInfo.initForUser(userId);
5449 return newInfo;
5450 }
5451
Wale Ogunwale9c103022018-10-18 07:44:54 -07005452 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005453 if (uid == SYSTEM_UID) {
5454 // The system gets to run in any process. If there are multiple processes with the same
5455 // uid, just pick the first (this should never happen).
5456 final SparseArray<WindowProcessController> procs =
5457 mProcessNames.getMap().get(processName);
5458 if (procs == null) return null;
5459 final int procCount = procs.size();
5460 for (int i = 0; i < procCount; i++) {
5461 final int procUid = procs.keyAt(i);
5462 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5463 // Don't use an app process or different user process for system component.
5464 continue;
5465 }
5466 return procs.valueAt(i);
5467 }
5468 }
5469
5470 return mProcessNames.get(processName, uid);
5471 }
5472
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005473 WindowProcessController getProcessController(IApplicationThread thread) {
5474 if (thread == null) {
5475 return null;
5476 }
5477
5478 final IBinder threadBinder = thread.asBinder();
5479 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5480 for (int i = pmap.size()-1; i >= 0; i--) {
5481 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5482 for (int j = procs.size() - 1; j >= 0; j--) {
5483 final WindowProcessController proc = procs.valueAt(j);
5484 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5485 return proc;
5486 }
5487 }
5488 }
5489
5490 return null;
5491 }
5492
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005493 int getUidStateLocked(int uid) {
5494 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5495 }
5496
Wale Ogunwale9de19442018-10-18 19:05:03 -07005497 /**
5498 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5499 * the whitelist
5500 */
5501 String getPendingTempWhitelistTagForUidLocked(int uid) {
5502 return mPendingTempWhitelist.get(uid);
5503 }
5504
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005505 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5506 if (true || Build.IS_USER) {
5507 return;
5508 }
5509
5510 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5511 StrictMode.allowThreadDiskWrites();
5512 try {
5513 File tracesDir = new File("/data/anr");
5514 File tracesFile = null;
5515 try {
5516 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5517
5518 StringBuilder sb = new StringBuilder();
5519 Time tobj = new Time();
5520 tobj.set(System.currentTimeMillis());
5521 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5522 sb.append(": ");
5523 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5524 sb.append(" since ");
5525 sb.append(msg);
5526 FileOutputStream fos = new FileOutputStream(tracesFile);
5527 fos.write(sb.toString().getBytes());
5528 if (app == null) {
5529 fos.write("\n*** No application process!".getBytes());
5530 }
5531 fos.close();
5532 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5533 } catch (IOException e) {
5534 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5535 return;
5536 }
5537
5538 if (app != null && app.getPid() > 0) {
5539 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5540 firstPids.add(app.getPid());
5541 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5542 }
5543
5544 File lastTracesFile = null;
5545 File curTracesFile = null;
5546 for (int i=9; i>=0; i--) {
5547 String name = String.format(Locale.US, "slow%02d.txt", i);
5548 curTracesFile = new File(tracesDir, name);
5549 if (curTracesFile.exists()) {
5550 if (lastTracesFile != null) {
5551 curTracesFile.renameTo(lastTracesFile);
5552 } else {
5553 curTracesFile.delete();
5554 }
5555 }
5556 lastTracesFile = curTracesFile;
5557 }
5558 tracesFile.renameTo(curTracesFile);
5559 } finally {
5560 StrictMode.setThreadPolicy(oldPolicy);
5561 }
5562 }
5563
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005564 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005565 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005566
5567
Wale Ogunwale98875612018-10-12 07:53:02 -07005568 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5569 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005571 public H() {
5572 super(DisplayThread.get().getLooper());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005573 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574
5575 @Override
5576 public void handleMessage(Message msg) {
5577 switch (msg.what) {
5578 case REPORT_TIME_TRACKER_MSG: {
5579 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5580 tracker.deliverResult(mContext);
5581 } break;
5582 }
5583 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005584 }
5585
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005586 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005587 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005588
5589 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005590 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005591 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592
5593 @Override
5594 public void handleMessage(Message msg) {
5595 switch (msg.what) {
5596 case DISMISS_DIALOG_UI_MSG: {
5597 final Dialog d = (Dialog) msg.obj;
5598 d.dismiss();
5599 break;
5600 }
5601 }
5602 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005603 }
5604
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005605 final class LocalService extends ActivityTaskManagerInternal {
5606 @Override
5607 public SleepToken acquireSleepToken(String tag, int displayId) {
5608 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005609 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005610 }
5611
5612 @Override
5613 public ComponentName getHomeActivityForUser(int userId) {
5614 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005615 ActivityRecord homeActivity =
5616 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005617 return homeActivity == null ? null : homeActivity.realActivity;
5618 }
5619 }
5620
5621 @Override
5622 public void onLocalVoiceInteractionStarted(IBinder activity,
5623 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5624 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005625 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005626 }
5627 }
5628
5629 @Override
5630 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5631 synchronized (mGlobalLock) {
5632 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5633 reasons, timestamp);
5634 }
5635 }
5636
5637 @Override
5638 public void notifyAppTransitionFinished() {
5639 synchronized (mGlobalLock) {
5640 mStackSupervisor.notifyAppTransitionDone();
5641 }
5642 }
5643
5644 @Override
5645 public void notifyAppTransitionCancelled() {
5646 synchronized (mGlobalLock) {
5647 mStackSupervisor.notifyAppTransitionDone();
5648 }
5649 }
5650
5651 @Override
5652 public List<IBinder> getTopVisibleActivities() {
5653 synchronized (mGlobalLock) {
5654 return mStackSupervisor.getTopVisibleActivities();
5655 }
5656 }
5657
5658 @Override
5659 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5660 synchronized (mGlobalLock) {
5661 mStackSupervisor.setDockedStackMinimized(minimized);
5662 }
5663 }
5664
5665 @Override
5666 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5667 Bundle bOptions) {
5668 Preconditions.checkNotNull(intents, "intents");
5669 final String[] resolvedTypes = new String[intents.length];
5670
5671 // UID of the package on user userId.
5672 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5673 // packageUid may not be initialized.
5674 int packageUid = 0;
5675 final long ident = Binder.clearCallingIdentity();
5676
5677 try {
5678 for (int i = 0; i < intents.length; i++) {
5679 resolvedTypes[i] =
5680 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5681 }
5682
5683 packageUid = AppGlobals.getPackageManager().getPackageUid(
5684 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5685 } catch (RemoteException e) {
5686 // Shouldn't happen.
5687 } finally {
5688 Binder.restoreCallingIdentity(ident);
5689 }
5690
5691 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005692 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005693 packageUid, packageName,
5694 intents, resolvedTypes, null /* resultTo */,
5695 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005696 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005697 }
5698 }
5699
5700 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005701 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5702 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5703 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5704 synchronized (mGlobalLock) {
5705 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5706 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5707 originatingPendingIntent);
5708 }
5709 }
5710
5711 @Override
5712 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5713 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5714 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5715 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5716 PendingIntentRecord originatingPendingIntent) {
5717 synchronized (mGlobalLock) {
5718 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5719 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5720 requestCode, startFlags, options, userId, inTask, reason,
5721 validateIncomingUser, originatingPendingIntent);
5722 }
5723 }
5724
5725 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005726 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5727 Intent intent, Bundle options, int userId) {
5728 return ActivityTaskManagerService.this.startActivityAsUser(
5729 caller, callerPacakge, intent,
5730 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5731 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5732 false /*validateIncomingUser*/);
5733 }
5734
5735 @Override
lumark588a3e82018-07-20 18:53:54 +08005736 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005737 synchronized (mGlobalLock) {
5738
5739 // We might change the visibilities here, so prepare an empty app transition which
5740 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005741 final ActivityDisplay activityDisplay =
5742 mStackSupervisor.getActivityDisplay(displayId);
5743 if (activityDisplay == null) {
5744 return;
5745 }
5746 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005747 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005748 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005749 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005750 }
5751 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5752
5753 // If there was a transition set already we don't want to interfere with it as we
5754 // might be starting it too early.
5755 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005756 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005757 }
5758 }
5759 if (callback != null) {
5760 callback.run();
5761 }
5762 }
5763
5764 @Override
5765 public void notifyKeyguardTrustedChanged() {
5766 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005767 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005768 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5769 }
5770 }
5771 }
5772
5773 /**
5774 * Called after virtual display Id is updated by
5775 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5776 * {@param vrVr2dDisplayId}.
5777 */
5778 @Override
5779 public void setVr2dDisplayId(int vr2dDisplayId) {
5780 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5781 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005782 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005783 }
5784 }
5785
5786 @Override
5787 public void setFocusedActivity(IBinder token) {
5788 synchronized (mGlobalLock) {
5789 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5790 if (r == null) {
5791 throw new IllegalArgumentException(
5792 "setFocusedActivity: No activity record matching token=" + token);
5793 }
Louis Chang19443452018-10-09 12:10:21 +08005794 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005795 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005796 }
5797 }
5798 }
5799
5800 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005801 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005802 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005803 }
5804
5805 @Override
5806 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005807 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005808 }
5809
5810 @Override
5811 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005812 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005813 }
5814
5815 @Override
5816 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5817 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5818 }
5819
5820 @Override
5821 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005823 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005824
5825 @Override
5826 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5827 synchronized (mGlobalLock) {
5828 mActiveVoiceInteractionServiceComponent = component;
5829 }
5830 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005831
5832 @Override
5833 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5834 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5835 return;
5836 }
5837 synchronized (mGlobalLock) {
5838 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5839 if (types == null) {
5840 if (uid < 0) {
5841 return;
5842 }
5843 types = new ArrayMap<>();
5844 mAllowAppSwitchUids.put(userId, types);
5845 }
5846 if (uid < 0) {
5847 types.remove(type);
5848 } else {
5849 types.put(type, uid);
5850 }
5851 }
5852 }
5853
5854 @Override
5855 public void onUserStopped(int userId) {
5856 synchronized (mGlobalLock) {
5857 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5858 mAllowAppSwitchUids.remove(userId);
5859 }
5860 }
5861
5862 @Override
5863 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5864 synchronized (mGlobalLock) {
5865 return ActivityTaskManagerService.this.isGetTasksAllowed(
5866 caller, callingPid, callingUid);
5867 }
5868 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005869
5870 @Override
5871 public void onProcessAdded(WindowProcessController proc) {
5872 synchronized (mGlobalLock) {
5873 mProcessNames.put(proc.mName, proc.mUid, proc);
5874 }
5875 }
5876
5877 @Override
5878 public void onProcessRemoved(String name, int uid) {
5879 synchronized (mGlobalLock) {
5880 mProcessNames.remove(name, uid);
5881 }
5882 }
5883
5884 @Override
5885 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5886 synchronized (mGlobalLock) {
5887 if (proc == mHomeProcess) {
5888 mHomeProcess = null;
5889 }
5890 if (proc == mPreviousProcess) {
5891 mPreviousProcess = null;
5892 }
5893 }
5894 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005895
5896 @Override
5897 public int getTopProcessState() {
5898 synchronized (mGlobalLock) {
5899 return mTopProcessState;
5900 }
5901 }
5902
5903 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005904 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5905 synchronized (mGlobalLock) {
5906 return proc == mHeavyWeightProcess;
5907 }
5908 }
5909
5910 @Override
5911 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5912 synchronized (mGlobalLock) {
5913 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5914 }
5915 }
5916
5917 @Override
5918 public void finishHeavyWeightApp() {
5919 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005920 if (mHeavyWeightProcess != null) {
5921 mHeavyWeightProcess.finishActivities();
5922 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005923 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5924 mHeavyWeightProcess);
5925 }
5926 }
5927
5928 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005929 public boolean isSleeping() {
5930 synchronized (mGlobalLock) {
5931 return isSleepingLocked();
5932 }
5933 }
5934
5935 @Override
5936 public boolean isShuttingDown() {
5937 synchronized (mGlobalLock) {
5938 return mShuttingDown;
5939 }
5940 }
5941
5942 @Override
5943 public boolean shuttingDown(boolean booted, int timeout) {
5944 synchronized (mGlobalLock) {
5945 mShuttingDown = true;
5946 mStackSupervisor.prepareForShutdownLocked();
5947 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005948 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005949 return mStackSupervisor.shutdownLocked(timeout);
5950 }
5951 }
5952
5953 @Override
5954 public void enableScreenAfterBoot(boolean booted) {
5955 synchronized (mGlobalLock) {
5956 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5957 SystemClock.uptimeMillis());
5958 mWindowManager.enableScreenAfterBoot();
5959 updateEventDispatchingLocked(booted);
5960 }
5961 }
5962
5963 @Override
5964 public boolean showStrictModeViolationDialog() {
5965 synchronized (mGlobalLock) {
5966 return mShowDialogs && !mSleeping && !mShuttingDown;
5967 }
5968 }
5969
5970 @Override
5971 public void showSystemReadyErrorDialogsIfNeeded() {
5972 synchronized (mGlobalLock) {
5973 try {
5974 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5975 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5976 + " data partition or your device will be unstable.");
5977 mUiHandler.post(() -> {
5978 if (mShowDialogs) {
5979 AlertDialog d = new BaseErrorDialog(mUiContext);
5980 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5981 d.setCancelable(false);
5982 d.setTitle(mUiContext.getText(R.string.android_system_label));
5983 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5984 d.setButton(DialogInterface.BUTTON_POSITIVE,
5985 mUiContext.getText(R.string.ok),
5986 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5987 d.show();
5988 }
5989 });
5990 }
5991 } catch (RemoteException e) {
5992 }
5993
5994 if (!Build.isBuildConsistent()) {
5995 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5996 mUiHandler.post(() -> {
5997 if (mShowDialogs) {
5998 AlertDialog d = new BaseErrorDialog(mUiContext);
5999 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6000 d.setCancelable(false);
6001 d.setTitle(mUiContext.getText(R.string.android_system_label));
6002 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6003 d.setButton(DialogInterface.BUTTON_POSITIVE,
6004 mUiContext.getText(R.string.ok),
6005 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6006 d.show();
6007 }
6008 });
6009 }
6010 }
6011 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006012
6013 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006014 public void onProcessMapped(int pid, WindowProcessController proc) {
6015 synchronized (mGlobalLock) {
6016 mPidMap.put(pid, proc);
6017 }
6018 }
6019
6020 @Override
6021 public void onProcessUnMapped(int pid) {
6022 synchronized (mGlobalLock) {
6023 mPidMap.remove(pid);
6024 }
6025 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006026
6027 @Override
6028 public void onPackageDataCleared(String name) {
6029 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006030 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006031 mAppWarnings.onPackageDataCleared(name);
6032 }
6033 }
6034
6035 @Override
6036 public void onPackageUninstalled(String name) {
6037 synchronized (mGlobalLock) {
6038 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006039 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006040 }
6041 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006042
6043 @Override
6044 public void onPackageAdded(String name, boolean replacing) {
6045 synchronized (mGlobalLock) {
6046 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6047 }
6048 }
6049
6050 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006051 public void onPackageReplaced(ApplicationInfo aInfo) {
6052 synchronized (mGlobalLock) {
6053 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
6054 }
6055 }
6056
6057 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006058 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6059 synchronized (mGlobalLock) {
6060 return compatibilityInfoForPackageLocked(ai);
6061 }
6062 }
6063
Yunfan Chen75157d72018-07-27 14:47:21 +09006064 /**
6065 * Set the corresponding display information for the process global configuration. To be
6066 * called when we need to show IME on a different display.
6067 *
6068 * @param pid The process id associated with the IME window.
6069 * @param displayId The ID of the display showing the IME.
6070 */
6071 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006072 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006073 if (pid == MY_PID || pid < 0) {
6074 if (DEBUG_CONFIGURATION) {
6075 Slog.w(TAG,
6076 "Trying to update display configuration for system/invalid process.");
6077 }
6078 return;
6079 }
6080 mH.post(() -> {
6081 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006082 final ActivityDisplay activityDisplay =
6083 mStackSupervisor.getActivityDisplay(displayId);
6084 if (activityDisplay == null) {
6085 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006086 if (DEBUG_CONFIGURATION) {
6087 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006088 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006089 }
6090 return;
6091 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006092 final WindowProcessController process = mPidMap.get(pid);
6093 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006094 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006095 Slog.w(TAG, "Trying to update display configuration for invalid "
6096 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006097 }
6098 return;
6099 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006100 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006101 }
6102 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006103
Yunfan Chen75157d72018-07-27 14:47:21 +09006104 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006105
6106 @Override
6107 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6108 int requestCode, int resultCode, Intent data) {
6109 synchronized (mGlobalLock) {
6110 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6111 if (r != null && r.getStack() != null) {
6112 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6113 resultCode, data);
6114 }
6115 }
6116 }
6117
6118 @Override
6119 public void clearPendingResultForActivity(IBinder activityToken,
6120 WeakReference<PendingIntentRecord> pir) {
6121 synchronized (mGlobalLock) {
6122 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6123 if (r != null && r.pendingResults != null) {
6124 r.pendingResults.remove(pir);
6125 }
6126 }
6127 }
6128
6129 @Override
6130 public IIntentSender getIntentSender(int type, String packageName,
6131 int callingUid, int userId, IBinder token, String resultWho,
6132 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6133 Bundle bOptions) {
6134 synchronized (mGlobalLock) {
6135 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6136 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6137 }
6138 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006139
6140 @Override
6141 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6142 synchronized (mGlobalLock) {
6143 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6144 if (r == null) {
6145 return null;
6146 }
6147 if (r.mServiceConnectionsHolder == null) {
6148 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6149 ActivityTaskManagerService.this, r);
6150 }
6151
6152 return r.mServiceConnectionsHolder;
6153 }
6154 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006155
6156 @Override
6157 public Intent getHomeIntent() {
6158 synchronized (mGlobalLock) {
6159 return ActivityTaskManagerService.this.getHomeIntent();
6160 }
6161 }
6162
6163 @Override
6164 public boolean startHomeActivity(int userId, String reason) {
6165 synchronized (mGlobalLock) {
Louis Chang89f43fc2018-10-05 10:59:14 +08006166 return mStackSupervisor.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6167 }
6168 }
6169
6170 @Override
6171 public boolean startHomeOnAllDisplays(int userId, String reason) {
6172 synchronized (mGlobalLock) {
6173 return mStackSupervisor.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006174 }
6175 }
6176
6177 @Override
6178 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6179 synchronized (mGlobalLock) {
6180 if (mFactoryTest == FACTORY_TEST_OFF) {
6181 return false;
6182 }
6183 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6184 && wpc.mName.equals(mTopComponent.getPackageName())) {
6185 return true;
6186 }
6187 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6188 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6189 }
6190 }
6191
6192 @Override
6193 public void updateTopComponentForFactoryTest() {
6194 synchronized (mGlobalLock) {
6195 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6196 return;
6197 }
6198 final ResolveInfo ri = mContext.getPackageManager()
6199 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6200 final CharSequence errorMsg;
6201 if (ri != null) {
6202 final ActivityInfo ai = ri.activityInfo;
6203 final ApplicationInfo app = ai.applicationInfo;
6204 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6205 mTopAction = Intent.ACTION_FACTORY_TEST;
6206 mTopData = null;
6207 mTopComponent = new ComponentName(app.packageName, ai.name);
6208 errorMsg = null;
6209 } else {
6210 errorMsg = mContext.getResources().getText(
6211 com.android.internal.R.string.factorytest_not_system);
6212 }
6213 } else {
6214 errorMsg = mContext.getResources().getText(
6215 com.android.internal.R.string.factorytest_no_action);
6216 }
6217 if (errorMsg == null) {
6218 return;
6219 }
6220
6221 mTopAction = null;
6222 mTopData = null;
6223 mTopComponent = null;
6224 mUiHandler.post(() -> {
6225 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6226 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006227 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006228 });
6229 }
6230 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006231
6232 @Override
6233 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6234 Runnable finishInstrumentationCallback) {
6235 synchronized (mGlobalLock) {
6236 // Remove this application's activities from active lists.
6237 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6238
6239 wpc.clearRecentTasks();
6240 wpc.clearActivities();
6241
6242 if (wpc.isInstrumenting()) {
6243 finishInstrumentationCallback.run();
6244 }
6245
6246 mWindowManager.deferSurfaceLayout();
6247 try {
6248 if (!restarting && hasVisibleActivities
6249 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6250 // If there was nothing to resume, and we are not already restarting this
6251 // process, but there is a visible activity that is hosted by the process...
6252 // then make sure all visible activities are running, taking care of
6253 // restarting this process.
6254 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6255 }
6256 } finally {
6257 mWindowManager.continueSurfaceLayout();
6258 }
6259 }
6260 }
6261
6262 @Override
6263 public void closeSystemDialogs(String reason) {
6264 enforceNotIsolatedCaller("closeSystemDialogs");
6265
6266 final int pid = Binder.getCallingPid();
6267 final int uid = Binder.getCallingUid();
6268 final long origId = Binder.clearCallingIdentity();
6269 try {
6270 synchronized (mGlobalLock) {
6271 // Only allow this from foreground processes, so that background
6272 // applications can't abuse it to prevent system UI from being shown.
6273 if (uid >= FIRST_APPLICATION_UID) {
6274 final WindowProcessController proc = mPidMap.get(pid);
6275 if (!proc.isPerceptible()) {
6276 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6277 + " from background process " + proc);
6278 return;
6279 }
6280 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006281 mWindowManager.closeSystemDialogs(reason);
6282
6283 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006284 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006285 // Call into AM outside the synchronized block.
6286 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006287 } finally {
6288 Binder.restoreCallingIdentity(origId);
6289 }
6290 }
6291
6292 @Override
6293 public void cleanupDisabledPackageComponents(
6294 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6295 synchronized (mGlobalLock) {
6296 // Clean-up disabled activities.
6297 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6298 packageName, disabledClasses, true, false, userId) && booted) {
6299 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6300 mStackSupervisor.scheduleIdleLocked();
6301 }
6302
6303 // Clean-up disabled tasks
6304 getRecentTasks().cleanupDisabledPackageTasksLocked(
6305 packageName, disabledClasses, userId);
6306 }
6307 }
6308
6309 @Override
6310 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6311 int userId) {
6312 synchronized (mGlobalLock) {
6313
6314 boolean didSomething =
6315 getActivityStartController().clearPendingActivityLaunches(packageName);
6316 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6317 null, doit, evenPersistent, userId);
6318 return didSomething;
6319 }
6320 }
6321
6322 @Override
6323 public void resumeTopActivities(boolean scheduleIdle) {
6324 synchronized (mGlobalLock) {
6325 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6326 if (scheduleIdle) {
6327 mStackSupervisor.scheduleIdleLocked();
6328 }
6329 }
6330 }
6331
6332 @Override
6333 public void preBindApplication(WindowProcessController wpc) {
6334 synchronized (mGlobalLock) {
6335 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6336 }
6337 }
6338
6339 @Override
6340 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6341 synchronized (mGlobalLock) {
6342 return mStackSupervisor.attachApplicationLocked(wpc);
6343 }
6344 }
6345
6346 @Override
6347 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6348 try {
6349 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6350 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6351 }
6352 } catch (RemoteException ex) {
6353 throw new SecurityException("Fail to check is caller a privileged app", ex);
6354 }
6355
6356 synchronized (mGlobalLock) {
6357 final long ident = Binder.clearCallingIdentity();
6358 try {
6359 if (mAmInternal.shouldConfirmCredentials(userId)) {
6360 if (mKeyguardController.isKeyguardLocked()) {
6361 // Showing launcher to avoid user entering credential twice.
6362 startHomeActivity(currentUserId, "notifyLockedProfile");
6363 }
6364 mStackSupervisor.lockAllProfileTasks(userId);
6365 }
6366 } finally {
6367 Binder.restoreCallingIdentity(ident);
6368 }
6369 }
6370 }
6371
6372 @Override
6373 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6374 mAmInternal.enforceCallingPermission(
6375 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6376
6377 synchronized (mGlobalLock) {
6378 final long ident = Binder.clearCallingIdentity();
6379 try {
6380 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6381 FLAG_ACTIVITY_TASK_ON_HOME);
6382 ActivityOptions activityOptions = options != null
6383 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006384 final ActivityRecord homeActivity =
6385 mStackSupervisor.getDefaultDisplayHomeActivity();
6386 if (homeActivity != null) {
6387 activityOptions.setLaunchTaskId(homeActivity.getTask().taskId);
6388 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006389 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6390 UserHandle.CURRENT);
6391 } finally {
6392 Binder.restoreCallingIdentity(ident);
6393 }
6394 }
6395 }
6396
6397 @Override
6398 public void writeActivitiesToProto(ProtoOutputStream proto) {
6399 synchronized (mGlobalLock) {
6400 // The output proto of "activity --proto activities"
6401 // is ActivityManagerServiceDumpActivitiesProto
6402 mStackSupervisor.writeToProto(proto,
6403 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6404 }
6405 }
6406
6407 @Override
6408 public void saveANRState(String reason) {
6409 synchronized (mGlobalLock) {
6410 final StringWriter sw = new StringWriter();
6411 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6412 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6413 if (reason != null) {
6414 pw.println(" Reason: " + reason);
6415 }
6416 pw.println();
6417 getActivityStartController().dump(pw, " ", null);
6418 pw.println();
6419 pw.println("-------------------------------------------------------------------------------");
6420 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6421 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6422 "" /* header */);
6423 pw.println();
6424 pw.close();
6425
6426 mLastANRState = sw.toString();
6427 }
6428 }
6429
6430 @Override
6431 public void clearSavedANRState() {
6432 synchronized (mGlobalLock) {
6433 mLastANRState = null;
6434 }
6435 }
6436
6437 @Override
6438 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6439 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6440 synchronized (mGlobalLock) {
6441 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6442 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6443 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6444 dumpLastANRLocked(pw);
6445 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6446 dumpLastANRTracesLocked(pw);
6447 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6448 dumpActivityStarterLocked(pw, dumpPackage);
6449 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6450 dumpActivityContainersLocked(pw);
6451 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6452 if (getRecentTasks() != null) {
6453 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6454 }
6455 }
6456 }
6457 }
6458
6459 @Override
6460 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6461 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6462 int wakefulness) {
6463 synchronized (mGlobalLock) {
6464 if (mHomeProcess != null && (dumpPackage == null
6465 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6466 if (needSep) {
6467 pw.println();
6468 needSep = false;
6469 }
6470 pw.println(" mHomeProcess: " + mHomeProcess);
6471 }
6472 if (mPreviousProcess != null && (dumpPackage == null
6473 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6474 if (needSep) {
6475 pw.println();
6476 needSep = false;
6477 }
6478 pw.println(" mPreviousProcess: " + mPreviousProcess);
6479 }
6480 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6481 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6482 StringBuilder sb = new StringBuilder(128);
6483 sb.append(" mPreviousProcessVisibleTime: ");
6484 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6485 pw.println(sb);
6486 }
6487 if (mHeavyWeightProcess != null && (dumpPackage == null
6488 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6489 if (needSep) {
6490 pw.println();
6491 needSep = false;
6492 }
6493 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6494 }
6495 if (dumpPackage == null) {
6496 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6497 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6498 }
6499 if (dumpAll) {
6500 if (dumpPackage == null) {
6501 pw.println(" mConfigWillChange: "
6502 + getTopDisplayFocusedStack().mConfigWillChange);
6503 }
6504 if (mCompatModePackages.getPackages().size() > 0) {
6505 boolean printed = false;
6506 for (Map.Entry<String, Integer> entry
6507 : mCompatModePackages.getPackages().entrySet()) {
6508 String pkg = entry.getKey();
6509 int mode = entry.getValue();
6510 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6511 continue;
6512 }
6513 if (!printed) {
6514 pw.println(" mScreenCompatPackages:");
6515 printed = true;
6516 }
6517 pw.println(" " + pkg + ": " + mode);
6518 }
6519 }
6520 }
6521
6522 if (dumpPackage == null) {
6523 pw.println(" mWakefulness="
6524 + PowerManagerInternal.wakefulnessToString(wakefulness));
6525 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6526 if (mRunningVoice != null) {
6527 pw.println(" mRunningVoice=" + mRunningVoice);
6528 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6529 }
6530 pw.println(" mSleeping=" + mSleeping);
6531 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6532 pw.println(" mVrController=" + mVrController);
6533 }
6534 if (mCurAppTimeTracker != null) {
6535 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6536 }
6537 if (mAllowAppSwitchUids.size() > 0) {
6538 boolean printed = false;
6539 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6540 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6541 for (int j = 0; j < types.size(); j++) {
6542 if (dumpPackage == null ||
6543 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6544 if (needSep) {
6545 pw.println();
6546 needSep = false;
6547 }
6548 if (!printed) {
6549 pw.println(" mAllowAppSwitchUids:");
6550 printed = true;
6551 }
6552 pw.print(" User ");
6553 pw.print(mAllowAppSwitchUids.keyAt(i));
6554 pw.print(": Type ");
6555 pw.print(types.keyAt(j));
6556 pw.print(" = ");
6557 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6558 pw.println();
6559 }
6560 }
6561 }
6562 }
6563 if (dumpPackage == null) {
6564 if (mController != null) {
6565 pw.println(" mController=" + mController
6566 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6567 }
6568 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6569 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6570 }
6571
6572 return needSep;
6573 }
6574 }
6575
6576 @Override
6577 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6578 synchronized (mGlobalLock) {
6579 if (dumpPackage == null) {
6580 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6581 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6582 writeSleepStateToProto(proto);
6583 if (mController != null) {
6584 final long token = proto.start(CONTROLLER);
6585 proto.write(CONTROLLER, mController.toString());
6586 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6587 proto.end(token);
6588 }
6589 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6590 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6591 }
6592
6593 if (mHomeProcess != null && (dumpPackage == null
6594 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006595 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006596 }
6597
6598 if (mPreviousProcess != null && (dumpPackage == null
6599 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006600 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006601 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6602 }
6603
6604 if (mHeavyWeightProcess != null && (dumpPackage == null
6605 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006606 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006607 }
6608
6609 for (Map.Entry<String, Integer> entry
6610 : mCompatModePackages.getPackages().entrySet()) {
6611 String pkg = entry.getKey();
6612 int mode = entry.getValue();
6613 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6614 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6615 proto.write(PACKAGE, pkg);
6616 proto.write(MODE, mode);
6617 proto.end(compatToken);
6618 }
6619 }
6620
6621 if (mCurAppTimeTracker != null) {
6622 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6623 }
6624
6625 }
6626 }
6627
6628 @Override
6629 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6630 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6631 boolean dumpFocusedStackOnly) {
6632 synchronized (mGlobalLock) {
6633 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6634 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6635 }
6636 }
6637
6638 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006639 public void dumpForOom(PrintWriter pw) {
6640 synchronized (mGlobalLock) {
6641 pw.println(" mHomeProcess: " + mHomeProcess);
6642 pw.println(" mPreviousProcess: " + mPreviousProcess);
6643 if (mHeavyWeightProcess != null) {
6644 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6645 }
6646 }
6647 }
6648
6649 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006650 public boolean canGcNow() {
6651 synchronized (mGlobalLock) {
6652 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6653 }
6654 }
6655
6656 @Override
6657 public WindowProcessController getTopApp() {
6658 synchronized (mGlobalLock) {
6659 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6660 return top != null ? top.app : null;
6661 }
6662 }
6663
6664 @Override
6665 public void rankTaskLayersIfNeeded() {
6666 synchronized (mGlobalLock) {
6667 if (mStackSupervisor != null) {
6668 mStackSupervisor.rankTaskLayersIfNeeded();
6669 }
6670 }
6671 }
6672
6673 @Override
6674 public void scheduleDestroyAllActivities(String reason) {
6675 synchronized (mGlobalLock) {
6676 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6677 }
6678 }
6679
6680 @Override
6681 public void removeUser(int userId) {
6682 synchronized (mGlobalLock) {
6683 mStackSupervisor.removeUserLocked(userId);
6684 }
6685 }
6686
6687 @Override
6688 public boolean switchUser(int userId, UserState userState) {
6689 synchronized (mGlobalLock) {
6690 return mStackSupervisor.switchUserLocked(userId, userState);
6691 }
6692 }
6693
6694 @Override
6695 public void onHandleAppCrash(WindowProcessController wpc) {
6696 synchronized (mGlobalLock) {
6697 mStackSupervisor.handleAppCrashLocked(wpc);
6698 }
6699 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006700
6701 @Override
6702 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6703 synchronized (mGlobalLock) {
6704 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6705 }
6706 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006707
6708 @Override
6709 public void onUidActive(int uid, int procState) {
6710 synchronized (mGlobalLock) {
6711 mActiveUids.put(uid, procState);
6712 }
6713 }
6714
6715 @Override
6716 public void onUidInactive(int uid) {
6717 synchronized (mGlobalLock) {
6718 mActiveUids.remove(uid);
6719 }
6720 }
6721
6722 @Override
6723 public void onActiveUidsCleared() {
6724 synchronized (mGlobalLock) {
6725 mActiveUids.clear();
6726 }
6727 }
6728
6729 @Override
6730 public void onUidProcStateChanged(int uid, int procState) {
6731 synchronized (mGlobalLock) {
6732 if (mActiveUids.get(uid) != null) {
6733 mActiveUids.put(uid, procState);
6734 }
6735 }
6736 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006737
6738 @Override
6739 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6740 synchronized (mGlobalLock) {
6741 mPendingTempWhitelist.put(uid, tag);
6742 }
6743 }
6744
6745 @Override
6746 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6747 synchronized (mGlobalLock) {
6748 mPendingTempWhitelist.remove(uid);
6749 }
6750 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006751
6752 @Override
6753 public boolean handleAppCrashInActivityController(String processName, int pid,
6754 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6755 Runnable killCrashingAppCallback) {
6756 synchronized (mGlobalLock) {
6757 if (mController == null) {
6758 return false;
6759 }
6760
6761 try {
6762 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6763 stackTrace)) {
6764 killCrashingAppCallback.run();
6765 return true;
6766 }
6767 } catch (RemoteException e) {
6768 mController = null;
6769 Watchdog.getInstance().setActivityController(null);
6770 }
6771 return false;
6772 }
6773 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006774
6775 @Override
6776 public void removeRecentTasksByPackageName(String packageName, int userId) {
6777 synchronized (mGlobalLock) {
6778 mRecentTasks.removeTasksByPackageName(packageName, userId);
6779 }
6780 }
6781
6782 @Override
6783 public void cleanupRecentTasksForUser(int userId) {
6784 synchronized (mGlobalLock) {
6785 mRecentTasks.cleanupLocked(userId);
6786 }
6787 }
6788
6789 @Override
6790 public void loadRecentTasksForUser(int userId) {
6791 synchronized (mGlobalLock) {
6792 mRecentTasks.loadUserRecentsLocked(userId);
6793 }
6794 }
6795
6796 @Override
6797 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6798 synchronized (mGlobalLock) {
6799 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6800 }
6801 }
6802
6803 @Override
6804 public void flushRecentTasks() {
6805 mRecentTasks.flush();
6806 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006807
6808 @Override
6809 public WindowProcessController getHomeProcess() {
6810 synchronized (mGlobalLock) {
6811 return mHomeProcess;
6812 }
6813 }
6814
6815 @Override
6816 public WindowProcessController getPreviousProcess() {
6817 synchronized (mGlobalLock) {
6818 return mPreviousProcess;
6819 }
6820 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006821
6822 @Override
6823 public void clearLockedTasks(String reason) {
6824 synchronized (mGlobalLock) {
6825 getLockTaskController().clearLockedTasks(reason);
6826 }
6827 }
6828
6829 @Override
6830 public void updateUserConfiguration() {
6831 synchronized (mGlobalLock) {
6832 final Configuration configuration = new Configuration(getGlobalConfiguration());
6833 final int currentUserId = mAmInternal.getCurrentUserId();
6834 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6835 configuration, currentUserId, Settings.System.canWrite(mContext));
6836 updateConfigurationLocked(configuration, null /* starting */,
6837 false /* initLocale */, false /* persistent */, currentUserId,
6838 false /* deferResume */);
6839 }
6840 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006841
6842 @Override
6843 public boolean canShowErrorDialogs() {
6844 synchronized (mGlobalLock) {
6845 return mShowDialogs && !mSleeping && !mShuttingDown
6846 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6847 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6848 mAmInternal.getCurrentUserId())
6849 && !(UserManager.isDeviceInDemoMode(mContext)
6850 && mAmInternal.getCurrentUser().isDemo());
6851 }
6852 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006853
6854 @Override
6855 public void setProfileApp(String profileApp) {
6856 synchronized (mGlobalLock) {
6857 mProfileApp = profileApp;
6858 }
6859 }
6860
6861 @Override
6862 public void setProfileProc(WindowProcessController wpc) {
6863 synchronized (mGlobalLock) {
6864 mProfileProc = wpc;
6865 }
6866 }
6867
6868 @Override
6869 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6870 synchronized (mGlobalLock) {
6871 mProfilerInfo = profilerInfo;
6872 }
6873 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006874 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08006875}