blob: 1d0007545d78a7c8d64caae1627dd6a421e7c174 [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 Ogunwale38f72bd2018-11-20 02:53:49 +0000344 private ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 PowerManagerInternal mPowerManagerInternal;
346 private UsageStatsManagerInternal mUsageStatsInternal;
347
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700348 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 IntentFirewall mIntentFirewall;
350
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700351 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800352 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700353 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700355 private UserManagerService mUserManager;
356 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700357 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700358 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
359 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700360 /** All processes currently running that might have a window organized by name. */
361 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700362 /** All processes we currently have running mapped by pid */
363 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700364 /** This is the process holding what we currently consider to be the "home" activity. */
365 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700366 /** The currently running heavy-weight process, if any. */
367 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700368 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700369 /**
370 * This is the process holding the activity the user last visited that is in a different process
371 * from the one they are currently in.
372 */
373 WindowProcessController mPreviousProcess;
374 /** The time at which the previous process was last visible. */
375 long mPreviousProcessVisibleTime;
376
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 /** List of intents that were used to start the most recent tasks. */
378 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700379 /** State of external calls telling us if the device is awake or asleep. */
380 private boolean mKeyguardShown = false;
381
382 // Wrapper around VoiceInteractionServiceManager
383 private AssistUtils mAssistUtils;
384
385 // VoiceInteraction session ID that changes for each new request except when
386 // being called for multi-window assist in a single session.
387 private int mViSessionId = 1000;
388
389 // How long to wait in getAssistContextExtras for the activity and foreground services
390 // to respond with the result.
391 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
392
393 // How long top wait when going through the modern assist (which doesn't need to block
394 // on getting this result before starting to launch its UI).
395 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
396
397 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
398 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
399
Alison Cichowlas3e340502018-08-07 17:15:01 -0400400 // Permission tokens are used to temporarily granted a trusted app the ability to call
401 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
402 // showing any appropriate error messages to the user.
403 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
404 10 * MINUTE_IN_MILLIS;
405
406 // How long before the service actually expires a token. This is slightly longer than
407 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
408 // expiration exception.
409 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
410 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
411
412 // How long the service will remember expired tokens, for the purpose of providing error
413 // messaging when a client uses an expired token.
414 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
415 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
416
417 // Activity tokens of system activities that are delegating their call to
418 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
419 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
420
421 // Permission tokens that have expired, but we remember for error reporting.
422 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700424 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
425
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700426 // Keeps track of the active voice interaction service component, notified from
427 // VoiceInteractionManagerService
428 ComponentName mActiveVoiceInteractionServiceComponent;
429
Wale Ogunwalee2172292018-10-25 10:11:10 -0700430 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700431 KeyguardController mKeyguardController;
432 private final ClientLifecycleManager mLifecycleManager;
433 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700434 /** The controller for all operations related to locktask. */
435 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700436 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700437
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700438 boolean mSuppressResizeConfigChanges;
439
440 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
441 new UpdateConfigurationResult();
442
443 static final class UpdateConfigurationResult {
444 // Configuration changes that were updated.
445 int changes;
446 // If the activity was relaunched to match the new configuration.
447 boolean activityRelaunched;
448
449 void reset() {
450 changes = 0;
451 activityRelaunched = false;
452 }
453 }
454
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700455 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700456 private int mConfigurationSeq;
457 // To cache the list of supported system locales
458 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700459
460 /**
461 * Temp object used when global and/or display override configuration is updated. It is also
462 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
463 * anyone...
464 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700465 private Configuration mTempConfig = new Configuration();
466
Wale Ogunwalef6733932018-06-27 05:14:34 -0700467 /** Temporary to avoid allocations. */
468 final StringBuilder mStringBuilder = new StringBuilder(256);
469
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700470 // Amount of time after a call to stopAppSwitches() during which we will
471 // prevent further untrusted switches from happening.
472 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
473
474 /**
475 * The time at which we will allow normal application switches again,
476 * after a call to {@link #stopAppSwitches()}.
477 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700478 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 /**
480 * This is set to true after the first switch after mAppSwitchesAllowedTime
481 * is set; any switches after that will clear the time.
482 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700483 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484
485 IActivityController mController = null;
486 boolean mControllerIsAMonkey = false;
487
Wale Ogunwale214f3482018-10-04 11:00:47 -0700488 final int mFactoryTest;
489
490 /** Used to control how we initialize the service. */
491 ComponentName mTopComponent;
492 String mTopAction = Intent.ACTION_MAIN;
493 String mTopData;
494
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800495 /** Profiling app information. */
496 String mProfileApp = null;
497 WindowProcessController mProfileProc = null;
498 ProfilerInfo mProfilerInfo = null;
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700501 * Dump of the activity state at the time of the last ANR. Cleared after
502 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
503 */
504 String mLastANRState;
505
506 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 * Used to retain an update lock when the foreground activity is in
508 * immersive mode.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
512 /**
513 * Packages that are being allowed to perform unrestricted app switches. Mapping is
514 * User -> Type -> uid.
515 */
516 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
517
518 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700519 private int mThumbnailWidth;
520 private int mThumbnailHeight;
521 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522
523 /**
524 * Flag that indicates if multi-window is enabled.
525 *
526 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
527 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
528 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
529 * At least one of the forms of multi-window must be enabled in order for this flag to be
530 * initialized to 'true'.
531 *
532 * @see #mSupportsSplitScreenMultiWindow
533 * @see #mSupportsFreeformWindowManagement
534 * @see #mSupportsPictureInPicture
535 * @see #mSupportsMultiDisplay
536 */
537 boolean mSupportsMultiWindow;
538 boolean mSupportsSplitScreenMultiWindow;
539 boolean mSupportsFreeformWindowManagement;
540 boolean mSupportsPictureInPicture;
541 boolean mSupportsMultiDisplay;
542 boolean mForceResizableActivities;
543
544 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
545
546 // VR Vr2d Display Id.
547 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700548
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 /**
550 * Set while we are wanting to sleep, to prevent any
551 * activities from being started/resumed.
552 *
553 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
554 *
555 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
556 * while in the sleep state until there is a pending transition out of sleep, in which case
557 * mSleeping is set to false, and remains false while awake.
558 *
559 * Whether mSleeping can quickly toggled between true/false without the device actually
560 * display changing states is undefined.
561 */
562 private boolean mSleeping = false;
563
564 /**
565 * The process state used for processes that are running the top activities.
566 * This changes between TOP and TOP_SLEEPING to following mSleeping.
567 */
568 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
569
570 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
571 // automatically. Important for devices without direct input devices.
572 private boolean mShowDialogs = true;
573
574 /** Set if we are shutting down the system, similar to sleeping. */
575 boolean mShuttingDown = false;
576
577 /**
578 * We want to hold a wake lock while running a voice interaction session, since
579 * this may happen with the screen off and we need to keep the CPU running to
580 * be able to continue to interact with the user.
581 */
582 PowerManager.WakeLock mVoiceWakeLock;
583
584 /**
585 * Set while we are running a voice interaction. This overrides sleeping while it is active.
586 */
587 IVoiceInteractionSession mRunningVoice;
588
589 /**
590 * The last resumed activity. This is identical to the current resumed activity most
591 * of the time but could be different when we're pausing one activity before we resume
592 * another activity.
593 */
594 ActivityRecord mLastResumedActivity;
595
596 /**
597 * The activity that is currently being traced as the active resumed activity.
598 *
599 * @see #updateResumedAppTrace
600 */
601 private @Nullable ActivityRecord mTracedResumedActivity;
602
603 /** If non-null, we are tracking the time the user spends in the currently focused app. */
604 AppTimeTracker mCurAppTimeTracker;
605
Wale Ogunwale008163e2018-07-23 23:11:08 -0700606 private AppWarnings mAppWarnings;
607
Wale Ogunwale53783742018-09-16 10:21:51 -0700608 /**
609 * Packages that the user has asked to have run in screen size
610 * compatibility mode instead of filling the screen.
611 */
612 CompatModePackages mCompatModePackages;
613
Wale Ogunwalef6733932018-06-27 05:14:34 -0700614 private FontScaleSettingObserver mFontScaleSettingObserver;
615
616 private final class FontScaleSettingObserver extends ContentObserver {
617 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
618 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
619
620 public FontScaleSettingObserver() {
621 super(mH);
622 final ContentResolver resolver = mContext.getContentResolver();
623 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
624 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
625 UserHandle.USER_ALL);
626 }
627
628 @Override
629 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
630 if (mFontScaleUri.equals(uri)) {
631 updateFontScaleIfNeeded(userId);
632 } else if (mHideErrorDialogsUri.equals(uri)) {
633 synchronized (mGlobalLock) {
634 updateShouldShowDialogsLocked(getGlobalConfiguration());
635 }
636 }
637 }
638 }
639
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700640 ActivityTaskManagerService(Context context) {
641 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700642 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700643 mSystemThread = ActivityThread.currentActivityThread();
644 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700645 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700646 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700647 }
648
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700649 public void onSystemReady() {
650 synchronized (mGlobalLock) {
651 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
652 PackageManager.FEATURE_CANT_SAVE_STATE);
653 mAssistUtils = new AssistUtils(mContext);
654 mVrController.onSystemReady();
655 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700656 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700657 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700658 }
659
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700660 public void onInitPowerManagement() {
661 synchronized (mGlobalLock) {
662 mStackSupervisor.initPowerManagement();
663 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
664 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
665 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
666 mVoiceWakeLock.setReferenceCounted(false);
667 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700668 }
669
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700670 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 mFontScaleSettingObserver = new FontScaleSettingObserver();
672 }
673
Wale Ogunwale59507092018-10-29 09:00:30 -0700674 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700675 final boolean freeformWindowManagement =
676 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
677 || Settings.Global.getInt(
678 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
679
680 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
681 final boolean supportsPictureInPicture = supportsMultiWindow &&
682 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
683 final boolean supportsSplitScreenMultiWindow =
684 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
685 final boolean supportsMultiDisplay = mContext.getPackageManager()
686 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700687 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
688 final boolean forceResizable = Settings.Global.getInt(
689 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700690 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700691
692 // Transfer any global setting for forcing RTL layout, into a System Property
693 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
694
695 final Configuration configuration = new Configuration();
696 Settings.System.getConfiguration(resolver, configuration);
697 if (forceRtl) {
698 // This will take care of setting the correct layout direction flags
699 configuration.setLayoutDirection(configuration.locale);
700 }
701
702 synchronized (mGlobalLock) {
703 mForceResizableActivities = forceResizable;
704 final boolean multiWindowFormEnabled = freeformWindowManagement
705 || supportsSplitScreenMultiWindow
706 || supportsPictureInPicture
707 || supportsMultiDisplay;
708 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
709 mSupportsMultiWindow = true;
710 mSupportsFreeformWindowManagement = freeformWindowManagement;
711 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
712 mSupportsPictureInPicture = supportsPictureInPicture;
713 mSupportsMultiDisplay = supportsMultiDisplay;
714 } else {
715 mSupportsMultiWindow = false;
716 mSupportsFreeformWindowManagement = false;
717 mSupportsSplitScreenMultiWindow = false;
718 mSupportsPictureInPicture = false;
719 mSupportsMultiDisplay = false;
720 }
721 mWindowManager.setForceResizableTasks(mForceResizableActivities);
722 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700723 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
724 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725 // This happens before any activities are started, so we can change global configuration
726 // in-place.
727 updateConfigurationLocked(configuration, null, true);
728 final Configuration globalConfig = getGlobalConfiguration();
729 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
730
731 // Load resources only after the current configuration has been set.
732 final Resources res = mContext.getResources();
733 mThumbnailWidth = res.getDimensionPixelSize(
734 com.android.internal.R.dimen.thumbnail_width);
735 mThumbnailHeight = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_height);
737
738 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
739 mFullscreenThumbnailScale = (float) res
740 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
741 (float) globalConfig.screenWidthDp;
742 } else {
743 mFullscreenThumbnailScale = res.getFraction(
744 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
745 }
746 }
747 }
748
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800749 public WindowManagerGlobalLock getGlobalLock() {
750 return mGlobalLock;
751 }
752
753 public void setActivityManagerService(IntentFirewall intentFirewall,
754 PendingIntentController intentController) {
755 mH = new H();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700757 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700758 final File systemDir = SystemServiceManager.ensureSystemDir();
759 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
760 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700761 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700762
763 mTempConfig.setToDefaults();
764 mTempConfig.setLocales(LocaleList.getDefault());
765 mConfigurationSeq = mTempConfig.seq = 1;
766 mStackSupervisor = createStackSupervisor();
767 mStackSupervisor.onConfigurationChanged(mTempConfig);
768
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700769 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700770 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700771 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700772 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700773 mRecentTasks = createRecentTasks();
774 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700775 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700776 mKeyguardController = mStackSupervisor.getKeyguardController();
777 }
778
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700779 public void onActivityManagerInternalAdded() {
780 synchronized (mGlobalLock) {
781 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
782 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
783 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700784 }
785
Yunfan Chen75157d72018-07-27 14:47:21 +0900786 int increaseConfigurationSeqLocked() {
787 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
788 return mConfigurationSeq;
789 }
790
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700791 protected ActivityStackSupervisor createStackSupervisor() {
792 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
793 supervisor.initialize();
794 return supervisor;
795 }
796
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700797 public void setWindowManager(WindowManagerService wm) {
798 synchronized (mGlobalLock) {
799 mWindowManager = wm;
800 mLockTaskController.setWindowManager(wm);
801 mStackSupervisor.setWindowManager(wm);
802 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700803 }
804
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700805 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
806 synchronized (mGlobalLock) {
807 mUsageStatsInternal = usageStatsManager;
808 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700809 }
810
Wale Ogunwalef6733932018-06-27 05:14:34 -0700811 UserManagerService getUserManager() {
812 if (mUserManager == null) {
813 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
814 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
815 }
816 return mUserManager;
817 }
818
819 AppOpsService getAppOpsService() {
820 if (mAppOpsService == null) {
821 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
822 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
823 }
824 return mAppOpsService;
825 }
826
827 boolean hasUserRestriction(String restriction, int userId) {
828 return getUserManager().hasUserRestriction(restriction, userId);
829 }
830
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700831 protected RecentTasks createRecentTasks() {
832 return new RecentTasks(this, mStackSupervisor);
833 }
834
835 RecentTasks getRecentTasks() {
836 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700837 }
838
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700839 ClientLifecycleManager getLifecycleManager() {
840 return mLifecycleManager;
841 }
842
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700843 ActivityStartController getActivityStartController() {
844 return mActivityStartController;
845 }
846
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700847 TaskChangeNotificationController getTaskChangeNotificationController() {
848 return mTaskChangeNotificationController;
849 }
850
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700851 LockTaskController getLockTaskController() {
852 return mLockTaskController;
853 }
854
Yunfan Chen75157d72018-07-27 14:47:21 +0900855 /**
856 * Return the global configuration used by the process corresponding to the input pid. This is
857 * usually the global configuration with some overrides specific to that process.
858 */
859 Configuration getGlobalConfigurationForCallingPid() {
860 final int pid = Binder.getCallingPid();
861 if (pid == MY_PID || pid < 0) {
862 return getGlobalConfiguration();
863 }
864 synchronized (mGlobalLock) {
865 final WindowProcessController app = mPidMap.get(pid);
866 return app != null ? app.getConfiguration() : getGlobalConfiguration();
867 }
868 }
869
870 /**
871 * Return the device configuration info used by the process corresponding to the input pid.
872 * The value is consistent with the global configuration for the process.
873 */
874 @Override
875 public ConfigurationInfo getDeviceConfigurationInfo() {
876 ConfigurationInfo config = new ConfigurationInfo();
877 synchronized (mGlobalLock) {
878 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
879 config.reqTouchScreen = globalConfig.touchscreen;
880 config.reqKeyboardType = globalConfig.keyboard;
881 config.reqNavigation = globalConfig.navigation;
882 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
883 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
884 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
885 }
886 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
887 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
888 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
889 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700890 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900891 }
892 return config;
893 }
894
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700895 private void start() {
Wale Ogunwale38f72bd2018-11-20 02:53:49 +0000896 mInternal = new LocalService();
Wale Ogunwale53783742018-09-16 10:21:51 -0700897 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700898 }
899
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700900 public static final class Lifecycle extends SystemService {
901 private final ActivityTaskManagerService mService;
902
903 public Lifecycle(Context context) {
904 super(context);
905 mService = new ActivityTaskManagerService(context);
906 }
907
908 @Override
909 public void onStart() {
910 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700911 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700912 }
913
Garfield Tan891146c2018-10-09 12:14:00 -0700914 @Override
915 public void onUnlockUser(int userId) {
916 synchronized (mService.getGlobalLock()) {
917 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
918 }
919 }
920
921 @Override
922 public void onCleanupUser(int userId) {
923 synchronized (mService.getGlobalLock()) {
924 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
925 }
926 }
927
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700928 public ActivityTaskManagerService getService() {
929 return mService;
930 }
931 }
932
933 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700934 public final int startActivity(IApplicationThread caller, String callingPackage,
935 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
936 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
937 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
938 resultWho, requestCode, startFlags, profilerInfo, bOptions,
939 UserHandle.getCallingUserId());
940 }
941
942 @Override
943 public final int startActivities(IApplicationThread caller, String callingPackage,
944 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
945 int userId) {
946 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700947 enforceNotIsolatedCaller(reason);
948 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700949 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700950 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100951 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
952 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700953 }
954
955 @Override
956 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
957 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
958 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
959 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
960 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
961 true /*validateIncomingUser*/);
962 }
963
964 int startActivityAsUser(IApplicationThread caller, String callingPackage,
965 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
966 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
967 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700968 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700969
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700970 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700971 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
972
973 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700974 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700975 .setCaller(caller)
976 .setCallingPackage(callingPackage)
977 .setResolvedType(resolvedType)
978 .setResultTo(resultTo)
979 .setResultWho(resultWho)
980 .setRequestCode(requestCode)
981 .setStartFlags(startFlags)
982 .setProfilerInfo(profilerInfo)
983 .setActivityOptions(bOptions)
984 .setMayWait(userId)
985 .execute();
986
987 }
988
989 @Override
990 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
991 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700992 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
993 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700994 // Refuse possible leaked file descriptors
995 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
996 throw new IllegalArgumentException("File descriptors passed in Intent");
997 }
998
999 if (!(target instanceof PendingIntentRecord)) {
1000 throw new IllegalArgumentException("Bad PendingIntent object");
1001 }
1002
1003 PendingIntentRecord pir = (PendingIntentRecord)target;
1004
1005 synchronized (mGlobalLock) {
1006 // If this is coming from the currently resumed activity, it is
1007 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001008 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001009 if (stack.mResumedActivity != null &&
1010 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001011 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001012 }
1013 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001014 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 }
1017
1018 @Override
1019 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1020 Bundle bOptions) {
1021 // Refuse possible leaked file descriptors
1022 if (intent != null && intent.hasFileDescriptors()) {
1023 throw new IllegalArgumentException("File descriptors passed in Intent");
1024 }
1025 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1026
1027 synchronized (mGlobalLock) {
1028 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1029 if (r == null) {
1030 SafeActivityOptions.abort(options);
1031 return false;
1032 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001033 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 // The caller is not running... d'oh!
1035 SafeActivityOptions.abort(options);
1036 return false;
1037 }
1038 intent = new Intent(intent);
1039 // The caller is not allowed to change the data.
1040 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1041 // And we are resetting to find the next component...
1042 intent.setComponent(null);
1043
1044 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1045
1046 ActivityInfo aInfo = null;
1047 try {
1048 List<ResolveInfo> resolves =
1049 AppGlobals.getPackageManager().queryIntentActivities(
1050 intent, r.resolvedType,
1051 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1052 UserHandle.getCallingUserId()).getList();
1053
1054 // Look for the original activity in the list...
1055 final int N = resolves != null ? resolves.size() : 0;
1056 for (int i=0; i<N; i++) {
1057 ResolveInfo rInfo = resolves.get(i);
1058 if (rInfo.activityInfo.packageName.equals(r.packageName)
1059 && rInfo.activityInfo.name.equals(r.info.name)) {
1060 // We found the current one... the next matching is
1061 // after it.
1062 i++;
1063 if (i<N) {
1064 aInfo = resolves.get(i).activityInfo;
1065 }
1066 if (debug) {
1067 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1068 + "/" + r.info.name);
1069 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1070 ? "null" : aInfo.packageName + "/" + aInfo.name));
1071 }
1072 break;
1073 }
1074 }
1075 } catch (RemoteException e) {
1076 }
1077
1078 if (aInfo == null) {
1079 // Nobody who is next!
1080 SafeActivityOptions.abort(options);
1081 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1082 return false;
1083 }
1084
1085 intent.setComponent(new ComponentName(
1086 aInfo.applicationInfo.packageName, aInfo.name));
1087 intent.setFlags(intent.getFlags()&~(
1088 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1089 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1090 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1091 FLAG_ACTIVITY_NEW_TASK));
1092
1093 // Okay now we need to start the new activity, replacing the currently running activity.
1094 // This is a little tricky because we want to start the new one as if the current one is
1095 // finished, but not finish the current one first so that there is no flicker.
1096 // And thus...
1097 final boolean wasFinishing = r.finishing;
1098 r.finishing = true;
1099
1100 // Propagate reply information over to the new activity.
1101 final ActivityRecord resultTo = r.resultTo;
1102 final String resultWho = r.resultWho;
1103 final int requestCode = r.requestCode;
1104 r.resultTo = null;
1105 if (resultTo != null) {
1106 resultTo.removeResultsLocked(r, resultWho, requestCode);
1107 }
1108
1109 final long origId = Binder.clearCallingIdentity();
1110 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001111 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001113 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 .setResolvedType(r.resolvedType)
1115 .setActivityInfo(aInfo)
1116 .setResultTo(resultTo != null ? resultTo.appToken : null)
1117 .setResultWho(resultWho)
1118 .setRequestCode(requestCode)
1119 .setCallingPid(-1)
1120 .setCallingUid(r.launchedFromUid)
1121 .setCallingPackage(r.launchedFromPackage)
1122 .setRealCallingPid(-1)
1123 .setRealCallingUid(r.launchedFromUid)
1124 .setActivityOptions(options)
1125 .execute();
1126 Binder.restoreCallingIdentity(origId);
1127
1128 r.finishing = wasFinishing;
1129 if (res != ActivityManager.START_SUCCESS) {
1130 return false;
1131 }
1132 return true;
1133 }
1134 }
1135
1136 @Override
1137 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1138 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1139 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1140 final WaitResult res = new WaitResult();
1141 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001142 enforceNotIsolatedCaller("startActivityAndWait");
1143 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1144 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001145 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001146 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001147 .setCaller(caller)
1148 .setCallingPackage(callingPackage)
1149 .setResolvedType(resolvedType)
1150 .setResultTo(resultTo)
1151 .setResultWho(resultWho)
1152 .setRequestCode(requestCode)
1153 .setStartFlags(startFlags)
1154 .setActivityOptions(bOptions)
1155 .setMayWait(userId)
1156 .setProfilerInfo(profilerInfo)
1157 .setWaitResult(res)
1158 .execute();
1159 }
1160 return res;
1161 }
1162
1163 @Override
1164 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1165 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1166 int startFlags, Configuration config, Bundle bOptions, int userId) {
1167 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001168 enforceNotIsolatedCaller("startActivityWithConfig");
1169 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1170 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001171 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001172 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001173 .setCaller(caller)
1174 .setCallingPackage(callingPackage)
1175 .setResolvedType(resolvedType)
1176 .setResultTo(resultTo)
1177 .setResultWho(resultWho)
1178 .setRequestCode(requestCode)
1179 .setStartFlags(startFlags)
1180 .setGlobalConfiguration(config)
1181 .setActivityOptions(bOptions)
1182 .setMayWait(userId)
1183 .execute();
1184 }
1185 }
1186
Alison Cichowlas3e340502018-08-07 17:15:01 -04001187
1188 @Override
1189 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1190 int callingUid = Binder.getCallingUid();
1191 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1192 throw new SecurityException("Only the system process can request a permission token, "
1193 + "received request from uid: " + callingUid);
1194 }
1195 IBinder permissionToken = new Binder();
1196 synchronized (mGlobalLock) {
1197 mStartActivitySources.put(permissionToken, delegatorToken);
1198 }
1199
1200 Message expireMsg = PooledLambda.obtainMessage(
1201 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1202 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1203
1204 Message forgetMsg = PooledLambda.obtainMessage(
1205 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1206 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1207
1208 return permissionToken;
1209 }
1210
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 @Override
1212 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1213 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001214 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1215 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001217 // permission grants) as any app that may launch one of your own activities. So we only
1218 // allow this in two cases:
1219 // 1) The caller is an activity that is part of the core framework, and then only when it
1220 // is running as the system.
1221 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1222 // can only be requested by a system activity, which may then delegate this call to
1223 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 final ActivityRecord sourceRecord;
1225 final int targetUid;
1226 final String targetPackage;
1227 final boolean isResolver;
1228 synchronized (mGlobalLock) {
1229 if (resultTo == null) {
1230 throw new SecurityException("Must be called from an activity");
1231 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001232 final IBinder sourceToken;
1233 if (permissionToken != null) {
1234 // To even attempt to use a permissionToken, an app must also have this signature
1235 // permission.
1236 mAmInternal.enforceCallingPermission(
1237 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1238 "startActivityAsCaller");
1239 // If called with a permissionToken, we want the sourceRecord from the delegator
1240 // activity that requested this token.
1241 sourceToken = mStartActivitySources.remove(permissionToken);
1242 if (sourceToken == null) {
1243 // Invalid permissionToken, check if it recently expired.
1244 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1245 throw new SecurityException("Called with expired permission token: "
1246 + permissionToken);
1247 } else {
1248 throw new SecurityException("Called with invalid permission token: "
1249 + permissionToken);
1250 }
1251 }
1252 } else {
1253 // This method was called directly by the source.
1254 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001256
1257 sourceRecord = mStackSupervisor.isInAnyStackLocked(sourceToken);
1258 if (sourceRecord == null) {
1259 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001260 }
1261 if (sourceRecord.app == null) {
1262 throw new SecurityException("Called without a process attached to activity");
1263 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001264
1265 // Whether called directly or from a delegate, the source activity must be from the
1266 // android package.
1267 if (!sourceRecord.info.packageName.equals("android")) {
1268 throw new SecurityException("Must be called from an activity that is "
1269 + "declared in the android package");
1270 }
1271
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001272 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001273 // This is still okay, as long as this activity is running under the
1274 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001275 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001277 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 + " must be system uid or original calling uid "
1279 + sourceRecord.launchedFromUid);
1280 }
1281 }
1282 if (ignoreTargetSecurity) {
1283 if (intent.getComponent() == null) {
1284 throw new SecurityException(
1285 "Component must be specified with ignoreTargetSecurity");
1286 }
1287 if (intent.getSelector() != null) {
1288 throw new SecurityException(
1289 "Selector not allowed with ignoreTargetSecurity");
1290 }
1291 }
1292 targetUid = sourceRecord.launchedFromUid;
1293 targetPackage = sourceRecord.launchedFromPackage;
1294 isResolver = sourceRecord.isResolverOrChildActivity();
1295 }
1296
1297 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001298 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 }
1300
1301 // TODO: Switch to user app stacks here.
1302 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001303 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 .setCallingUid(targetUid)
1305 .setCallingPackage(targetPackage)
1306 .setResolvedType(resolvedType)
1307 .setResultTo(resultTo)
1308 .setResultWho(resultWho)
1309 .setRequestCode(requestCode)
1310 .setStartFlags(startFlags)
1311 .setActivityOptions(bOptions)
1312 .setMayWait(userId)
1313 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1314 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1315 .execute();
1316 } catch (SecurityException e) {
1317 // XXX need to figure out how to propagate to original app.
1318 // A SecurityException here is generally actually a fault of the original
1319 // calling activity (such as a fairly granting permissions), so propagate it
1320 // back to them.
1321 /*
1322 StringBuilder msg = new StringBuilder();
1323 msg.append("While launching");
1324 msg.append(intent.toString());
1325 msg.append(": ");
1326 msg.append(e.getMessage());
1327 */
1328 throw e;
1329 }
1330 }
1331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001332 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1333 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1334 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1335 }
1336
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 @Override
1338 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1339 Intent intent, String resolvedType, IVoiceInteractionSession session,
1340 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1341 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001342 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 if (session == null || interactor == null) {
1344 throw new NullPointerException("null session or interactor");
1345 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001346 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001348 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 .setCallingUid(callingUid)
1350 .setCallingPackage(callingPackage)
1351 .setResolvedType(resolvedType)
1352 .setVoiceSession(session)
1353 .setVoiceInteractor(interactor)
1354 .setStartFlags(startFlags)
1355 .setProfilerInfo(profilerInfo)
1356 .setActivityOptions(bOptions)
1357 .setMayWait(userId)
1358 .execute();
1359 }
1360
1361 @Override
1362 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1363 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001364 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1365 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001367 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 .setCallingUid(callingUid)
1369 .setCallingPackage(callingPackage)
1370 .setResolvedType(resolvedType)
1371 .setActivityOptions(bOptions)
1372 .setMayWait(userId)
1373 .execute();
1374 }
1375
1376 @Override
1377 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1378 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001379 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 final int callingPid = Binder.getCallingPid();
1381 final long origId = Binder.clearCallingIdentity();
1382 try {
1383 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001384 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1385 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386
1387 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001388 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1389 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1391 recentsUid, assistDataReceiver);
1392 }
1393 } finally {
1394 Binder.restoreCallingIdentity(origId);
1395 }
1396 }
1397
1398 @Override
1399 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 "startActivityFromRecents()");
1402
1403 final int callingPid = Binder.getCallingPid();
1404 final int callingUid = Binder.getCallingUid();
1405 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1406 final long origId = Binder.clearCallingIdentity();
1407 try {
1408 synchronized (mGlobalLock) {
1409 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1410 safeOptions);
1411 }
1412 } finally {
1413 Binder.restoreCallingIdentity(origId);
1414 }
1415 }
1416
1417 /**
1418 * This is the internal entry point for handling Activity.finish().
1419 *
1420 * @param token The Binder token referencing the Activity we want to finish.
1421 * @param resultCode Result code, if any, from this Activity.
1422 * @param resultData Result data (Intent), if any, from this Activity.
1423 * @param finishTask Whether to finish the task associated with this Activity.
1424 *
1425 * @return Returns true if the activity successfully finished, or false if it is still running.
1426 */
1427 @Override
1428 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1429 int finishTask) {
1430 // Refuse possible leaked file descriptors
1431 if (resultData != null && resultData.hasFileDescriptors()) {
1432 throw new IllegalArgumentException("File descriptors passed in Intent");
1433 }
1434
1435 synchronized (mGlobalLock) {
1436 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1437 if (r == null) {
1438 return true;
1439 }
1440 // Keep track of the root activity of the task before we finish it
1441 TaskRecord tr = r.getTask();
1442 ActivityRecord rootR = tr.getRootActivity();
1443 if (rootR == null) {
1444 Slog.w(TAG, "Finishing task with all activities already finished");
1445 }
1446 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1447 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001448 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 return false;
1450 }
1451
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001452 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1453 // We should consolidate.
1454 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 // Find the first activity that is not finishing.
1456 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1457 if (next != null) {
1458 // ask watcher if this is allowed
1459 boolean resumeOK = true;
1460 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001461 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 Watchdog.getInstance().setActivityController(null);
1465 }
1466
1467 if (!resumeOK) {
1468 Slog.i(TAG, "Not finishing activity because controller resumed");
1469 return false;
1470 }
1471 }
1472 }
1473 final long origId = Binder.clearCallingIdentity();
1474 try {
1475 boolean res;
1476 final boolean finishWithRootActivity =
1477 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1478 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1479 || (finishWithRootActivity && r == rootR)) {
1480 // If requested, remove the task that is associated to this activity only if it
1481 // was the root activity in the task. The result code and data is ignored
1482 // because we don't support returning them across task boundaries. Also, to
1483 // keep backwards compatibility we remove the task from recents when finishing
1484 // task with root activity.
1485 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1486 finishWithRootActivity, "finish-activity");
1487 if (!res) {
1488 Slog.i(TAG, "Removing task failed to finish activity");
1489 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001490 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001491 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 } else {
1493 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1494 resultData, "app-request", true);
1495 if (!res) {
1496 Slog.i(TAG, "Failed to finish by app-request");
1497 }
1498 }
1499 return res;
1500 } finally {
1501 Binder.restoreCallingIdentity(origId);
1502 }
1503 }
1504 }
1505
1506 @Override
1507 public boolean finishActivityAffinity(IBinder token) {
1508 synchronized (mGlobalLock) {
1509 final long origId = Binder.clearCallingIdentity();
1510 try {
1511 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1512 if (r == null) {
1513 return false;
1514 }
1515
1516 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1517 // can finish.
1518 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001519 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001520 return false;
1521 }
1522 return task.getStack().finishActivityAffinityLocked(r);
1523 } finally {
1524 Binder.restoreCallingIdentity(origId);
1525 }
1526 }
1527 }
1528
1529 @Override
1530 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1531 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001532 try {
1533 WindowProcessController proc = null;
1534 synchronized (mGlobalLock) {
1535 ActivityStack stack = ActivityRecord.getStackLocked(token);
1536 if (stack == null) {
1537 return;
1538 }
1539 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1540 false /* fromTimeout */, false /* processPausingActivities */, config);
1541 if (r != null) {
1542 proc = r.app;
1543 }
1544 if (stopProfiling && proc != null) {
1545 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 }
1547 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001548 } finally {
1549 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 }
1552
1553 @Override
1554 public final void activityResumed(IBinder token) {
1555 final long origId = Binder.clearCallingIdentity();
1556 synchronized (mGlobalLock) {
1557 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001558 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001559 }
1560 Binder.restoreCallingIdentity(origId);
1561 }
1562
1563 @Override
1564 public final void activityPaused(IBinder token) {
1565 final long origId = Binder.clearCallingIdentity();
1566 synchronized (mGlobalLock) {
1567 ActivityStack stack = ActivityRecord.getStackLocked(token);
1568 if (stack != null) {
1569 stack.activityPausedLocked(token, false);
1570 }
1571 }
1572 Binder.restoreCallingIdentity(origId);
1573 }
1574
1575 @Override
1576 public final void activityStopped(IBinder token, Bundle icicle,
1577 PersistableBundle persistentState, CharSequence description) {
1578 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1579
1580 // Refuse possible leaked file descriptors
1581 if (icicle != null && icicle.hasFileDescriptors()) {
1582 throw new IllegalArgumentException("File descriptors passed in Bundle");
1583 }
1584
1585 final long origId = Binder.clearCallingIdentity();
1586
1587 synchronized (mGlobalLock) {
1588 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1589 if (r != null) {
1590 r.activityStoppedLocked(icicle, persistentState, description);
1591 }
1592 }
1593
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001594 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595
1596 Binder.restoreCallingIdentity(origId);
1597 }
1598
1599 @Override
1600 public final void activityDestroyed(IBinder token) {
1601 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1602 synchronized (mGlobalLock) {
1603 ActivityStack stack = ActivityRecord.getStackLocked(token);
1604 if (stack != null) {
1605 stack.activityDestroyedLocked(token, "activityDestroyed");
1606 }
1607 }
1608 }
1609
1610 @Override
1611 public final void activityRelaunched(IBinder token) {
1612 final long origId = Binder.clearCallingIdentity();
1613 synchronized (mGlobalLock) {
1614 mStackSupervisor.activityRelaunchedLocked(token);
1615 }
1616 Binder.restoreCallingIdentity(origId);
1617 }
1618
1619 public final void activitySlept(IBinder token) {
1620 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1621
1622 final long origId = Binder.clearCallingIdentity();
1623
1624 synchronized (mGlobalLock) {
1625 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1626 if (r != null) {
1627 mStackSupervisor.activitySleptLocked(r);
1628 }
1629 }
1630
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633
1634 @Override
1635 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1636 synchronized (mGlobalLock) {
1637 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1638 if (r == null) {
1639 return;
1640 }
1641 final long origId = Binder.clearCallingIdentity();
1642 try {
1643 r.setRequestedOrientation(requestedOrientation);
1644 } finally {
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647 }
1648 }
1649
1650 @Override
1651 public int getRequestedOrientation(IBinder token) {
1652 synchronized (mGlobalLock) {
1653 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1654 if (r == null) {
1655 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1656 }
1657 return r.getRequestedOrientation();
1658 }
1659 }
1660
1661 @Override
1662 public void setImmersive(IBinder token, boolean immersive) {
1663 synchronized (mGlobalLock) {
1664 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1665 if (r == null) {
1666 throw new IllegalArgumentException();
1667 }
1668 r.immersive = immersive;
1669
1670 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001671 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001672 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001673 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 }
1675 }
1676 }
1677
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001678 void applyUpdateLockStateLocked(ActivityRecord r) {
1679 // Modifications to the UpdateLock state are done on our handler, outside
1680 // the activity manager's locks. The new state is determined based on the
1681 // state *now* of the relevant activity record. The object is passed to
1682 // the handler solely for logging detail, not to be consulted/modified.
1683 final boolean nextState = r != null && r.immersive;
1684 mH.post(() -> {
1685 if (mUpdateLock.isHeld() != nextState) {
1686 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1687 "Applying new update lock state '" + nextState + "' for " + r);
1688 if (nextState) {
1689 mUpdateLock.acquire();
1690 } else {
1691 mUpdateLock.release();
1692 }
1693 }
1694 });
1695 }
1696
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 @Override
1698 public boolean isImmersive(IBinder token) {
1699 synchronized (mGlobalLock) {
1700 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1701 if (r == null) {
1702 throw new IllegalArgumentException();
1703 }
1704 return r.immersive;
1705 }
1706 }
1707
1708 @Override
1709 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001710 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001712 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 return (r != null) ? r.immersive : false;
1714 }
1715 }
1716
1717 @Override
1718 public void overridePendingTransition(IBinder token, String packageName,
1719 int enterAnim, int exitAnim) {
1720 synchronized (mGlobalLock) {
1721 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1722 if (self == null) {
1723 return;
1724 }
1725
1726 final long origId = Binder.clearCallingIdentity();
1727
1728 if (self.isState(
1729 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001730 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1731 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001732 }
1733
1734 Binder.restoreCallingIdentity(origId);
1735 }
1736 }
1737
1738 @Override
1739 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001740 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001741 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001742 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001743 if (r == null) {
1744 return ActivityManager.COMPAT_MODE_UNKNOWN;
1745 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001746 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747 }
1748 }
1749
1750 @Override
1751 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001752 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001754 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001755 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001756 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001757 if (r == null) {
1758 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1759 return;
1760 }
1761 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001762 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001763 }
1764 }
1765
1766 @Override
1767 public int getLaunchedFromUid(IBinder activityToken) {
1768 ActivityRecord srec;
1769 synchronized (mGlobalLock) {
1770 srec = ActivityRecord.forTokenLocked(activityToken);
1771 }
1772 if (srec == null) {
1773 return -1;
1774 }
1775 return srec.launchedFromUid;
1776 }
1777
1778 @Override
1779 public String getLaunchedFromPackage(IBinder activityToken) {
1780 ActivityRecord srec;
1781 synchronized (mGlobalLock) {
1782 srec = ActivityRecord.forTokenLocked(activityToken);
1783 }
1784 if (srec == null) {
1785 return null;
1786 }
1787 return srec.launchedFromPackage;
1788 }
1789
1790 @Override
1791 public boolean convertFromTranslucent(IBinder token) {
1792 final long origId = Binder.clearCallingIdentity();
1793 try {
1794 synchronized (mGlobalLock) {
1795 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1796 if (r == null) {
1797 return false;
1798 }
1799 final boolean translucentChanged = r.changeWindowTranslucency(true);
1800 if (translucentChanged) {
1801 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1802 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001803 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 return translucentChanged;
1805 }
1806 } finally {
1807 Binder.restoreCallingIdentity(origId);
1808 }
1809 }
1810
1811 @Override
1812 public boolean convertToTranslucent(IBinder token, Bundle options) {
1813 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1814 final long origId = Binder.clearCallingIdentity();
1815 try {
1816 synchronized (mGlobalLock) {
1817 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1818 if (r == null) {
1819 return false;
1820 }
1821 final TaskRecord task = r.getTask();
1822 int index = task.mActivities.lastIndexOf(r);
1823 if (index > 0) {
1824 ActivityRecord under = task.mActivities.get(index - 1);
1825 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1826 }
1827 final boolean translucentChanged = r.changeWindowTranslucency(false);
1828 if (translucentChanged) {
1829 r.getStack().convertActivityToTranslucent(r);
1830 }
1831 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001832 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 return translucentChanged;
1834 }
1835 } finally {
1836 Binder.restoreCallingIdentity(origId);
1837 }
1838 }
1839
1840 @Override
1841 public void notifyActivityDrawn(IBinder token) {
1842 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1843 synchronized (mGlobalLock) {
1844 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1845 if (r != null) {
1846 r.getStack().notifyActivityDrawnLocked(r);
1847 }
1848 }
1849 }
1850
1851 @Override
1852 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1853 synchronized (mGlobalLock) {
1854 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1855 if (r == null) {
1856 return;
1857 }
1858 r.reportFullyDrawnLocked(restoredFromBundle);
1859 }
1860 }
1861
1862 @Override
1863 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1864 synchronized (mGlobalLock) {
1865 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1866 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1867 return stack.mDisplayId;
1868 }
1869 return DEFAULT_DISPLAY;
1870 }
1871 }
1872
1873 @Override
1874 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001875 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 long ident = Binder.clearCallingIdentity();
1877 try {
1878 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001879 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 if (focusedStack != null) {
1881 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1882 }
1883 return null;
1884 }
1885 } finally {
1886 Binder.restoreCallingIdentity(ident);
1887 }
1888 }
1889
1890 @Override
1891 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1894 final long callingId = Binder.clearCallingIdentity();
1895 try {
1896 synchronized (mGlobalLock) {
1897 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1898 if (stack == null) {
1899 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1900 return;
1901 }
1902 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001903 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001904 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 }
1906 }
1907 } finally {
1908 Binder.restoreCallingIdentity(callingId);
1909 }
1910 }
1911
1912 @Override
1913 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001914 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1916 final long callingId = Binder.clearCallingIdentity();
1917 try {
1918 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001919 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1920 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 if (task == null) {
1922 return;
1923 }
1924 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001925 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001926 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 }
1928 }
1929 } finally {
1930 Binder.restoreCallingIdentity(callingId);
1931 }
1932 }
1933
1934 @Override
1935 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 synchronized (mGlobalLock) {
1938 final long ident = Binder.clearCallingIdentity();
1939 try {
1940 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1941 "remove-task");
1942 } finally {
1943 Binder.restoreCallingIdentity(ident);
1944 }
1945 }
1946 }
1947
1948 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001949 public void removeAllVisibleRecentTasks() {
1950 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1951 synchronized (mGlobalLock) {
1952 final long ident = Binder.clearCallingIdentity();
1953 try {
1954 getRecentTasks().removeAllVisibleTasks();
1955 } finally {
1956 Binder.restoreCallingIdentity(ident);
1957 }
1958 }
1959 }
1960
1961 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1963 synchronized (mGlobalLock) {
1964 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1965 if (srec != null) {
1966 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1967 }
1968 }
1969 return false;
1970 }
1971
1972 @Override
1973 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1974 Intent resultData) {
1975
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1978 if (r != null) {
1979 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1980 }
1981 return false;
1982 }
1983 }
1984
1985 /**
1986 * Attempts to move a task backwards in z-order (the order of activities within the task is
1987 * unchanged).
1988 *
1989 * There are several possible results of this call:
1990 * - if the task is locked, then we will show the lock toast
1991 * - if there is a task behind the provided task, then that task is made visible and resumed as
1992 * this task is moved to the back
1993 * - otherwise, if there are no other tasks in the stack:
1994 * - if this task is in the pinned stack, then we remove the stack completely, which will
1995 * have the effect of moving the task to the top or bottom of the fullscreen stack
1996 * (depending on whether it is visible)
1997 * - otherwise, we simply return home and hide this task
1998 *
1999 * @param token A reference to the activity we wish to move
2000 * @param nonRoot If false then this only works if the activity is the root
2001 * of a task; if true it will work for any activity in a task.
2002 * @return Returns true if the move completed, false if not.
2003 */
2004 @Override
2005 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002006 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 synchronized (mGlobalLock) {
2008 final long origId = Binder.clearCallingIdentity();
2009 try {
2010 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
2011 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2012 if (task != null) {
2013 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2014 }
2015 } finally {
2016 Binder.restoreCallingIdentity(origId);
2017 }
2018 }
2019 return false;
2020 }
2021
2022 @Override
2023 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002024 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 long ident = Binder.clearCallingIdentity();
2026 Rect rect = new Rect();
2027 try {
2028 synchronized (mGlobalLock) {
2029 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2030 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2031 if (task == null) {
2032 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2033 return rect;
2034 }
2035 if (task.getStack() != null) {
2036 // Return the bounds from window manager since it will be adjusted for various
2037 // things like the presense of a docked stack for tasks that aren't resizeable.
2038 task.getWindowContainerBounds(rect);
2039 } else {
2040 // Task isn't in window manager yet since it isn't associated with a stack.
2041 // Return the persist value from activity manager
2042 if (!task.matchParentBounds()) {
2043 rect.set(task.getBounds());
2044 } else if (task.mLastNonFullscreenBounds != null) {
2045 rect.set(task.mLastNonFullscreenBounds);
2046 }
2047 }
2048 }
2049 } finally {
2050 Binder.restoreCallingIdentity(ident);
2051 }
2052 return rect;
2053 }
2054
2055 @Override
2056 public ActivityManager.TaskDescription getTaskDescription(int id) {
2057 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002058 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
2060 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
2061 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2062 if (tr != null) {
2063 return tr.lastTaskDescription;
2064 }
2065 }
2066 return null;
2067 }
2068
2069 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002070 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2071 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2072 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2073 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2074 return;
2075 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002076 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002077 synchronized (mGlobalLock) {
2078 final long ident = Binder.clearCallingIdentity();
2079 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002080 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2081 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002082 if (task == null) {
2083 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2084 return;
2085 }
2086
2087 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2088 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2089
2090 if (!task.isActivityTypeStandardOrUndefined()) {
2091 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2092 + " non-standard task " + taskId + " to windowing mode="
2093 + windowingMode);
2094 }
2095
2096 final ActivityStack stack = task.getStack();
2097 if (toTop) {
2098 stack.moveToFront("setTaskWindowingMode", task);
2099 }
2100 stack.setWindowingMode(windowingMode);
2101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
2104 }
2105 }
2106
2107 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002109 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 ActivityRecord r = getCallingRecordLocked(token);
2111 return r != null ? r.info.packageName : null;
2112 }
2113 }
2114
2115 @Override
2116 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002117 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 ActivityRecord r = getCallingRecordLocked(token);
2119 return r != null ? r.intent.getComponent() : null;
2120 }
2121 }
2122
2123 private ActivityRecord getCallingRecordLocked(IBinder token) {
2124 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2125 if (r == null) {
2126 return null;
2127 }
2128 return r.resultTo;
2129 }
2130
2131 @Override
2132 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002133 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134
2135 synchronized (mGlobalLock) {
2136 final long origId = Binder.clearCallingIdentity();
2137 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002138 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002139 } finally {
2140 Binder.restoreCallingIdentity(origId);
2141 }
2142 }
2143 }
2144
2145 /**
2146 * TODO: Add mController hook
2147 */
2148 @Override
2149 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002150 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002151
2152 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2153 synchronized (mGlobalLock) {
2154 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2155 false /* fromRecents */);
2156 }
2157 }
2158
2159 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2160 boolean fromRecents) {
2161
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002162 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 Binder.getCallingUid(), -1, -1, "Task to front")) {
2164 SafeActivityOptions.abort(options);
2165 return;
2166 }
2167 final long origId = Binder.clearCallingIdentity();
2168 try {
2169 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2170 if (task == null) {
2171 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002172 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002173 return;
2174 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002175 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002177 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 return;
2179 }
2180 ActivityOptions realOptions = options != null
2181 ? options.getOptions(mStackSupervisor)
2182 : null;
2183 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2184 false /* forceNonResizable */);
2185
2186 final ActivityRecord topActivity = task.getTopActivity();
2187 if (topActivity != null) {
2188
2189 // We are reshowing a task, use a starting window to hide the initial draw delay
2190 // so the transition can start earlier.
2191 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2192 true /* taskSwitch */, fromRecents);
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(origId);
2196 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 }
2198
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002199 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2200 int callingPid, int callingUid, String name) {
2201 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2202 return true;
2203 }
2204
2205 if (getRecentTasks().isCallerRecents(sourceUid)) {
2206 return true;
2207 }
2208
2209 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2210 if (perm == PackageManager.PERMISSION_GRANTED) {
2211 return true;
2212 }
2213 if (checkAllowAppSwitchUid(sourceUid)) {
2214 return true;
2215 }
2216
2217 // If the actual IPC caller is different from the logical source, then
2218 // also see if they are allowed to control app switches.
2219 if (callingUid != -1 && callingUid != sourceUid) {
2220 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2221 if (perm == PackageManager.PERMISSION_GRANTED) {
2222 return true;
2223 }
2224 if (checkAllowAppSwitchUid(callingUid)) {
2225 return true;
2226 }
2227 }
2228
2229 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2230 return false;
2231 }
2232
2233 private boolean checkAllowAppSwitchUid(int uid) {
2234 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2235 if (types != null) {
2236 for (int i = types.size() - 1; i >= 0; i--) {
2237 if (types.valueAt(i).intValue() == uid) {
2238 return true;
2239 }
2240 }
2241 }
2242 return false;
2243 }
2244
2245 @Override
2246 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2247 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2248 "setActivityController()");
2249 synchronized (mGlobalLock) {
2250 mController = controller;
2251 mControllerIsAMonkey = imAMonkey;
2252 Watchdog.getInstance().setActivityController(controller);
2253 }
2254 }
2255
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002256 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002257 synchronized (mGlobalLock) {
2258 return mController != null && mControllerIsAMonkey;
2259 }
2260 }
2261
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 @Override
2263 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2264 synchronized (mGlobalLock) {
2265 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2266 }
2267 }
2268
2269 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002270 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2271 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2272 }
2273
2274 @Override
2275 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2276 @WindowConfiguration.ActivityType int ignoreActivityType,
2277 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2278 final int callingUid = Binder.getCallingUid();
2279 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2280
2281 synchronized (mGlobalLock) {
2282 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2283
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002285 callingUid);
2286 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2287 ignoreWindowingMode, callingUid, allowed);
2288 }
2289
2290 return list;
2291 }
2292
2293 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2295 synchronized (mGlobalLock) {
2296 final long origId = Binder.clearCallingIdentity();
2297 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2298 if (r != null) {
2299 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2300 }
2301 Binder.restoreCallingIdentity(origId);
2302 }
2303 }
2304
2305 @Override
2306 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002307 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 ActivityStack stack = ActivityRecord.getStackLocked(token);
2309 if (stack != null) {
2310 return stack.willActivityBeVisibleLocked(token);
2311 }
2312 return false;
2313 }
2314 }
2315
2316 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002317 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002318 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002319 synchronized (mGlobalLock) {
2320 final long ident = Binder.clearCallingIdentity();
2321 try {
2322 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2323 if (task == null) {
2324 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2325 return;
2326 }
2327
2328 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2329 + " to stackId=" + stackId + " toTop=" + toTop);
2330
2331 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2332 if (stack == null) {
2333 throw new IllegalStateException(
2334 "moveTaskToStack: No stack for stackId=" + stackId);
2335 }
2336 if (!stack.isActivityTypeStandardOrUndefined()) {
2337 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2338 + taskId + " to stack " + stackId);
2339 }
2340 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002341 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002342 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2343 }
2344 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2345 "moveTaskToStack");
2346 } finally {
2347 Binder.restoreCallingIdentity(ident);
2348 }
2349 }
2350 }
2351
2352 @Override
2353 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2354 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002355 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002356
2357 final long ident = Binder.clearCallingIdentity();
2358 try {
2359 synchronized (mGlobalLock) {
2360 if (animate) {
2361 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2362 if (stack == null) {
2363 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2364 return;
2365 }
2366 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2367 throw new IllegalArgumentException("Stack: " + stackId
2368 + " doesn't support animated resize.");
2369 }
2370 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2371 animationDuration, false /* fromFullscreen */);
2372 } else {
2373 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2374 if (stack == null) {
2375 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2376 return;
2377 }
2378 mStackSupervisor.resizeStackLocked(stack, destBounds,
2379 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2380 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2381 }
2382 }
2383 } finally {
2384 Binder.restoreCallingIdentity(ident);
2385 }
2386 }
2387
2388 /**
2389 * Moves the specified task to the primary-split-screen stack.
2390 *
2391 * @param taskId Id of task to move.
2392 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2393 * exist already. See
2394 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2395 * and
2396 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2397 * @param toTop If the task and stack should be moved to the top.
2398 * @param animate Whether we should play an animation for the moving the task.
2399 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2400 * stack. Pass {@code null} to use default bounds.
2401 * @param showRecents If the recents activity should be shown on the other side of the task
2402 * going into split-screen mode.
2403 */
2404 @Override
2405 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2406 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002407 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002408 "setTaskWindowingModeSplitScreenPrimary()");
2409 synchronized (mGlobalLock) {
2410 final long ident = Binder.clearCallingIdentity();
2411 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002412 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2413 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002414 if (task == null) {
2415 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2416 return false;
2417 }
2418 if (DEBUG_STACK) Slog.d(TAG_STACK,
2419 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2420 + " to createMode=" + createMode + " toTop=" + toTop);
2421 if (!task.isActivityTypeStandardOrUndefined()) {
2422 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2423 + " non-standard task " + taskId + " to split-screen windowing mode");
2424 }
2425
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002426 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002427 final int windowingMode = task.getWindowingMode();
2428 final ActivityStack stack = task.getStack();
2429 if (toTop) {
2430 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2431 }
2432 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2433 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2434 return windowingMode != task.getWindowingMode();
2435 } finally {
2436 Binder.restoreCallingIdentity(ident);
2437 }
2438 }
2439 }
2440
2441 /**
2442 * Removes stacks in the input windowing modes from the system if they are of activity type
2443 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2444 */
2445 @Override
2446 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002447 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002448 "removeStacksInWindowingModes()");
2449
2450 synchronized (mGlobalLock) {
2451 final long ident = Binder.clearCallingIdentity();
2452 try {
2453 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2454 } finally {
2455 Binder.restoreCallingIdentity(ident);
2456 }
2457 }
2458 }
2459
2460 @Override
2461 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002462 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002463 "removeStacksWithActivityTypes()");
2464
2465 synchronized (mGlobalLock) {
2466 final long ident = Binder.clearCallingIdentity();
2467 try {
2468 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2469 } finally {
2470 Binder.restoreCallingIdentity(ident);
2471 }
2472 }
2473 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002474
2475 @Override
2476 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2477 int userId) {
2478 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002479 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2480 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002481 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002482 final boolean detailed = checkGetTasksPermission(
2483 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2484 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002485 == PackageManager.PERMISSION_GRANTED;
2486
2487 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002488 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002489 callingUid);
2490 }
2491 }
2492
2493 @Override
2494 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002495 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002496 long ident = Binder.clearCallingIdentity();
2497 try {
2498 synchronized (mGlobalLock) {
2499 return mStackSupervisor.getAllStackInfosLocked();
2500 }
2501 } finally {
2502 Binder.restoreCallingIdentity(ident);
2503 }
2504 }
2505
2506 @Override
2507 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002508 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002509 long ident = Binder.clearCallingIdentity();
2510 try {
2511 synchronized (mGlobalLock) {
2512 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2513 }
2514 } finally {
2515 Binder.restoreCallingIdentity(ident);
2516 }
2517 }
2518
2519 @Override
2520 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002521 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002522 final long callingUid = Binder.getCallingUid();
2523 final long origId = Binder.clearCallingIdentity();
2524 try {
2525 synchronized (mGlobalLock) {
2526 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002527 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2529 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2530 }
2531 } finally {
2532 Binder.restoreCallingIdentity(origId);
2533 }
2534 }
2535
2536 @Override
2537 public void startLockTaskModeByToken(IBinder token) {
2538 synchronized (mGlobalLock) {
2539 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2540 if (r == null) {
2541 return;
2542 }
2543 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2544 }
2545 }
2546
2547 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002548 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002549 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 // This makes inner call to look as if it was initiated by system.
2551 long ident = Binder.clearCallingIdentity();
2552 try {
2553 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002554 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2555 MATCH_TASK_IN_STACKS_ONLY);
2556 if (task == null) {
2557 return;
2558 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002559
2560 // When starting lock task mode the stack must be in front and focused
2561 task.getStack().moveToFront("startSystemLockTaskMode");
2562 startLockTaskModeLocked(task, true /* isSystemCaller */);
2563 }
2564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
2568
2569 @Override
2570 public void stopLockTaskModeByToken(IBinder token) {
2571 synchronized (mGlobalLock) {
2572 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2573 if (r == null) {
2574 return;
2575 }
2576 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2577 }
2578 }
2579
2580 /**
2581 * This API should be called by SystemUI only when user perform certain action to dismiss
2582 * lock task mode. We should only dismiss pinned lock task mode in this case.
2583 */
2584 @Override
2585 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002586 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002587 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2588 }
2589
2590 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2591 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2592 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2593 return;
2594 }
2595
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002596 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002597 if (stack == null || task != stack.topTask()) {
2598 throw new IllegalArgumentException("Invalid task, not in foreground");
2599 }
2600
2601 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2602 // system or a specific app.
2603 // * System-initiated requests will only start the pinned mode (screen pinning)
2604 // * App-initiated requests
2605 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2606 // - will start the pinned mode, otherwise
2607 final int callingUid = Binder.getCallingUid();
2608 long ident = Binder.clearCallingIdentity();
2609 try {
2610 // When a task is locked, dismiss the pinned stack if it exists
2611 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2612
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002613 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002614 } finally {
2615 Binder.restoreCallingIdentity(ident);
2616 }
2617 }
2618
2619 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2620 final int callingUid = Binder.getCallingUid();
2621 long ident = Binder.clearCallingIdentity();
2622 try {
2623 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002624 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002625 }
2626 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2627 // task and jumping straight into a call in the case of emergency call back.
2628 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2629 if (tm != null) {
2630 tm.showInCallScreen(false);
2631 }
2632 } finally {
2633 Binder.restoreCallingIdentity(ident);
2634 }
2635 }
2636
2637 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002638 public void updateLockTaskPackages(int userId, String[] packages) {
2639 final int callingUid = Binder.getCallingUid();
2640 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2641 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2642 "updateLockTaskPackages()");
2643 }
2644 synchronized (this) {
2645 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2646 + Arrays.toString(packages));
2647 getLockTaskController().updateLockTaskPackages(userId, packages);
2648 }
2649 }
2650
2651 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002652 public boolean isInLockTaskMode() {
2653 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2654 }
2655
2656 @Override
2657 public int getLockTaskModeState() {
2658 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002659 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002660 }
2661 }
2662
2663 @Override
2664 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2665 synchronized (mGlobalLock) {
2666 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2667 if (r != null) {
2668 r.setTaskDescription(td);
2669 final TaskRecord task = r.getTask();
2670 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002671 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002672 }
2673 }
2674 }
2675
2676 @Override
2677 public Bundle getActivityOptions(IBinder token) {
2678 final long origId = Binder.clearCallingIdentity();
2679 try {
2680 synchronized (mGlobalLock) {
2681 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2682 if (r != null) {
2683 final ActivityOptions activityOptions = r.takeOptionsLocked();
2684 return activityOptions == null ? null : activityOptions.toBundle();
2685 }
2686 return null;
2687 }
2688 } finally {
2689 Binder.restoreCallingIdentity(origId);
2690 }
2691 }
2692
2693 @Override
2694 public List<IBinder> getAppTasks(String callingPackage) {
2695 int callingUid = Binder.getCallingUid();
2696 long ident = Binder.clearCallingIdentity();
2697 try {
2698 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002699 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002700 }
2701 } finally {
2702 Binder.restoreCallingIdentity(ident);
2703 }
2704 }
2705
2706 @Override
2707 public void finishVoiceTask(IVoiceInteractionSession session) {
2708 synchronized (mGlobalLock) {
2709 final long origId = Binder.clearCallingIdentity();
2710 try {
2711 // TODO: VI Consider treating local voice interactions and voice tasks
2712 // differently here
2713 mStackSupervisor.finishVoiceTask(session);
2714 } finally {
2715 Binder.restoreCallingIdentity(origId);
2716 }
2717 }
2718
2719 }
2720
2721 @Override
2722 public boolean isTopOfTask(IBinder token) {
2723 synchronized (mGlobalLock) {
2724 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002725 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002726 }
2727 }
2728
2729 @Override
2730 public void notifyLaunchTaskBehindComplete(IBinder token) {
2731 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2732 }
2733
2734 @Override
2735 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002736 mH.post(() -> {
2737 synchronized (mGlobalLock) {
2738 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002739 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002740 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002741 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002742 } catch (RemoteException e) {
2743 }
2744 }
2745 }
2746
2747 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002748 }
2749
2750 /** Called from an app when assist data is ready. */
2751 @Override
2752 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2753 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002754 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 synchronized (pae) {
2756 pae.result = extras;
2757 pae.structure = structure;
2758 pae.content = content;
2759 if (referrer != null) {
2760 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2761 }
2762 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002763 // Pre-fill the task/activity component for all assist data receivers
2764 structure.setTaskId(pae.activity.getTask().taskId);
2765 structure.setActivityComponent(pae.activity.realActivity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 structure.setHomeActivity(pae.isHome);
2767 }
2768 pae.haveResult = true;
2769 pae.notifyAll();
2770 if (pae.intent == null && pae.receiver == null) {
2771 // Caller is just waiting for the result.
2772 return;
2773 }
2774 }
2775 // We are now ready to launch the assist activity.
2776 IAssistDataReceiver sendReceiver = null;
2777 Bundle sendBundle = null;
2778 synchronized (mGlobalLock) {
2779 buildAssistBundleLocked(pae, extras);
2780 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002781 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 if (!exists) {
2783 // Timed out.
2784 return;
2785 }
2786
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002788 // Caller wants result sent back to them.
2789 sendBundle = new Bundle();
2790 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2791 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2792 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2793 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2794 }
2795 }
2796 if (sendReceiver != null) {
2797 try {
2798 sendReceiver.onHandleAssistData(sendBundle);
2799 } catch (RemoteException e) {
2800 }
2801 return;
2802 }
2803
2804 final long ident = Binder.clearCallingIdentity();
2805 try {
2806 if (TextUtils.equals(pae.intent.getAction(),
2807 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2808 pae.intent.putExtras(pae.extras);
2809 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2810 } else {
2811 pae.intent.replaceExtras(pae.extras);
2812 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2813 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2814 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002815 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816
2817 try {
2818 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2819 } catch (ActivityNotFoundException e) {
2820 Slog.w(TAG, "No activity to handle assist action.", e);
2821 }
2822 }
2823 } finally {
2824 Binder.restoreCallingIdentity(ident);
2825 }
2826 }
2827
2828 @Override
2829 public int addAppTask(IBinder activityToken, Intent intent,
2830 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2831 final int callingUid = Binder.getCallingUid();
2832 final long callingIdent = Binder.clearCallingIdentity();
2833
2834 try {
2835 synchronized (mGlobalLock) {
2836 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2837 if (r == null) {
2838 throw new IllegalArgumentException("Activity does not exist; token="
2839 + activityToken);
2840 }
2841 ComponentName comp = intent.getComponent();
2842 if (comp == null) {
2843 throw new IllegalArgumentException("Intent " + intent
2844 + " must specify explicit component");
2845 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002846 if (thumbnail.getWidth() != mThumbnailWidth
2847 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 throw new IllegalArgumentException("Bad thumbnail size: got "
2849 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002850 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002851 }
2852 if (intent.getSelector() != null) {
2853 intent.setSelector(null);
2854 }
2855 if (intent.getSourceBounds() != null) {
2856 intent.setSourceBounds(null);
2857 }
2858 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2859 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2860 // The caller has added this as an auto-remove task... that makes no
2861 // sense, so turn off auto-remove.
2862 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2863 }
2864 }
2865 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2866 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2867 if (ainfo.applicationInfo.uid != callingUid) {
2868 throw new SecurityException(
2869 "Can't add task for another application: target uid="
2870 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2871 }
2872
2873 final ActivityStack stack = r.getStack();
2874 final TaskRecord task = stack.createTaskRecord(
2875 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2876 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002877 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002878 // The app has too many tasks already and we can't add any more
2879 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2880 return INVALID_TASK_ID;
2881 }
2882 task.lastTaskDescription.copyFrom(description);
2883
2884 // TODO: Send the thumbnail to WM to store it.
2885
2886 return task.taskId;
2887 }
2888 } finally {
2889 Binder.restoreCallingIdentity(callingIdent);
2890 }
2891 }
2892
2893 @Override
2894 public Point getAppTaskThumbnailSize() {
2895 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002896 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 }
2898 }
2899
2900 @Override
2901 public void setTaskResizeable(int taskId, int resizeableMode) {
2902 synchronized (mGlobalLock) {
2903 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2904 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2905 if (task == null) {
2906 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2907 return;
2908 }
2909 task.setResizeMode(resizeableMode);
2910 }
2911 }
2912
2913 @Override
2914 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002915 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916 long ident = Binder.clearCallingIdentity();
2917 try {
2918 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002919 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2920 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 if (task == null) {
2922 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2923 return;
2924 }
2925 // Place the task in the right stack if it isn't there already based on
2926 // the requested bounds.
2927 // The stack transition logic is:
2928 // - a null bounds on a freeform task moves that task to fullscreen
2929 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2930 // that task to freeform
2931 // - otherwise the task is not moved
2932 ActivityStack stack = task.getStack();
2933 if (!task.getWindowConfiguration().canResizeTask()) {
2934 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2935 }
2936 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2937 stack = stack.getDisplay().getOrCreateStack(
2938 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2939 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2940 stack = stack.getDisplay().getOrCreateStack(
2941 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2942 }
2943
2944 // Reparent the task to the right stack if necessary
2945 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2946 if (stack != task.getStack()) {
2947 // Defer resume until the task is resized below
2948 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2949 DEFER_RESUME, "resizeTask");
2950 preserveWindow = false;
2951 }
2952
2953 // After reparenting (which only resizes the task to the stack bounds), resize the
2954 // task to the actual bounds provided
2955 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2956 }
2957 } finally {
2958 Binder.restoreCallingIdentity(ident);
2959 }
2960 }
2961
2962 @Override
2963 public boolean releaseActivityInstance(IBinder token) {
2964 synchronized (mGlobalLock) {
2965 final long origId = Binder.clearCallingIdentity();
2966 try {
2967 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2968 if (r == null) {
2969 return false;
2970 }
2971 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2972 } finally {
2973 Binder.restoreCallingIdentity(origId);
2974 }
2975 }
2976 }
2977
2978 @Override
2979 public void releaseSomeActivities(IApplicationThread appInt) {
2980 synchronized (mGlobalLock) {
2981 final long origId = Binder.clearCallingIdentity();
2982 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002983 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2985 } finally {
2986 Binder.restoreCallingIdentity(origId);
2987 }
2988 }
2989 }
2990
2991 @Override
2992 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002993 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002994 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 != PackageManager.PERMISSION_GRANTED) {
2996 throw new SecurityException("Requires permission "
2997 + android.Manifest.permission.DEVICE_POWER);
2998 }
2999
3000 synchronized (mGlobalLock) {
3001 long ident = Binder.clearCallingIdentity();
3002 if (mKeyguardShown != keyguardShowing) {
3003 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003004 final Message msg = PooledLambda.obtainMessage(
3005 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3006 keyguardShowing);
3007 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 }
3009 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003010 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003011 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003012 } finally {
3013 Binder.restoreCallingIdentity(ident);
3014 }
3015 }
3016
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003017 mH.post(() -> {
3018 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3019 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3020 }
3021 });
3022 }
3023
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003024 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003025 mH.post(() -> {
3026 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3027 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3028 }
3029 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 }
3031
3032 @Override
3033 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003034 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3035 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036
3037 final File passedIconFile = new File(filePath);
3038 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3039 passedIconFile.getName());
3040 if (!legitIconFile.getPath().equals(filePath)
3041 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3042 throw new IllegalArgumentException("Bad file path: " + filePath
3043 + " passed for userId " + userId);
3044 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003045 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 }
3047
3048 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003049 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3051 final ActivityOptions activityOptions = safeOptions != null
3052 ? safeOptions.getOptions(mStackSupervisor)
3053 : null;
3054 if (activityOptions == null
3055 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3056 || activityOptions.getCustomInPlaceResId() == 0) {
3057 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3058 "with valid animation");
3059 }
lumark588a3e82018-07-20 18:53:54 +08003060 // Get top display of front most application.
3061 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3062 if (focusedStack != null) {
3063 final DisplayWindowController dwc =
3064 focusedStack.getDisplay().getWindowContainerController();
3065 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3066 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3067 activityOptions.getCustomInPlaceResId());
3068 dwc.executeAppTransition();
3069 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 }
3071
3072 @Override
3073 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 synchronized (mGlobalLock) {
3076 final long ident = Binder.clearCallingIdentity();
3077 try {
3078 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3079 if (stack == null) {
3080 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3081 return;
3082 }
3083 if (!stack.isActivityTypeStandardOrUndefined()) {
3084 throw new IllegalArgumentException(
3085 "Removing non-standard stack is not allowed.");
3086 }
3087 mStackSupervisor.removeStack(stack);
3088 } finally {
3089 Binder.restoreCallingIdentity(ident);
3090 }
3091 }
3092 }
3093
3094 @Override
3095 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003096 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097
3098 synchronized (mGlobalLock) {
3099 final long ident = Binder.clearCallingIdentity();
3100 try {
3101 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3102 + " to displayId=" + displayId);
3103 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
3104 } finally {
3105 Binder.restoreCallingIdentity(ident);
3106 }
3107 }
3108 }
3109
3110 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 public void exitFreeformMode(IBinder token) {
3112 synchronized (mGlobalLock) {
3113 long ident = Binder.clearCallingIdentity();
3114 try {
3115 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3116 if (r == null) {
3117 throw new IllegalArgumentException(
3118 "exitFreeformMode: No activity record matching token=" + token);
3119 }
3120
3121 final ActivityStack stack = r.getStack();
3122 if (stack == null || !stack.inFreeformWindowingMode()) {
3123 throw new IllegalStateException(
3124 "exitFreeformMode: You can only go fullscreen from freeform.");
3125 }
3126
3127 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3128 } finally {
3129 Binder.restoreCallingIdentity(ident);
3130 }
3131 }
3132 }
3133
3134 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3135 @Override
3136 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003137 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003139 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 }
3141
3142 /** Unregister a task stack listener so that it stops receiving callbacks. */
3143 @Override
3144 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003145 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003147 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 }
3149
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 @Override
3151 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3152 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3153 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3154 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3155 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3156 }
3157
3158 @Override
3159 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3160 IBinder activityToken, int flags) {
3161 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3162 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3163 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3164 }
3165
3166 @Override
3167 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3168 Bundle args) {
3169 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3170 true /* focused */, true /* newSessionId */, userHandle, args,
3171 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3172 }
3173
3174 @Override
3175 public Bundle getAssistContextExtras(int requestType) {
3176 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3177 null, null, true /* focused */, true /* newSessionId */,
3178 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3179 if (pae == null) {
3180 return null;
3181 }
3182 synchronized (pae) {
3183 while (!pae.haveResult) {
3184 try {
3185 pae.wait();
3186 } catch (InterruptedException e) {
3187 }
3188 }
3189 }
3190 synchronized (mGlobalLock) {
3191 buildAssistBundleLocked(pae, pae.result);
3192 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003193 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 }
3195 return pae.extras;
3196 }
3197
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003198 /**
3199 * Binder IPC calls go through the public entry point.
3200 * This can be called with or without the global lock held.
3201 */
3202 private static int checkCallingPermission(String permission) {
3203 return checkPermission(
3204 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3205 }
3206
3207 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003208 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003209 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3210 mAmInternal.enforceCallingPermission(permission, func);
3211 }
3212 }
3213
3214 @VisibleForTesting
3215 int checkGetTasksPermission(String permission, int pid, int uid) {
3216 return checkPermission(permission, pid, uid);
3217 }
3218
3219 static int checkPermission(String permission, int pid, int uid) {
3220 if (permission == null) {
3221 return PackageManager.PERMISSION_DENIED;
3222 }
3223 return checkComponentPermission(permission, pid, uid, -1, true);
3224 }
3225
Wale Ogunwale214f3482018-10-04 11:00:47 -07003226 public static int checkComponentPermission(String permission, int pid, int uid,
3227 int owningUid, boolean exported) {
3228 return ActivityManagerService.checkComponentPermission(
3229 permission, pid, uid, owningUid, exported);
3230 }
3231
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003232 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3233 if (getRecentTasks().isCallerRecents(callingUid)) {
3234 // Always allow the recents component to get tasks
3235 return true;
3236 }
3237
3238 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3239 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3240 if (!allowed) {
3241 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3242 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3243 // Temporary compatibility: some existing apps on the system image may
3244 // still be requesting the old permission and not switched to the new
3245 // one; if so, we'll still allow them full access. This means we need
3246 // to see if they are holding the old permission and are a system app.
3247 try {
3248 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3249 allowed = true;
3250 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3251 + " is using old GET_TASKS but privileged; allowing");
3252 }
3253 } catch (RemoteException e) {
3254 }
3255 }
3256 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3257 + " does not hold REAL_GET_TASKS; limiting output");
3258 }
3259 return allowed;
3260 }
3261
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3263 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3264 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3265 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003266 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 "enqueueAssistContext()");
3268
3269 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003270 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 if (activity == null) {
3272 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3273 return null;
3274 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003275 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3277 return null;
3278 }
3279 if (focused) {
3280 if (activityToken != null) {
3281 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3282 if (activity != caller) {
3283 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3284 + " is not current top " + activity);
3285 return null;
3286 }
3287 }
3288 } else {
3289 activity = ActivityRecord.forTokenLocked(activityToken);
3290 if (activity == null) {
3291 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3292 + " couldn't be found");
3293 return null;
3294 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003295 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3297 return null;
3298 }
3299 }
3300
3301 PendingAssistExtras pae;
3302 Bundle extras = new Bundle();
3303 if (args != null) {
3304 extras.putAll(args);
3305 }
3306 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003307 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308
3309 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3310 userHandle);
3311 pae.isHome = activity.isActivityTypeHome();
3312
3313 // Increment the sessionId if necessary
3314 if (newSessionId) {
3315 mViSessionId++;
3316 }
3317 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003318 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3319 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003321 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 } catch (RemoteException e) {
3323 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3324 return null;
3325 }
3326 return pae;
3327 }
3328 }
3329
3330 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3331 if (result != null) {
3332 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3333 }
3334 if (pae.hint != null) {
3335 pae.extras.putBoolean(pae.hint, true);
3336 }
3337 }
3338
3339 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3340 IAssistDataReceiver receiver;
3341 synchronized (mGlobalLock) {
3342 mPendingAssistExtras.remove(pae);
3343 receiver = pae.receiver;
3344 }
3345 if (receiver != null) {
3346 // Caller wants result sent back to them.
3347 Bundle sendBundle = new Bundle();
3348 // At least return the receiver extras
3349 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3350 try {
3351 pae.receiver.onHandleAssistData(sendBundle);
3352 } catch (RemoteException e) {
3353 }
3354 }
3355 }
3356
3357 public class PendingAssistExtras extends Binder implements Runnable {
3358 public final ActivityRecord activity;
3359 public boolean isHome;
3360 public final Bundle extras;
3361 public final Intent intent;
3362 public final String hint;
3363 public final IAssistDataReceiver receiver;
3364 public final int userHandle;
3365 public boolean haveResult = false;
3366 public Bundle result = null;
3367 public AssistStructure structure = null;
3368 public AssistContent content = null;
3369 public Bundle receiverExtras;
3370
3371 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3372 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3373 int _userHandle) {
3374 activity = _activity;
3375 extras = _extras;
3376 intent = _intent;
3377 hint = _hint;
3378 receiver = _receiver;
3379 receiverExtras = _receiverExtras;
3380 userHandle = _userHandle;
3381 }
3382
3383 @Override
3384 public void run() {
3385 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3386 synchronized (this) {
3387 haveResult = true;
3388 notifyAll();
3389 }
3390 pendingAssistExtrasTimedOut(this);
3391 }
3392 }
3393
3394 @Override
3395 public boolean isAssistDataAllowedOnCurrentActivity() {
3396 int userId;
3397 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003398 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3400 return false;
3401 }
3402
3403 final ActivityRecord activity = focusedStack.getTopActivity();
3404 if (activity == null) {
3405 return false;
3406 }
3407 userId = activity.userId;
3408 }
3409 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3410 }
3411
3412 @Override
3413 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3414 long ident = Binder.clearCallingIdentity();
3415 try {
3416 synchronized (mGlobalLock) {
3417 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003418 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419 if (top != caller) {
3420 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3421 + " is not current top " + top);
3422 return false;
3423 }
3424 if (!top.nowVisible) {
3425 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3426 + " is not visible");
3427 return false;
3428 }
3429 }
3430 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3431 token);
3432 } finally {
3433 Binder.restoreCallingIdentity(ident);
3434 }
3435 }
3436
3437 @Override
3438 public boolean isRootVoiceInteraction(IBinder token) {
3439 synchronized (mGlobalLock) {
3440 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3441 if (r == null) {
3442 return false;
3443 }
3444 return r.rootVoiceInteraction;
3445 }
3446 }
3447
Wale Ogunwalef6733932018-06-27 05:14:34 -07003448 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3449 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3450 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3451 if (activityToCallback == null) return;
3452 activityToCallback.setVoiceSessionLocked(voiceSession);
3453
3454 // Inform the activity
3455 try {
3456 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3457 voiceInteractor);
3458 long token = Binder.clearCallingIdentity();
3459 try {
3460 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3461 } finally {
3462 Binder.restoreCallingIdentity(token);
3463 }
3464 // TODO: VI Should we cache the activity so that it's easier to find later
3465 // rather than scan through all the stacks and activities?
3466 } catch (RemoteException re) {
3467 activityToCallback.clearVoiceSessionLocked();
3468 // TODO: VI Should this terminate the voice session?
3469 }
3470 }
3471
3472 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3473 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3474 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3475 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3476 boolean wasRunningVoice = mRunningVoice != null;
3477 mRunningVoice = session;
3478 if (!wasRunningVoice) {
3479 mVoiceWakeLock.acquire();
3480 updateSleepIfNeededLocked();
3481 }
3482 }
3483 }
3484
3485 void finishRunningVoiceLocked() {
3486 if (mRunningVoice != null) {
3487 mRunningVoice = null;
3488 mVoiceWakeLock.release();
3489 updateSleepIfNeededLocked();
3490 }
3491 }
3492
3493 @Override
3494 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3495 synchronized (mGlobalLock) {
3496 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3497 if (keepAwake) {
3498 mVoiceWakeLock.acquire();
3499 } else {
3500 mVoiceWakeLock.release();
3501 }
3502 }
3503 }
3504 }
3505
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003506 @Override
3507 public ComponentName getActivityClassForToken(IBinder token) {
3508 synchronized (mGlobalLock) {
3509 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3510 if (r == null) {
3511 return null;
3512 }
3513 return r.intent.getComponent();
3514 }
3515 }
3516
3517 @Override
3518 public String getPackageForToken(IBinder token) {
3519 synchronized (mGlobalLock) {
3520 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3521 if (r == null) {
3522 return null;
3523 }
3524 return r.packageName;
3525 }
3526 }
3527
3528 @Override
3529 public void showLockTaskEscapeMessage(IBinder token) {
3530 synchronized (mGlobalLock) {
3531 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3532 if (r == null) {
3533 return;
3534 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003535 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003536 }
3537 }
3538
3539 @Override
3540 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003541 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003542 final long token = Binder.clearCallingIdentity();
3543 try {
3544 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003545 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003546 }
3547 } finally {
3548 Binder.restoreCallingIdentity(token);
3549 }
3550 }
3551
3552 /**
3553 * Try to place task to provided position. The final position might be different depending on
3554 * current user and stacks state. The task will be moved to target stack if it's currently in
3555 * different stack.
3556 */
3557 @Override
3558 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003559 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 synchronized (mGlobalLock) {
3561 long ident = Binder.clearCallingIdentity();
3562 try {
3563 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3564 + taskId + " in stackId=" + stackId + " at position=" + position);
3565 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3566 if (task == null) {
3567 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3568 + taskId);
3569 }
3570
3571 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3572
3573 if (stack == null) {
3574 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3575 + stackId);
3576 }
3577 if (!stack.isActivityTypeStandardOrUndefined()) {
3578 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3579 + " the position of task " + taskId + " in/to non-standard stack");
3580 }
3581
3582 // TODO: Have the callers of this API call a separate reparent method if that is
3583 // what they intended to do vs. having this method also do reparenting.
3584 if (task.getStack() == stack) {
3585 // Change position in current stack.
3586 stack.positionChildAt(task, position);
3587 } else {
3588 // Reparent to new stack.
3589 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3590 !DEFER_RESUME, "positionTaskInStack");
3591 }
3592 } finally {
3593 Binder.restoreCallingIdentity(ident);
3594 }
3595 }
3596 }
3597
3598 @Override
3599 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3600 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3601 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3602 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3603 synchronized (mGlobalLock) {
3604 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3605 if (record == null) {
3606 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3607 + "found for: " + token);
3608 }
3609 record.setSizeConfigurations(horizontalSizeConfiguration,
3610 verticalSizeConfigurations, smallestSizeConfigurations);
3611 }
3612 }
3613
3614 /**
3615 * Dismisses split-screen multi-window mode.
3616 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3617 */
3618 @Override
3619 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003620 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003621 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3622 final long ident = Binder.clearCallingIdentity();
3623 try {
3624 synchronized (mGlobalLock) {
3625 final ActivityStack stack =
3626 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3627 if (stack == null) {
3628 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3629 return;
3630 }
3631
3632 if (toTop) {
3633 // Caller wants the current split-screen primary stack to be the top stack after
3634 // it goes fullscreen, so move it to the front.
3635 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003636 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003637 // In this case the current split-screen primary stack shouldn't be the top
3638 // stack after it goes fullscreen, but it current has focus, so we move the
3639 // focus to the top-most split-screen secondary stack next to it.
3640 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3641 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3642 if (otherStack != null) {
3643 otherStack.moveToFront("dismissSplitScreenMode_other");
3644 }
3645 }
3646
Evan Rosky10475742018-09-05 19:02:48 -07003647 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003648 }
3649 } finally {
3650 Binder.restoreCallingIdentity(ident);
3651 }
3652 }
3653
3654 /**
3655 * Dismisses Pip
3656 * @param animate True if the dismissal should be animated.
3657 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3658 * default animation duration should be used.
3659 */
3660 @Override
3661 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003662 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 final long ident = Binder.clearCallingIdentity();
3664 try {
3665 synchronized (mGlobalLock) {
3666 final PinnedActivityStack stack =
3667 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3668 if (stack == null) {
3669 Slog.w(TAG, "dismissPip: pinned stack not found.");
3670 return;
3671 }
3672 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3673 throw new IllegalArgumentException("Stack: " + stack
3674 + " doesn't support animated resize.");
3675 }
3676 if (animate) {
3677 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3678 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3679 } else {
3680 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3681 }
3682 }
3683 } finally {
3684 Binder.restoreCallingIdentity(ident);
3685 }
3686 }
3687
3688 @Override
3689 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003690 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691 synchronized (mGlobalLock) {
3692 mSuppressResizeConfigChanges = suppress;
3693 }
3694 }
3695
3696 /**
3697 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3698 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3699 * activity and clearing the task at the same time.
3700 */
3701 @Override
3702 // TODO: API should just be about changing windowing modes...
3703 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003704 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 "moveTasksToFullscreenStack()");
3706 synchronized (mGlobalLock) {
3707 final long origId = Binder.clearCallingIdentity();
3708 try {
3709 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3710 if (stack != null){
3711 if (!stack.isActivityTypeStandardOrUndefined()) {
3712 throw new IllegalArgumentException(
3713 "You can't move tasks from non-standard stacks.");
3714 }
3715 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3716 }
3717 } finally {
3718 Binder.restoreCallingIdentity(origId);
3719 }
3720 }
3721 }
3722
3723 /**
3724 * Moves the top activity in the input stackId to the pinned stack.
3725 *
3726 * @param stackId Id of stack to move the top activity to pinned stack.
3727 * @param bounds Bounds to use for pinned stack.
3728 *
3729 * @return True if the top activity of the input stack was successfully moved to the pinned
3730 * stack.
3731 */
3732 @Override
3733 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003734 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003735 "moveTopActivityToPinnedStack()");
3736 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003737 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3739 + "Device doesn't support picture-in-picture mode");
3740 }
3741
3742 long ident = Binder.clearCallingIdentity();
3743 try {
3744 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3745 } finally {
3746 Binder.restoreCallingIdentity(ident);
3747 }
3748 }
3749 }
3750
3751 @Override
3752 public boolean isInMultiWindowMode(IBinder token) {
3753 final long origId = Binder.clearCallingIdentity();
3754 try {
3755 synchronized (mGlobalLock) {
3756 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3757 if (r == null) {
3758 return false;
3759 }
3760 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3761 return r.inMultiWindowMode();
3762 }
3763 } finally {
3764 Binder.restoreCallingIdentity(origId);
3765 }
3766 }
3767
3768 @Override
3769 public boolean isInPictureInPictureMode(IBinder token) {
3770 final long origId = Binder.clearCallingIdentity();
3771 try {
3772 synchronized (mGlobalLock) {
3773 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3774 }
3775 } finally {
3776 Binder.restoreCallingIdentity(origId);
3777 }
3778 }
3779
3780 private boolean isInPictureInPictureMode(ActivityRecord r) {
3781 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3782 || r.getStack().isInStackLocked(r) == null) {
3783 return false;
3784 }
3785
3786 // If we are animating to fullscreen then we have already dispatched the PIP mode
3787 // changed, so we should reflect that check here as well.
3788 final PinnedActivityStack stack = r.getStack();
3789 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3790 return !windowController.isAnimatingBoundsToFullscreen();
3791 }
3792
3793 @Override
3794 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3795 final long origId = Binder.clearCallingIdentity();
3796 try {
3797 synchronized (mGlobalLock) {
3798 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3799 "enterPictureInPictureMode", token, params);
3800
3801 // If the activity is already in picture in picture mode, then just return early
3802 if (isInPictureInPictureMode(r)) {
3803 return true;
3804 }
3805
3806 // Activity supports picture-in-picture, now check that we can enter PiP at this
3807 // point, if it is
3808 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3809 false /* beforeStopping */)) {
3810 return false;
3811 }
3812
3813 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003814 synchronized (mGlobalLock) {
3815 // Only update the saved args from the args that are set
3816 r.pictureInPictureArgs.copyOnlySet(params);
3817 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3818 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3819 // Adjust the source bounds by the insets for the transition down
3820 final Rect sourceBounds = new Rect(
3821 r.pictureInPictureArgs.getSourceRectHint());
3822 mStackSupervisor.moveActivityToPinnedStackLocked(
3823 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3824 final PinnedActivityStack stack = r.getStack();
3825 stack.setPictureInPictureAspectRatio(aspectRatio);
3826 stack.setPictureInPictureActions(actions);
3827 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3828 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3829 logPictureInPictureArgs(params);
3830 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 };
3832
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003833 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 // If the keyguard is showing or occluded, then try and dismiss it before
3835 // entering picture-in-picture (this will prompt the user to authenticate if the
3836 // device is currently locked).
3837 dismissKeyguard(token, new KeyguardDismissCallback() {
3838 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003839 public void onDismissSucceeded() {
3840 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 }
3842 }, null /* message */);
3843 } else {
3844 // Enter picture in picture immediately otherwise
3845 enterPipRunnable.run();
3846 }
3847 return true;
3848 }
3849 } finally {
3850 Binder.restoreCallingIdentity(origId);
3851 }
3852 }
3853
3854 @Override
3855 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3856 final long origId = Binder.clearCallingIdentity();
3857 try {
3858 synchronized (mGlobalLock) {
3859 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3860 "setPictureInPictureParams", token, params);
3861
3862 // Only update the saved args from the args that are set
3863 r.pictureInPictureArgs.copyOnlySet(params);
3864 if (r.inPinnedWindowingMode()) {
3865 // If the activity is already in picture-in-picture, update the pinned stack now
3866 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3867 // be used the next time the activity enters PiP
3868 final PinnedActivityStack stack = r.getStack();
3869 if (!stack.isAnimatingBoundsToFullscreen()) {
3870 stack.setPictureInPictureAspectRatio(
3871 r.pictureInPictureArgs.getAspectRatio());
3872 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3873 }
3874 }
3875 logPictureInPictureArgs(params);
3876 }
3877 } finally {
3878 Binder.restoreCallingIdentity(origId);
3879 }
3880 }
3881
3882 @Override
3883 public int getMaxNumPictureInPictureActions(IBinder token) {
3884 // Currently, this is a static constant, but later, we may change this to be dependent on
3885 // the context of the activity
3886 return 3;
3887 }
3888
3889 private void logPictureInPictureArgs(PictureInPictureParams params) {
3890 if (params.hasSetActions()) {
3891 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3892 params.getActions().size());
3893 }
3894 if (params.hasSetAspectRatio()) {
3895 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3896 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3897 MetricsLogger.action(lm);
3898 }
3899 }
3900
3901 /**
3902 * Checks the state of the system and the activity associated with the given {@param token} to
3903 * verify that picture-in-picture is supported for that activity.
3904 *
3905 * @return the activity record for the given {@param token} if all the checks pass.
3906 */
3907 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3908 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003909 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910 throw new IllegalStateException(caller
3911 + ": Device doesn't support picture-in-picture mode.");
3912 }
3913
3914 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3915 if (r == null) {
3916 throw new IllegalStateException(caller
3917 + ": Can't find activity for token=" + token);
3918 }
3919
3920 if (!r.supportsPictureInPicture()) {
3921 throw new IllegalStateException(caller
3922 + ": Current activity does not support picture-in-picture.");
3923 }
3924
3925 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003926 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 params.getAspectRatio())) {
3928 final float minAspectRatio = mContext.getResources().getFloat(
3929 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3930 final float maxAspectRatio = mContext.getResources().getFloat(
3931 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3932 throw new IllegalArgumentException(String.format(caller
3933 + ": Aspect ratio is too extreme (must be between %f and %f).",
3934 minAspectRatio, maxAspectRatio));
3935 }
3936
3937 // Truncate the number of actions if necessary
3938 params.truncateActions(getMaxNumPictureInPictureActions(token));
3939
3940 return r;
3941 }
3942
3943 @Override
3944 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003945 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 synchronized (mGlobalLock) {
3947 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3948 if (r == null) {
3949 throw new IllegalArgumentException("Activity does not exist; token="
3950 + activityToken);
3951 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003952 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 }
3954 }
3955
3956 @Override
3957 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3958 Rect tempDockedTaskInsetBounds,
3959 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003960 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 long ident = Binder.clearCallingIdentity();
3962 try {
3963 synchronized (mGlobalLock) {
3964 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3965 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3966 PRESERVE_WINDOWS);
3967 }
3968 } finally {
3969 Binder.restoreCallingIdentity(ident);
3970 }
3971 }
3972
3973 @Override
3974 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003975 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 final long ident = Binder.clearCallingIdentity();
3977 try {
3978 synchronized (mGlobalLock) {
3979 mStackSupervisor.setSplitScreenResizing(resizing);
3980 }
3981 } finally {
3982 Binder.restoreCallingIdentity(ident);
3983 }
3984 }
3985
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 /**
3987 * Check that we have the features required for VR-related API calls, and throw an exception if
3988 * not.
3989 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003990 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003991 if (!mContext.getPackageManager().hasSystemFeature(
3992 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3993 throw new UnsupportedOperationException("VR mode not supported on this device!");
3994 }
3995 }
3996
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 @Override
3998 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003999 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000
4001 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4002
4003 ActivityRecord r;
4004 synchronized (mGlobalLock) {
4005 r = ActivityRecord.isInStackLocked(token);
4006 }
4007
4008 if (r == null) {
4009 throw new IllegalArgumentException();
4010 }
4011
4012 int err;
4013 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
4014 VrManagerInternal.NO_ERROR) {
4015 return err;
4016 }
4017
4018 // Clear the binder calling uid since this path may call moveToTask().
4019 final long callingId = Binder.clearCallingIdentity();
4020 try {
4021 synchronized (mGlobalLock) {
4022 r.requestedVrComponent = (enabled) ? packageName : null;
4023
4024 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004025 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004026 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 }
4028 return 0;
4029 }
4030 } finally {
4031 Binder.restoreCallingIdentity(callingId);
4032 }
4033 }
4034
4035 @Override
4036 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4037 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4038 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004039 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4041 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4042 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004043 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 || activity.voiceSession != null) {
4045 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4046 return;
4047 }
4048 if (activity.pendingVoiceInteractionStart) {
4049 Slog.w(TAG, "Pending start of voice interaction already.");
4050 return;
4051 }
4052 activity.pendingVoiceInteractionStart = true;
4053 }
4054 LocalServices.getService(VoiceInteractionManagerInternal.class)
4055 .startLocalVoiceInteraction(callingActivity, options);
4056 }
4057
4058 @Override
4059 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4060 LocalServices.getService(VoiceInteractionManagerInternal.class)
4061 .stopLocalVoiceInteraction(callingActivity);
4062 }
4063
4064 @Override
4065 public boolean supportsLocalVoiceInteraction() {
4066 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4067 .supportsLocalVoiceInteraction();
4068 }
4069
4070 /** Notifies all listeners when the pinned stack animation starts. */
4071 @Override
4072 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004073 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 }
4075
4076 /** Notifies all listeners when the pinned stack animation ends. */
4077 @Override
4078 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004079 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 }
4081
4082 @Override
4083 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004084 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 final long ident = Binder.clearCallingIdentity();
4086 try {
4087 synchronized (mGlobalLock) {
4088 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4089 }
4090 } finally {
4091 Binder.restoreCallingIdentity(ident);
4092 }
4093 }
4094
4095 @Override
4096 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004097 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004098
4099 synchronized (mGlobalLock) {
4100 // Check if display is initialized in AM.
4101 if (!mStackSupervisor.isDisplayAdded(displayId)) {
4102 // Call might come when display is not yet added or has already been removed.
4103 if (DEBUG_CONFIGURATION) {
4104 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4105 + displayId);
4106 }
4107 return false;
4108 }
4109
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004110 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004112 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 }
4114
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004115 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004116 final Message msg = PooledLambda.obtainMessage(
4117 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4118 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 }
4120
4121 final long origId = Binder.clearCallingIdentity();
4122 try {
4123 if (values != null) {
4124 Settings.System.clearConfiguration(values);
4125 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004126 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4128 return mTmpUpdateConfigurationResult.changes != 0;
4129 } finally {
4130 Binder.restoreCallingIdentity(origId);
4131 }
4132 }
4133 }
4134
4135 @Override
4136 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004137 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004138
4139 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004140 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004141 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004142 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 }
4144
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004145 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004146 final Message msg = PooledLambda.obtainMessage(
4147 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4148 DEFAULT_DISPLAY);
4149 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004150 }
4151
4152 final long origId = Binder.clearCallingIdentity();
4153 try {
4154 if (values != null) {
4155 Settings.System.clearConfiguration(values);
4156 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004157 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 UserHandle.USER_NULL, false /* deferResume */,
4159 mTmpUpdateConfigurationResult);
4160 return mTmpUpdateConfigurationResult.changes != 0;
4161 } finally {
4162 Binder.restoreCallingIdentity(origId);
4163 }
4164 }
4165 }
4166
4167 @Override
4168 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4169 CharSequence message) {
4170 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004171 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4173 }
4174 final long callingId = Binder.clearCallingIdentity();
4175 try {
4176 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004177 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 }
4179 } finally {
4180 Binder.restoreCallingIdentity(callingId);
4181 }
4182 }
4183
4184 @Override
4185 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004186 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 "cancelTaskWindowTransition()");
4188 final long ident = Binder.clearCallingIdentity();
4189 try {
4190 synchronized (mGlobalLock) {
4191 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4192 MATCH_TASK_IN_STACKS_ONLY);
4193 if (task == null) {
4194 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4195 return;
4196 }
4197 task.cancelWindowTransition();
4198 }
4199 } finally {
4200 Binder.restoreCallingIdentity(ident);
4201 }
4202 }
4203
4204 @Override
4205 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 final long ident = Binder.clearCallingIdentity();
4208 try {
4209 final TaskRecord task;
4210 synchronized (mGlobalLock) {
4211 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4212 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4213 if (task == null) {
4214 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4215 return null;
4216 }
4217 }
4218 // Don't call this while holding the lock as this operation might hit the disk.
4219 return task.getSnapshot(reducedResolution);
4220 } finally {
4221 Binder.restoreCallingIdentity(ident);
4222 }
4223 }
4224
4225 @Override
4226 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4227 synchronized (mGlobalLock) {
4228 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4229 if (r == null) {
4230 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4231 + token);
4232 return;
4233 }
4234 final long origId = Binder.clearCallingIdentity();
4235 try {
4236 r.setDisablePreviewScreenshots(disable);
4237 } finally {
4238 Binder.restoreCallingIdentity(origId);
4239 }
4240 }
4241 }
4242
4243 /** Return the user id of the last resumed activity. */
4244 @Override
4245 public @UserIdInt
4246 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4249 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004250 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004251 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004253 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 }
4255 }
4256
4257 @Override
4258 public void updateLockTaskFeatures(int userId, int flags) {
4259 final int callingUid = Binder.getCallingUid();
4260 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 "updateLockTaskFeatures()");
4263 }
4264 synchronized (mGlobalLock) {
4265 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4266 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004267 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 }
4269 }
4270
4271 @Override
4272 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4273 synchronized (mGlobalLock) {
4274 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4275 if (r == null) {
4276 return;
4277 }
4278 final long origId = Binder.clearCallingIdentity();
4279 try {
4280 r.setShowWhenLocked(showWhenLocked);
4281 } finally {
4282 Binder.restoreCallingIdentity(origId);
4283 }
4284 }
4285 }
4286
4287 @Override
4288 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4289 synchronized (mGlobalLock) {
4290 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4291 if (r == null) {
4292 return;
4293 }
4294 final long origId = Binder.clearCallingIdentity();
4295 try {
4296 r.setTurnScreenOn(turnScreenOn);
4297 } finally {
4298 Binder.restoreCallingIdentity(origId);
4299 }
4300 }
4301 }
4302
4303 @Override
4304 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004305 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004306 "registerRemoteAnimations");
4307 definition.setCallingPid(Binder.getCallingPid());
4308 synchronized (mGlobalLock) {
4309 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4310 if (r == null) {
4311 return;
4312 }
4313 final long origId = Binder.clearCallingIdentity();
4314 try {
4315 r.registerRemoteAnimations(definition);
4316 } finally {
4317 Binder.restoreCallingIdentity(origId);
4318 }
4319 }
4320 }
4321
4322 @Override
4323 public void registerRemoteAnimationForNextActivityStart(String packageName,
4324 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004325 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004326 "registerRemoteAnimationForNextActivityStart");
4327 adapter.setCallingPid(Binder.getCallingPid());
4328 synchronized (mGlobalLock) {
4329 final long origId = Binder.clearCallingIdentity();
4330 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004331 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 packageName, adapter);
4333 } finally {
4334 Binder.restoreCallingIdentity(origId);
4335 }
4336 }
4337 }
4338
4339 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4340 @Override
4341 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4342 synchronized (mGlobalLock) {
4343 final long origId = Binder.clearCallingIdentity();
4344 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004345 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 } finally {
4347 Binder.restoreCallingIdentity(origId);
4348 }
4349 }
4350 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004351
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004352 @Override
4353 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004354 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004355 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004356 final int pid = Binder.getCallingPid();
4357 final WindowProcessController wpc = mPidMap.get(pid);
4358 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004359 }
4360 }
4361
4362 @Override
4363 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004364 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004365 != PERMISSION_GRANTED) {
4366 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4367 + Binder.getCallingPid()
4368 + ", uid=" + Binder.getCallingUid()
4369 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4370 Slog.w(TAG, msg);
4371 throw new SecurityException(msg);
4372 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004373 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004374 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004375 final int pid = Binder.getCallingPid();
4376 final WindowProcessController proc = mPidMap.get(pid);
4377 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004378 }
4379 }
4380
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004381 @Override
4382 public void stopAppSwitches() {
4383 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4384 synchronized (mGlobalLock) {
4385 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4386 mDidAppSwitch = false;
4387 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4388 }
4389 }
4390
4391 @Override
4392 public void resumeAppSwitches() {
4393 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4394 synchronized (mGlobalLock) {
4395 // Note that we don't execute any pending app switches... we will
4396 // let those wait until either the timeout, or the next start
4397 // activity request.
4398 mAppSwitchesAllowedTime = 0;
4399 }
4400 }
4401
4402 void onStartActivitySetDidAppSwitch() {
4403 if (mDidAppSwitch) {
4404 // This is the second allowed switch since we stopped switches, so now just generally
4405 // allow switches. Use case:
4406 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4407 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4408 // anyone to switch again).
4409 mAppSwitchesAllowedTime = 0;
4410 } else {
4411 mDidAppSwitch = true;
4412 }
4413 }
4414
4415 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004416 boolean shouldDisableNonVrUiLocked() {
4417 return mVrController.shouldDisableNonVrUiLocked();
4418 }
4419
Wale Ogunwale53783742018-09-16 10:21:51 -07004420 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 // VR apps are expected to run in a main display. If an app is turning on VR for
4422 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4423 // fullscreen stack before enabling VR Mode.
4424 // TODO: The goal of this code is to keep the VR app on the main display. When the
4425 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4426 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4427 // option would be a better choice here.
4428 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4429 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4430 + " to main stack for VR");
4431 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4432 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4433 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4434 }
4435 mH.post(() -> {
4436 if (!mVrController.onVrModeChanged(r)) {
4437 return;
4438 }
4439 synchronized (mGlobalLock) {
4440 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4441 mWindowManager.disableNonVrUi(disableNonVrUi);
4442 if (disableNonVrUi) {
4443 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4444 // then remove the pinned stack.
4445 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4446 }
4447 }
4448 });
4449 }
4450
Wale Ogunwale53783742018-09-16 10:21:51 -07004451 @Override
4452 public int getPackageScreenCompatMode(String packageName) {
4453 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4454 synchronized (mGlobalLock) {
4455 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4456 }
4457 }
4458
4459 @Override
4460 public void setPackageScreenCompatMode(String packageName, int mode) {
4461 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4462 "setPackageScreenCompatMode");
4463 synchronized (mGlobalLock) {
4464 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4465 }
4466 }
4467
4468 @Override
4469 public boolean getPackageAskScreenCompat(String packageName) {
4470 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4471 synchronized (mGlobalLock) {
4472 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4473 }
4474 }
4475
4476 @Override
4477 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4478 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4479 "setPackageAskScreenCompat");
4480 synchronized (mGlobalLock) {
4481 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4482 }
4483 }
4484
Wale Ogunwale64258362018-10-16 15:13:37 -07004485 public static String relaunchReasonToString(int relaunchReason) {
4486 switch (relaunchReason) {
4487 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4488 return "window_resize";
4489 case RELAUNCH_REASON_FREE_RESIZE:
4490 return "free_resize";
4491 default:
4492 return null;
4493 }
4494 }
4495
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004496 ActivityStack getTopDisplayFocusedStack() {
4497 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004498 }
4499
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004500 /** Pokes the task persister. */
4501 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4502 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4503 }
4504
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004505 boolean isKeyguardLocked() {
4506 return mKeyguardController.isKeyguardLocked();
4507 }
4508
Wale Ogunwale31913b52018-10-13 08:29:31 -07004509 void dumpLastANRLocked(PrintWriter pw) {
4510 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4511 if (mLastANRState == null) {
4512 pw.println(" <no ANR has occurred since boot>");
4513 } else {
4514 pw.println(mLastANRState);
4515 }
4516 }
4517
4518 void dumpLastANRTracesLocked(PrintWriter pw) {
4519 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4520
4521 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4522 if (ArrayUtils.isEmpty(files)) {
4523 pw.println(" <no ANR has occurred since boot>");
4524 return;
4525 }
4526 // Find the latest file.
4527 File latest = null;
4528 for (File f : files) {
4529 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4530 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004531 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004532 }
4533 pw.print("File: ");
4534 pw.print(latest.getName());
4535 pw.println();
4536 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4537 String line;
4538 while ((line = in.readLine()) != null) {
4539 pw.println(line);
4540 }
4541 } catch (IOException e) {
4542 pw.print("Unable to read: ");
4543 pw.print(e);
4544 pw.println();
4545 }
4546 }
4547
4548 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4549 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4550 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4551 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4552 }
4553
4554 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4555 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4556 pw.println(header);
4557
4558 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4559 dumpPackage);
4560 boolean needSep = printedAnything;
4561
4562 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4563 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4564 " ResumedActivity: ");
4565 if (printed) {
4566 printedAnything = true;
4567 needSep = false;
4568 }
4569
4570 if (dumpPackage == null) {
4571 if (needSep) {
4572 pw.println();
4573 }
4574 printedAnything = true;
4575 mStackSupervisor.dump(pw, " ");
4576 }
4577
4578 if (!printedAnything) {
4579 pw.println(" (nothing)");
4580 }
4581 }
4582
4583 void dumpActivityContainersLocked(PrintWriter pw) {
4584 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4585 mStackSupervisor.dumpChildrenNames(pw, " ");
4586 pw.println(" ");
4587 }
4588
4589 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4590 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4591 getActivityStartController().dump(pw, "", dumpPackage);
4592 }
4593
4594 /**
4595 * There are three things that cmd can be:
4596 * - a flattened component name that matches an existing activity
4597 * - the cmd arg isn't the flattened component name of an existing activity:
4598 * dump all activity whose component contains the cmd as a substring
4599 * - A hex number of the ActivityRecord object instance.
4600 *
4601 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4602 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4603 */
4604 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4605 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4606 ArrayList<ActivityRecord> activities;
4607
4608 synchronized (mGlobalLock) {
4609 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4610 dumpFocusedStackOnly);
4611 }
4612
4613 if (activities.size() <= 0) {
4614 return false;
4615 }
4616
4617 String[] newArgs = new String[args.length - opti];
4618 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4619
4620 TaskRecord lastTask = null;
4621 boolean needSep = false;
4622 for (int i = activities.size() - 1; i >= 0; i--) {
4623 ActivityRecord r = activities.get(i);
4624 if (needSep) {
4625 pw.println();
4626 }
4627 needSep = true;
4628 synchronized (mGlobalLock) {
4629 final TaskRecord task = r.getTask();
4630 if (lastTask != task) {
4631 lastTask = task;
4632 pw.print("TASK "); pw.print(lastTask.affinity);
4633 pw.print(" id="); pw.print(lastTask.taskId);
4634 pw.print(" userId="); pw.println(lastTask.userId);
4635 if (dumpAll) {
4636 lastTask.dump(pw, " ");
4637 }
4638 }
4639 }
4640 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4641 }
4642 return true;
4643 }
4644
4645 /**
4646 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4647 * there is a thread associated with the activity.
4648 */
4649 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4650 final ActivityRecord r, String[] args, boolean dumpAll) {
4651 String innerPrefix = prefix + " ";
4652 synchronized (mGlobalLock) {
4653 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4654 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4655 pw.print(" pid=");
4656 if (r.hasProcess()) pw.println(r.app.getPid());
4657 else pw.println("(not running)");
4658 if (dumpAll) {
4659 r.dump(pw, innerPrefix);
4660 }
4661 }
4662 if (r.attachedToProcess()) {
4663 // flush anything that is already in the PrintWriter since the thread is going
4664 // to write to the file descriptor directly
4665 pw.flush();
4666 try {
4667 TransferPipe tp = new TransferPipe();
4668 try {
4669 r.app.getThread().dumpActivity(tp.getWriteFd(),
4670 r.appToken, innerPrefix, args);
4671 tp.go(fd);
4672 } finally {
4673 tp.kill();
4674 }
4675 } catch (IOException e) {
4676 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4677 } catch (RemoteException e) {
4678 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4679 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004680 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004681 }
4682
Wale Ogunwalef6733932018-06-27 05:14:34 -07004683 void writeSleepStateToProto(ProtoOutputStream proto) {
4684 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4685 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4686 st.toString());
4687 }
4688
4689 if (mRunningVoice != null) {
4690 final long vrToken = proto.start(
4691 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4692 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4693 mRunningVoice.toString());
4694 mVoiceWakeLock.writeToProto(
4695 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4696 proto.end(vrToken);
4697 }
4698
4699 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4700 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4701 mShuttingDown);
4702 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004703 }
4704
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004705 int getCurrentUserId() {
4706 return mAmInternal.getCurrentUserId();
4707 }
4708
4709 private void enforceNotIsolatedCaller(String caller) {
4710 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4711 throw new SecurityException("Isolated process not allowed to call " + caller);
4712 }
4713 }
4714
Wale Ogunwalef6733932018-06-27 05:14:34 -07004715 public Configuration getConfiguration() {
4716 Configuration ci;
4717 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004718 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004719 ci.userSetLocale = false;
4720 }
4721 return ci;
4722 }
4723
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 /**
4725 * Current global configuration information. Contains general settings for the entire system,
4726 * also corresponds to the merged configuration of the default display.
4727 */
4728 Configuration getGlobalConfiguration() {
4729 return mStackSupervisor.getConfiguration();
4730 }
4731
4732 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4733 boolean initLocale) {
4734 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4735 }
4736
4737 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4738 boolean initLocale, boolean deferResume) {
4739 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4740 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4741 UserHandle.USER_NULL, deferResume);
4742 }
4743
Wale Ogunwale59507092018-10-29 09:00:30 -07004744 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004745 final long origId = Binder.clearCallingIdentity();
4746 try {
4747 synchronized (mGlobalLock) {
4748 updateConfigurationLocked(values, null, false, true, userId,
4749 false /* deferResume */);
4750 }
4751 } finally {
4752 Binder.restoreCallingIdentity(origId);
4753 }
4754 }
4755
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004756 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4757 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4758 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4759 deferResume, null /* result */);
4760 }
4761
4762 /**
4763 * Do either or both things: (1) change the current configuration, and (2)
4764 * make sure the given activity is running with the (now) current
4765 * configuration. Returns true if the activity has been left running, or
4766 * false if <var>starting</var> is being destroyed to match the new
4767 * configuration.
4768 *
4769 * @param userId is only used when persistent parameter is set to true to persist configuration
4770 * for that particular user
4771 */
4772 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4773 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4774 ActivityTaskManagerService.UpdateConfigurationResult result) {
4775 int changes = 0;
4776 boolean kept = true;
4777
4778 if (mWindowManager != null) {
4779 mWindowManager.deferSurfaceLayout();
4780 }
4781 try {
4782 if (values != null) {
4783 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4784 deferResume);
4785 }
4786
4787 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4788 } finally {
4789 if (mWindowManager != null) {
4790 mWindowManager.continueSurfaceLayout();
4791 }
4792 }
4793
4794 if (result != null) {
4795 result.changes = changes;
4796 result.activityRelaunched = !kept;
4797 }
4798 return kept;
4799 }
4800
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004801 /** Update default (global) configuration and notify listeners about changes. */
4802 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4803 boolean persistent, int userId, boolean deferResume) {
4804 mTempConfig.setTo(getGlobalConfiguration());
4805 final int changes = mTempConfig.updateFrom(values);
4806 if (changes == 0) {
4807 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4808 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4809 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4810 // (even if there are no actual changes) to unfreeze the window.
4811 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4812 return 0;
4813 }
4814
4815 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4816 "Updating global configuration to: " + values);
4817
4818 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4819 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4820 values.colorMode,
4821 values.densityDpi,
4822 values.fontScale,
4823 values.hardKeyboardHidden,
4824 values.keyboard,
4825 values.keyboardHidden,
4826 values.mcc,
4827 values.mnc,
4828 values.navigation,
4829 values.navigationHidden,
4830 values.orientation,
4831 values.screenHeightDp,
4832 values.screenLayout,
4833 values.screenWidthDp,
4834 values.smallestScreenWidthDp,
4835 values.touchscreen,
4836 values.uiMode);
4837
4838
4839 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4840 final LocaleList locales = values.getLocales();
4841 int bestLocaleIndex = 0;
4842 if (locales.size() > 1) {
4843 if (mSupportedSystemLocales == null) {
4844 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4845 }
4846 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4847 }
4848 SystemProperties.set("persist.sys.locale",
4849 locales.get(bestLocaleIndex).toLanguageTag());
4850 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004851
4852 final Message m = PooledLambda.obtainMessage(
4853 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4854 locales.get(bestLocaleIndex));
4855 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004856 }
4857
Yunfan Chen75157d72018-07-27 14:47:21 +09004858 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004859
4860 // Update stored global config and notify everyone about the change.
4861 mStackSupervisor.onConfigurationChanged(mTempConfig);
4862
4863 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4864 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004865 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004866
4867 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004868 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004869
4870 AttributeCache ac = AttributeCache.instance();
4871 if (ac != null) {
4872 ac.updateConfiguration(mTempConfig);
4873 }
4874
4875 // Make sure all resources in our process are updated right now, so that anyone who is going
4876 // to retrieve resource values after we return will be sure to get the new ones. This is
4877 // especially important during boot, where the first config change needs to guarantee all
4878 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004879 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004880
4881 // We need another copy of global config because we're scheduling some calls instead of
4882 // running them in place. We need to be sure that object we send will be handled unchanged.
4883 final Configuration configCopy = new Configuration(mTempConfig);
4884 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004885 final Message msg = PooledLambda.obtainMessage(
4886 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4887 this, userId, configCopy);
4888 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004889 }
4890
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004891 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004892 final int pid = mPidMap.keyAt(i);
4893 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004894 if (DEBUG_CONFIGURATION) {
4895 Slog.v(TAG_CONFIGURATION, "Update process config of "
4896 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004898 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004899 }
4900
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004901 final Message msg = PooledLambda.obtainMessage(
4902 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4903 mAmInternal, changes, initLocale);
4904 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004905
4906 // Override configuration of the default display duplicates global config, so we need to
4907 // update it also. This will also notify WindowManager about changes.
4908 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4909 DEFAULT_DISPLAY);
4910
4911 return changes;
4912 }
4913
4914 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4915 boolean deferResume, int displayId) {
4916 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4917 displayId, null /* result */);
4918 }
4919
4920 /**
4921 * Updates override configuration specific for the selected display. If no config is provided,
4922 * new one will be computed in WM based on current display info.
4923 */
4924 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4925 ActivityRecord starting, boolean deferResume, int displayId,
4926 ActivityTaskManagerService.UpdateConfigurationResult result) {
4927 int changes = 0;
4928 boolean kept = true;
4929
4930 if (mWindowManager != null) {
4931 mWindowManager.deferSurfaceLayout();
4932 }
4933 try {
4934 if (values != null) {
4935 if (displayId == DEFAULT_DISPLAY) {
4936 // Override configuration of the default display duplicates global config, so
4937 // we're calling global config update instead for default display. It will also
4938 // apply the correct override config.
4939 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4940 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4941 } else {
4942 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4943 }
4944 }
4945
4946 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4947 } finally {
4948 if (mWindowManager != null) {
4949 mWindowManager.continueSurfaceLayout();
4950 }
4951 }
4952
4953 if (result != null) {
4954 result.changes = changes;
4955 result.activityRelaunched = !kept;
4956 }
4957 return kept;
4958 }
4959
4960 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4961 int displayId) {
4962 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4963 final int changes = mTempConfig.updateFrom(values);
4964 if (changes != 0) {
4965 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4966 + mTempConfig + " for displayId=" + displayId);
4967 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4968
4969 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4970 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004971 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004972
Wale Ogunwale5c918702018-10-18 11:06:33 -07004973 // Post message to start process to avoid possible deadlock of calling into AMS with
4974 // the ATMS lock held.
4975 final Message msg = PooledLambda.obtainMessage(
4976 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4977 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4978 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004979 }
4980 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004981 return changes;
4982 }
4983
Wale Ogunwalef6733932018-06-27 05:14:34 -07004984 private void updateEventDispatchingLocked(boolean booted) {
4985 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4986 }
4987
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004988 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4989 final ContentResolver resolver = mContext.getContentResolver();
4990 Settings.System.putConfigurationForUser(resolver, config, userId);
4991 }
4992
4993 private void sendLocaleToMountDaemonMsg(Locale l) {
4994 try {
4995 IBinder service = ServiceManager.getService("mount");
4996 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
4997 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
4998 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
4999 } catch (RemoteException e) {
5000 Log.e(TAG, "Error storing locale for decryption UI", e);
5001 }
5002 }
5003
Alison Cichowlas3e340502018-08-07 17:15:01 -04005004 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5005 mStartActivitySources.remove(permissionToken);
5006 mExpiredStartAsCallerTokens.add(permissionToken);
5007 }
5008
5009 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5010 mExpiredStartAsCallerTokens.remove(permissionToken);
5011 }
5012
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005013 boolean isActivityStartsLoggingEnabled() {
5014 return mAmInternal.isActivityStartsLoggingEnabled();
5015 }
5016
Wale Ogunwalef6733932018-06-27 05:14:34 -07005017 void enableScreenAfterBoot(boolean booted) {
5018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5019 SystemClock.uptimeMillis());
5020 mWindowManager.enableScreenAfterBoot();
5021
5022 synchronized (mGlobalLock) {
5023 updateEventDispatchingLocked(booted);
5024 }
5025 }
5026
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005027 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5028 if (r == null || !r.hasProcess()) {
5029 return KEY_DISPATCHING_TIMEOUT_MS;
5030 }
5031 return getInputDispatchingTimeoutLocked(r.app);
5032 }
5033
5034 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005035 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005036 }
5037
Wale Ogunwalef6733932018-06-27 05:14:34 -07005038 /**
5039 * Decide based on the configuration whether we should show the ANR,
5040 * crash, etc dialogs. The idea is that if there is no affordance to
5041 * press the on-screen buttons, or the user experience would be more
5042 * greatly impacted than the crash itself, we shouldn't show the dialog.
5043 *
5044 * A thought: SystemUI might also want to get told about this, the Power
5045 * dialog / global actions also might want different behaviors.
5046 */
5047 private void updateShouldShowDialogsLocked(Configuration config) {
5048 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5049 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5050 && config.navigation == Configuration.NAVIGATION_NONAV);
5051 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5052 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5053 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5054 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5055 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5056 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5057 HIDE_ERROR_DIALOGS, 0) != 0;
5058 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5059 }
5060
5061 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5062 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5063 FONT_SCALE, 1.0f, userId);
5064
5065 synchronized (this) {
5066 if (getGlobalConfiguration().fontScale == scaleFactor) {
5067 return;
5068 }
5069
5070 final Configuration configuration
5071 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5072 configuration.fontScale = scaleFactor;
5073 updatePersistentConfiguration(configuration, userId);
5074 }
5075 }
5076
5077 // Actually is sleeping or shutting down or whatever else in the future
5078 // is an inactive state.
5079 boolean isSleepingOrShuttingDownLocked() {
5080 return isSleepingLocked() || mShuttingDown;
5081 }
5082
5083 boolean isSleepingLocked() {
5084 return mSleeping;
5085 }
5086
Riddle Hsu16567132018-08-16 21:37:47 +08005087 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005088 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
5089 final TaskRecord task = r.getTask();
5090 if (task.isActivityTypeStandard()) {
5091 if (mCurAppTimeTracker != r.appTimeTracker) {
5092 // We are switching app tracking. Complete the current one.
5093 if (mCurAppTimeTracker != null) {
5094 mCurAppTimeTracker.stop();
5095 mH.obtainMessage(
5096 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
5097 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
5098 mCurAppTimeTracker = null;
5099 }
5100 if (r.appTimeTracker != null) {
5101 mCurAppTimeTracker = r.appTimeTracker;
5102 startTimeTrackingFocusedActivityLocked();
5103 }
5104 } else {
5105 startTimeTrackingFocusedActivityLocked();
5106 }
5107 } else {
5108 r.appTimeTracker = null;
5109 }
5110 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5111 // TODO: Probably not, because we don't want to resume voice on switching
5112 // back to this activity
5113 if (task.voiceInteractor != null) {
5114 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5115 } else {
5116 finishRunningVoiceLocked();
5117
5118 if (mLastResumedActivity != null) {
5119 final IVoiceInteractionSession session;
5120
5121 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5122 if (lastResumedActivityTask != null
5123 && lastResumedActivityTask.voiceSession != null) {
5124 session = lastResumedActivityTask.voiceSession;
5125 } else {
5126 session = mLastResumedActivity.voiceSession;
5127 }
5128
5129 if (session != null) {
5130 // We had been in a voice interaction session, but now focused has
5131 // move to something different. Just finish the session, we can't
5132 // return to it and retain the proper state and synchronization with
5133 // the voice interaction service.
5134 finishVoiceTask(session);
5135 }
5136 }
5137 }
5138
5139 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5140 mAmInternal.sendForegroundProfileChanged(r.userId);
5141 }
5142 updateResumedAppTrace(r);
5143 mLastResumedActivity = r;
5144
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005145 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005146
5147 applyUpdateLockStateLocked(r);
5148 applyUpdateVrModeLocked(r);
5149
5150 EventLogTags.writeAmSetResumedActivity(
5151 r == null ? -1 : r.userId,
5152 r == null ? "NULL" : r.shortComponentName,
5153 reason);
5154 }
5155
5156 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5157 synchronized (mGlobalLock) {
5158 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5159 updateSleepIfNeededLocked();
5160 return token;
5161 }
5162 }
5163
5164 void updateSleepIfNeededLocked() {
5165 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5166 final boolean wasSleeping = mSleeping;
5167 boolean updateOomAdj = false;
5168
5169 if (!shouldSleep) {
5170 // If wasSleeping is true, we need to wake up activity manager state from when
5171 // we started sleeping. In either case, we need to apply the sleep tokens, which
5172 // will wake up stacks or put them to sleep as appropriate.
5173 if (wasSleeping) {
5174 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005175 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5176 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005177 startTimeTrackingFocusedActivityLocked();
5178 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5179 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5180 }
5181 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5182 if (wasSleeping) {
5183 updateOomAdj = true;
5184 }
5185 } else if (!mSleeping && shouldSleep) {
5186 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005187 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5188 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005189 if (mCurAppTimeTracker != null) {
5190 mCurAppTimeTracker.stop();
5191 }
5192 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5193 mStackSupervisor.goingToSleepLocked();
5194 updateResumedAppTrace(null /* resumed */);
5195 updateOomAdj = true;
5196 }
5197 if (updateOomAdj) {
5198 mH.post(mAmInternal::updateOomAdj);
5199 }
5200 }
5201
5202 void updateOomAdj() {
5203 mH.post(mAmInternal::updateOomAdj);
5204 }
5205
Wale Ogunwale53783742018-09-16 10:21:51 -07005206 void updateCpuStats() {
5207 mH.post(mAmInternal::updateCpuStats);
5208 }
5209
5210 void updateUsageStats(ActivityRecord component, boolean resumed) {
5211 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5212 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5213 mH.sendMessage(m);
5214 }
5215
5216 void setBooting(boolean booting) {
5217 mAmInternal.setBooting(booting);
5218 }
5219
5220 boolean isBooting() {
5221 return mAmInternal.isBooting();
5222 }
5223
5224 void setBooted(boolean booted) {
5225 mAmInternal.setBooted(booted);
5226 }
5227
5228 boolean isBooted() {
5229 return mAmInternal.isBooted();
5230 }
5231
5232 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5233 mH.post(() -> {
5234 if (finishBooting) {
5235 mAmInternal.finishBooting();
5236 }
5237 if (enableScreen) {
5238 mInternal.enableScreenAfterBoot(isBooted());
5239 }
5240 });
5241 }
5242
5243 void setHeavyWeightProcess(ActivityRecord root) {
5244 mHeavyWeightProcess = root.app;
5245 final Message m = PooledLambda.obtainMessage(
5246 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5247 root.app, root.intent, root.userId);
5248 mH.sendMessage(m);
5249 }
5250
5251 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5252 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5253 return;
5254 }
5255
5256 mHeavyWeightProcess = null;
5257 final Message m = PooledLambda.obtainMessage(
5258 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5259 proc.mUserId);
5260 mH.sendMessage(m);
5261 }
5262
5263 private void cancelHeavyWeightProcessNotification(int userId) {
5264 final INotificationManager inm = NotificationManager.getService();
5265 if (inm == null) {
5266 return;
5267 }
5268 try {
5269 inm.cancelNotificationWithTag("android", null,
5270 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5271 } catch (RuntimeException e) {
5272 Slog.w(TAG, "Error canceling notification for service", e);
5273 } catch (RemoteException e) {
5274 }
5275
5276 }
5277
5278 private void postHeavyWeightProcessNotification(
5279 WindowProcessController proc, Intent intent, int userId) {
5280 if (proc == null) {
5281 return;
5282 }
5283
5284 final INotificationManager inm = NotificationManager.getService();
5285 if (inm == null) {
5286 return;
5287 }
5288
5289 try {
5290 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5291 String text = mContext.getString(R.string.heavy_weight_notification,
5292 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5293 Notification notification =
5294 new Notification.Builder(context,
5295 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5296 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5297 .setWhen(0)
5298 .setOngoing(true)
5299 .setTicker(text)
5300 .setColor(mContext.getColor(
5301 com.android.internal.R.color.system_notification_accent_color))
5302 .setContentTitle(text)
5303 .setContentText(
5304 mContext.getText(R.string.heavy_weight_notification_detail))
5305 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5306 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5307 new UserHandle(userId)))
5308 .build();
5309 try {
5310 inm.enqueueNotificationWithTag("android", "android", null,
5311 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5312 } catch (RuntimeException e) {
5313 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5314 } catch (RemoteException e) {
5315 }
5316 } catch (PackageManager.NameNotFoundException e) {
5317 Slog.w(TAG, "Unable to create context for heavy notification", e);
5318 }
5319
5320 }
5321
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005322 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5323 IBinder token, String resultWho, int requestCode, Intent[] intents,
5324 String[] resolvedTypes, int flags, Bundle bOptions) {
5325
5326 ActivityRecord activity = null;
5327 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5328 activity = ActivityRecord.isInStackLocked(token);
5329 if (activity == null) {
5330 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5331 return null;
5332 }
5333 if (activity.finishing) {
5334 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5335 return null;
5336 }
5337 }
5338
5339 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5340 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5341 bOptions);
5342 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5343 if (noCreate) {
5344 return rec;
5345 }
5346 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5347 if (activity.pendingResults == null) {
5348 activity.pendingResults = new HashSet<>();
5349 }
5350 activity.pendingResults.add(rec.ref);
5351 }
5352 return rec;
5353 }
5354
Andrii Kulian52d255c2018-07-13 11:32:19 -07005355 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005356 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005357 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5359 mCurAppTimeTracker.start(resumedActivity.packageName);
5360 }
5361 }
5362
5363 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5364 if (mTracedResumedActivity != null) {
5365 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5366 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5367 }
5368 if (resumed != null) {
5369 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5370 constructResumedTraceName(resumed.packageName), 0);
5371 }
5372 mTracedResumedActivity = resumed;
5373 }
5374
5375 private String constructResumedTraceName(String packageName) {
5376 return "focused app: " + packageName;
5377 }
5378
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005379 /** Applies latest configuration and/or visibility updates if needed. */
5380 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5381 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005382 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005383 // mainStack is null during startup.
5384 if (mainStack != null) {
5385 if (changes != 0 && starting == null) {
5386 // If the configuration changed, and the caller is not already
5387 // in the process of starting an activity, then find the top
5388 // activity to check if its configuration needs to change.
5389 starting = mainStack.topRunningActivityLocked();
5390 }
5391
5392 if (starting != null) {
5393 kept = starting.ensureActivityConfiguration(changes,
5394 false /* preserveWindow */);
5395 // And we need to make sure at this point that all other activities
5396 // are made visible with the correct configuration.
5397 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5398 !PRESERVE_WINDOWS);
5399 }
5400 }
5401
5402 return kept;
5403 }
5404
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005405 void scheduleAppGcsLocked() {
5406 mH.post(() -> mAmInternal.scheduleAppGcs());
5407 }
5408
Wale Ogunwale53783742018-09-16 10:21:51 -07005409 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5410 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5411 }
5412
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005413 /**
5414 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5415 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5416 * on demand.
5417 */
5418 IPackageManager getPackageManager() {
5419 return AppGlobals.getPackageManager();
5420 }
5421
5422 PackageManagerInternal getPackageManagerInternalLocked() {
5423 if (mPmInternal == null) {
5424 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5425 }
5426 return mPmInternal;
5427 }
5428
Wale Ogunwale008163e2018-07-23 23:11:08 -07005429 AppWarnings getAppWarningsLocked() {
5430 return mAppWarnings;
5431 }
5432
Wale Ogunwale214f3482018-10-04 11:00:47 -07005433 Intent getHomeIntent() {
5434 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5435 intent.setComponent(mTopComponent);
5436 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5437 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5438 intent.addCategory(Intent.CATEGORY_HOME);
5439 }
5440 return intent;
5441 }
5442
Wale Ogunwale214f3482018-10-04 11:00:47 -07005443 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5444 if (info == null) return null;
5445 ApplicationInfo newInfo = new ApplicationInfo(info);
5446 newInfo.initForUser(userId);
5447 return newInfo;
5448 }
5449
Wale Ogunwale9c103022018-10-18 07:44:54 -07005450 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005451 if (uid == SYSTEM_UID) {
5452 // The system gets to run in any process. If there are multiple processes with the same
5453 // uid, just pick the first (this should never happen).
5454 final SparseArray<WindowProcessController> procs =
5455 mProcessNames.getMap().get(processName);
5456 if (procs == null) return null;
5457 final int procCount = procs.size();
5458 for (int i = 0; i < procCount; i++) {
5459 final int procUid = procs.keyAt(i);
5460 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5461 // Don't use an app process or different user process for system component.
5462 continue;
5463 }
5464 return procs.valueAt(i);
5465 }
5466 }
5467
5468 return mProcessNames.get(processName, uid);
5469 }
5470
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005471 WindowProcessController getProcessController(IApplicationThread thread) {
5472 if (thread == null) {
5473 return null;
5474 }
5475
5476 final IBinder threadBinder = thread.asBinder();
5477 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5478 for (int i = pmap.size()-1; i >= 0; i--) {
5479 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5480 for (int j = procs.size() - 1; j >= 0; j--) {
5481 final WindowProcessController proc = procs.valueAt(j);
5482 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5483 return proc;
5484 }
5485 }
5486 }
5487
5488 return null;
5489 }
5490
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005491 int getUidStateLocked(int uid) {
5492 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5493 }
5494
Wale Ogunwale9de19442018-10-18 19:05:03 -07005495 /**
5496 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5497 * the whitelist
5498 */
5499 String getPendingTempWhitelistTagForUidLocked(int uid) {
5500 return mPendingTempWhitelist.get(uid);
5501 }
5502
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005503 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5504 if (true || Build.IS_USER) {
5505 return;
5506 }
5507
5508 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5509 StrictMode.allowThreadDiskWrites();
5510 try {
5511 File tracesDir = new File("/data/anr");
5512 File tracesFile = null;
5513 try {
5514 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5515
5516 StringBuilder sb = new StringBuilder();
5517 Time tobj = new Time();
5518 tobj.set(System.currentTimeMillis());
5519 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5520 sb.append(": ");
5521 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5522 sb.append(" since ");
5523 sb.append(msg);
5524 FileOutputStream fos = new FileOutputStream(tracesFile);
5525 fos.write(sb.toString().getBytes());
5526 if (app == null) {
5527 fos.write("\n*** No application process!".getBytes());
5528 }
5529 fos.close();
5530 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5531 } catch (IOException e) {
5532 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5533 return;
5534 }
5535
5536 if (app != null && app.getPid() > 0) {
5537 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5538 firstPids.add(app.getPid());
5539 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5540 }
5541
5542 File lastTracesFile = null;
5543 File curTracesFile = null;
5544 for (int i=9; i>=0; i--) {
5545 String name = String.format(Locale.US, "slow%02d.txt", i);
5546 curTracesFile = new File(tracesDir, name);
5547 if (curTracesFile.exists()) {
5548 if (lastTracesFile != null) {
5549 curTracesFile.renameTo(lastTracesFile);
5550 } else {
5551 curTracesFile.delete();
5552 }
5553 }
5554 lastTracesFile = curTracesFile;
5555 }
5556 tracesFile.renameTo(curTracesFile);
5557 } finally {
5558 StrictMode.setThreadPolicy(oldPolicy);
5559 }
5560 }
5561
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005562 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005564
5565
Wale Ogunwale98875612018-10-12 07:53:02 -07005566 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5567 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005569 public H() {
5570 super(DisplayThread.get().getLooper());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005571 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572
5573 @Override
5574 public void handleMessage(Message msg) {
5575 switch (msg.what) {
5576 case REPORT_TIME_TRACKER_MSG: {
5577 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5578 tracker.deliverResult(mContext);
5579 } break;
5580 }
5581 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005582 }
5583
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005584 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005586
5587 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005588 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005589 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005590
5591 @Override
5592 public void handleMessage(Message msg) {
5593 switch (msg.what) {
5594 case DISMISS_DIALOG_UI_MSG: {
5595 final Dialog d = (Dialog) msg.obj;
5596 d.dismiss();
5597 break;
5598 }
5599 }
5600 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005601 }
5602
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005603 final class LocalService extends ActivityTaskManagerInternal {
5604 @Override
5605 public SleepToken acquireSleepToken(String tag, int displayId) {
5606 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005607 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005608 }
5609
5610 @Override
5611 public ComponentName getHomeActivityForUser(int userId) {
5612 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005613 ActivityRecord homeActivity =
5614 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005615 return homeActivity == null ? null : homeActivity.realActivity;
5616 }
5617 }
5618
5619 @Override
5620 public void onLocalVoiceInteractionStarted(IBinder activity,
5621 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5622 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005623 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005624 }
5625 }
5626
5627 @Override
5628 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5629 synchronized (mGlobalLock) {
5630 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5631 reasons, timestamp);
5632 }
5633 }
5634
5635 @Override
5636 public void notifyAppTransitionFinished() {
5637 synchronized (mGlobalLock) {
5638 mStackSupervisor.notifyAppTransitionDone();
5639 }
5640 }
5641
5642 @Override
5643 public void notifyAppTransitionCancelled() {
5644 synchronized (mGlobalLock) {
5645 mStackSupervisor.notifyAppTransitionDone();
5646 }
5647 }
5648
5649 @Override
5650 public List<IBinder> getTopVisibleActivities() {
5651 synchronized (mGlobalLock) {
5652 return mStackSupervisor.getTopVisibleActivities();
5653 }
5654 }
5655
5656 @Override
5657 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5658 synchronized (mGlobalLock) {
5659 mStackSupervisor.setDockedStackMinimized(minimized);
5660 }
5661 }
5662
5663 @Override
5664 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5665 Bundle bOptions) {
5666 Preconditions.checkNotNull(intents, "intents");
5667 final String[] resolvedTypes = new String[intents.length];
5668
5669 // UID of the package on user userId.
5670 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5671 // packageUid may not be initialized.
5672 int packageUid = 0;
5673 final long ident = Binder.clearCallingIdentity();
5674
5675 try {
5676 for (int i = 0; i < intents.length; i++) {
5677 resolvedTypes[i] =
5678 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5679 }
5680
5681 packageUid = AppGlobals.getPackageManager().getPackageUid(
5682 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5683 } catch (RemoteException e) {
5684 // Shouldn't happen.
5685 } finally {
5686 Binder.restoreCallingIdentity(ident);
5687 }
5688
5689 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005690 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005691 packageUid, packageName,
5692 intents, resolvedTypes, null /* resultTo */,
5693 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005694 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005695 }
5696 }
5697
5698 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005699 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5700 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5701 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5702 synchronized (mGlobalLock) {
5703 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5704 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5705 originatingPendingIntent);
5706 }
5707 }
5708
5709 @Override
5710 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5711 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5712 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5713 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5714 PendingIntentRecord originatingPendingIntent) {
5715 synchronized (mGlobalLock) {
5716 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5717 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5718 requestCode, startFlags, options, userId, inTask, reason,
5719 validateIncomingUser, originatingPendingIntent);
5720 }
5721 }
5722
5723 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005724 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5725 Intent intent, Bundle options, int userId) {
5726 return ActivityTaskManagerService.this.startActivityAsUser(
5727 caller, callerPacakge, intent,
5728 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5729 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5730 false /*validateIncomingUser*/);
5731 }
5732
5733 @Override
lumark588a3e82018-07-20 18:53:54 +08005734 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005735 synchronized (mGlobalLock) {
5736
5737 // We might change the visibilities here, so prepare an empty app transition which
5738 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005739 final ActivityDisplay activityDisplay =
5740 mStackSupervisor.getActivityDisplay(displayId);
5741 if (activityDisplay == null) {
5742 return;
5743 }
5744 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005745 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005746 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005747 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005748 }
5749 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5750
5751 // If there was a transition set already we don't want to interfere with it as we
5752 // might be starting it too early.
5753 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005754 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005755 }
5756 }
5757 if (callback != null) {
5758 callback.run();
5759 }
5760 }
5761
5762 @Override
5763 public void notifyKeyguardTrustedChanged() {
5764 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005765 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005766 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5767 }
5768 }
5769 }
5770
5771 /**
5772 * Called after virtual display Id is updated by
5773 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5774 * {@param vrVr2dDisplayId}.
5775 */
5776 @Override
5777 public void setVr2dDisplayId(int vr2dDisplayId) {
5778 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5779 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005780 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005781 }
5782 }
5783
5784 @Override
5785 public void setFocusedActivity(IBinder token) {
5786 synchronized (mGlobalLock) {
5787 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5788 if (r == null) {
5789 throw new IllegalArgumentException(
5790 "setFocusedActivity: No activity record matching token=" + token);
5791 }
Louis Chang19443452018-10-09 12:10:21 +08005792 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005793 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005794 }
5795 }
5796 }
5797
5798 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005799 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005800 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005801 }
5802
5803 @Override
5804 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005805 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005806 }
5807
5808 @Override
5809 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005810 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005811 }
5812
5813 @Override
5814 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5815 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5816 }
5817
5818 @Override
5819 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005820 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005821 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005822
5823 @Override
5824 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5825 synchronized (mGlobalLock) {
5826 mActiveVoiceInteractionServiceComponent = component;
5827 }
5828 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005829
5830 @Override
5831 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5832 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5833 return;
5834 }
5835 synchronized (mGlobalLock) {
5836 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5837 if (types == null) {
5838 if (uid < 0) {
5839 return;
5840 }
5841 types = new ArrayMap<>();
5842 mAllowAppSwitchUids.put(userId, types);
5843 }
5844 if (uid < 0) {
5845 types.remove(type);
5846 } else {
5847 types.put(type, uid);
5848 }
5849 }
5850 }
5851
5852 @Override
5853 public void onUserStopped(int userId) {
5854 synchronized (mGlobalLock) {
5855 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5856 mAllowAppSwitchUids.remove(userId);
5857 }
5858 }
5859
5860 @Override
5861 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5862 synchronized (mGlobalLock) {
5863 return ActivityTaskManagerService.this.isGetTasksAllowed(
5864 caller, callingPid, callingUid);
5865 }
5866 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005867
5868 @Override
5869 public void onProcessAdded(WindowProcessController proc) {
5870 synchronized (mGlobalLock) {
5871 mProcessNames.put(proc.mName, proc.mUid, proc);
5872 }
5873 }
5874
5875 @Override
5876 public void onProcessRemoved(String name, int uid) {
5877 synchronized (mGlobalLock) {
5878 mProcessNames.remove(name, uid);
5879 }
5880 }
5881
5882 @Override
5883 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5884 synchronized (mGlobalLock) {
5885 if (proc == mHomeProcess) {
5886 mHomeProcess = null;
5887 }
5888 if (proc == mPreviousProcess) {
5889 mPreviousProcess = null;
5890 }
5891 }
5892 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005893
5894 @Override
5895 public int getTopProcessState() {
5896 synchronized (mGlobalLock) {
5897 return mTopProcessState;
5898 }
5899 }
5900
5901 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005902 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5903 synchronized (mGlobalLock) {
5904 return proc == mHeavyWeightProcess;
5905 }
5906 }
5907
5908 @Override
5909 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5910 synchronized (mGlobalLock) {
5911 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5912 }
5913 }
5914
5915 @Override
5916 public void finishHeavyWeightApp() {
5917 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005918 if (mHeavyWeightProcess != null) {
5919 mHeavyWeightProcess.finishActivities();
5920 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005921 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5922 mHeavyWeightProcess);
5923 }
5924 }
5925
5926 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005927 public boolean isSleeping() {
5928 synchronized (mGlobalLock) {
5929 return isSleepingLocked();
5930 }
5931 }
5932
5933 @Override
5934 public boolean isShuttingDown() {
5935 synchronized (mGlobalLock) {
5936 return mShuttingDown;
5937 }
5938 }
5939
5940 @Override
5941 public boolean shuttingDown(boolean booted, int timeout) {
5942 synchronized (mGlobalLock) {
5943 mShuttingDown = true;
5944 mStackSupervisor.prepareForShutdownLocked();
5945 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005946 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005947 return mStackSupervisor.shutdownLocked(timeout);
5948 }
5949 }
5950
5951 @Override
5952 public void enableScreenAfterBoot(boolean booted) {
5953 synchronized (mGlobalLock) {
5954 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5955 SystemClock.uptimeMillis());
5956 mWindowManager.enableScreenAfterBoot();
5957 updateEventDispatchingLocked(booted);
5958 }
5959 }
5960
5961 @Override
5962 public boolean showStrictModeViolationDialog() {
5963 synchronized (mGlobalLock) {
5964 return mShowDialogs && !mSleeping && !mShuttingDown;
5965 }
5966 }
5967
5968 @Override
5969 public void showSystemReadyErrorDialogsIfNeeded() {
5970 synchronized (mGlobalLock) {
5971 try {
5972 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5973 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5974 + " data partition or your device will be unstable.");
5975 mUiHandler.post(() -> {
5976 if (mShowDialogs) {
5977 AlertDialog d = new BaseErrorDialog(mUiContext);
5978 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5979 d.setCancelable(false);
5980 d.setTitle(mUiContext.getText(R.string.android_system_label));
5981 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5982 d.setButton(DialogInterface.BUTTON_POSITIVE,
5983 mUiContext.getText(R.string.ok),
5984 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5985 d.show();
5986 }
5987 });
5988 }
5989 } catch (RemoteException e) {
5990 }
5991
5992 if (!Build.isBuildConsistent()) {
5993 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5994 mUiHandler.post(() -> {
5995 if (mShowDialogs) {
5996 AlertDialog d = new BaseErrorDialog(mUiContext);
5997 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5998 d.setCancelable(false);
5999 d.setTitle(mUiContext.getText(R.string.android_system_label));
6000 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6001 d.setButton(DialogInterface.BUTTON_POSITIVE,
6002 mUiContext.getText(R.string.ok),
6003 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6004 d.show();
6005 }
6006 });
6007 }
6008 }
6009 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006010
6011 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006012 public void onProcessMapped(int pid, WindowProcessController proc) {
6013 synchronized (mGlobalLock) {
6014 mPidMap.put(pid, proc);
6015 }
6016 }
6017
6018 @Override
6019 public void onProcessUnMapped(int pid) {
6020 synchronized (mGlobalLock) {
6021 mPidMap.remove(pid);
6022 }
6023 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006024
6025 @Override
6026 public void onPackageDataCleared(String name) {
6027 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006028 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006029 mAppWarnings.onPackageDataCleared(name);
6030 }
6031 }
6032
6033 @Override
6034 public void onPackageUninstalled(String name) {
6035 synchronized (mGlobalLock) {
6036 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006037 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006038 }
6039 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006040
6041 @Override
6042 public void onPackageAdded(String name, boolean replacing) {
6043 synchronized (mGlobalLock) {
6044 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6045 }
6046 }
6047
6048 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006049 public void onPackageReplaced(ApplicationInfo aInfo) {
6050 synchronized (mGlobalLock) {
6051 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
6052 }
6053 }
6054
6055 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006056 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6057 synchronized (mGlobalLock) {
6058 return compatibilityInfoForPackageLocked(ai);
6059 }
6060 }
6061
Yunfan Chen75157d72018-07-27 14:47:21 +09006062 /**
6063 * Set the corresponding display information for the process global configuration. To be
6064 * called when we need to show IME on a different display.
6065 *
6066 * @param pid The process id associated with the IME window.
6067 * @param displayId The ID of the display showing the IME.
6068 */
6069 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006070 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006071 if (pid == MY_PID || pid < 0) {
6072 if (DEBUG_CONFIGURATION) {
6073 Slog.w(TAG,
6074 "Trying to update display configuration for system/invalid process.");
6075 }
6076 return;
6077 }
6078 mH.post(() -> {
6079 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006080 final ActivityDisplay activityDisplay =
6081 mStackSupervisor.getActivityDisplay(displayId);
6082 if (activityDisplay == null) {
6083 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006084 if (DEBUG_CONFIGURATION) {
6085 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006086 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006087 }
6088 return;
6089 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006090 final WindowProcessController process = mPidMap.get(pid);
6091 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006092 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006093 Slog.w(TAG, "Trying to update display configuration for invalid "
6094 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006095 }
6096 return;
6097 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006098 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006099 }
6100 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006101
Yunfan Chen75157d72018-07-27 14:47:21 +09006102 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006103
6104 @Override
6105 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6106 int requestCode, int resultCode, Intent data) {
6107 synchronized (mGlobalLock) {
6108 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6109 if (r != null && r.getStack() != null) {
6110 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6111 resultCode, data);
6112 }
6113 }
6114 }
6115
6116 @Override
6117 public void clearPendingResultForActivity(IBinder activityToken,
6118 WeakReference<PendingIntentRecord> pir) {
6119 synchronized (mGlobalLock) {
6120 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6121 if (r != null && r.pendingResults != null) {
6122 r.pendingResults.remove(pir);
6123 }
6124 }
6125 }
6126
6127 @Override
6128 public IIntentSender getIntentSender(int type, String packageName,
6129 int callingUid, int userId, IBinder token, String resultWho,
6130 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6131 Bundle bOptions) {
6132 synchronized (mGlobalLock) {
6133 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6134 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6135 }
6136 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006137
6138 @Override
6139 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6140 synchronized (mGlobalLock) {
6141 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6142 if (r == null) {
6143 return null;
6144 }
6145 if (r.mServiceConnectionsHolder == null) {
6146 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6147 ActivityTaskManagerService.this, r);
6148 }
6149
6150 return r.mServiceConnectionsHolder;
6151 }
6152 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006153
6154 @Override
6155 public Intent getHomeIntent() {
6156 synchronized (mGlobalLock) {
6157 return ActivityTaskManagerService.this.getHomeIntent();
6158 }
6159 }
6160
6161 @Override
6162 public boolean startHomeActivity(int userId, String reason) {
6163 synchronized (mGlobalLock) {
Louis Chang89f43fc2018-10-05 10:59:14 +08006164 return mStackSupervisor.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6165 }
6166 }
6167
6168 @Override
6169 public boolean startHomeOnAllDisplays(int userId, String reason) {
6170 synchronized (mGlobalLock) {
6171 return mStackSupervisor.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006172 }
6173 }
6174
6175 @Override
6176 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6177 synchronized (mGlobalLock) {
6178 if (mFactoryTest == FACTORY_TEST_OFF) {
6179 return false;
6180 }
6181 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6182 && wpc.mName.equals(mTopComponent.getPackageName())) {
6183 return true;
6184 }
6185 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6186 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6187 }
6188 }
6189
6190 @Override
6191 public void updateTopComponentForFactoryTest() {
6192 synchronized (mGlobalLock) {
6193 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6194 return;
6195 }
6196 final ResolveInfo ri = mContext.getPackageManager()
6197 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6198 final CharSequence errorMsg;
6199 if (ri != null) {
6200 final ActivityInfo ai = ri.activityInfo;
6201 final ApplicationInfo app = ai.applicationInfo;
6202 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6203 mTopAction = Intent.ACTION_FACTORY_TEST;
6204 mTopData = null;
6205 mTopComponent = new ComponentName(app.packageName, ai.name);
6206 errorMsg = null;
6207 } else {
6208 errorMsg = mContext.getResources().getText(
6209 com.android.internal.R.string.factorytest_not_system);
6210 }
6211 } else {
6212 errorMsg = mContext.getResources().getText(
6213 com.android.internal.R.string.factorytest_no_action);
6214 }
6215 if (errorMsg == null) {
6216 return;
6217 }
6218
6219 mTopAction = null;
6220 mTopData = null;
6221 mTopComponent = null;
6222 mUiHandler.post(() -> {
6223 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6224 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006225 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006226 });
6227 }
6228 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006229
6230 @Override
6231 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6232 Runnable finishInstrumentationCallback) {
6233 synchronized (mGlobalLock) {
6234 // Remove this application's activities from active lists.
6235 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6236
6237 wpc.clearRecentTasks();
6238 wpc.clearActivities();
6239
6240 if (wpc.isInstrumenting()) {
6241 finishInstrumentationCallback.run();
6242 }
6243
6244 mWindowManager.deferSurfaceLayout();
6245 try {
6246 if (!restarting && hasVisibleActivities
6247 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6248 // If there was nothing to resume, and we are not already restarting this
6249 // process, but there is a visible activity that is hosted by the process...
6250 // then make sure all visible activities are running, taking care of
6251 // restarting this process.
6252 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6253 }
6254 } finally {
6255 mWindowManager.continueSurfaceLayout();
6256 }
6257 }
6258 }
6259
6260 @Override
6261 public void closeSystemDialogs(String reason) {
6262 enforceNotIsolatedCaller("closeSystemDialogs");
6263
6264 final int pid = Binder.getCallingPid();
6265 final int uid = Binder.getCallingUid();
6266 final long origId = Binder.clearCallingIdentity();
6267 try {
6268 synchronized (mGlobalLock) {
6269 // Only allow this from foreground processes, so that background
6270 // applications can't abuse it to prevent system UI from being shown.
6271 if (uid >= FIRST_APPLICATION_UID) {
6272 final WindowProcessController proc = mPidMap.get(pid);
6273 if (!proc.isPerceptible()) {
6274 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6275 + " from background process " + proc);
6276 return;
6277 }
6278 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006279 mWindowManager.closeSystemDialogs(reason);
6280
6281 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006282 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006283 // Call into AM outside the synchronized block.
6284 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006285 } finally {
6286 Binder.restoreCallingIdentity(origId);
6287 }
6288 }
6289
6290 @Override
6291 public void cleanupDisabledPackageComponents(
6292 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6293 synchronized (mGlobalLock) {
6294 // Clean-up disabled activities.
6295 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6296 packageName, disabledClasses, true, false, userId) && booted) {
6297 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6298 mStackSupervisor.scheduleIdleLocked();
6299 }
6300
6301 // Clean-up disabled tasks
6302 getRecentTasks().cleanupDisabledPackageTasksLocked(
6303 packageName, disabledClasses, userId);
6304 }
6305 }
6306
6307 @Override
6308 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6309 int userId) {
6310 synchronized (mGlobalLock) {
6311
6312 boolean didSomething =
6313 getActivityStartController().clearPendingActivityLaunches(packageName);
6314 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6315 null, doit, evenPersistent, userId);
6316 return didSomething;
6317 }
6318 }
6319
6320 @Override
6321 public void resumeTopActivities(boolean scheduleIdle) {
6322 synchronized (mGlobalLock) {
6323 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6324 if (scheduleIdle) {
6325 mStackSupervisor.scheduleIdleLocked();
6326 }
6327 }
6328 }
6329
6330 @Override
6331 public void preBindApplication(WindowProcessController wpc) {
6332 synchronized (mGlobalLock) {
6333 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6334 }
6335 }
6336
6337 @Override
6338 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6339 synchronized (mGlobalLock) {
6340 return mStackSupervisor.attachApplicationLocked(wpc);
6341 }
6342 }
6343
6344 @Override
6345 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6346 try {
6347 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6348 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6349 }
6350 } catch (RemoteException ex) {
6351 throw new SecurityException("Fail to check is caller a privileged app", ex);
6352 }
6353
6354 synchronized (mGlobalLock) {
6355 final long ident = Binder.clearCallingIdentity();
6356 try {
6357 if (mAmInternal.shouldConfirmCredentials(userId)) {
6358 if (mKeyguardController.isKeyguardLocked()) {
6359 // Showing launcher to avoid user entering credential twice.
6360 startHomeActivity(currentUserId, "notifyLockedProfile");
6361 }
6362 mStackSupervisor.lockAllProfileTasks(userId);
6363 }
6364 } finally {
6365 Binder.restoreCallingIdentity(ident);
6366 }
6367 }
6368 }
6369
6370 @Override
6371 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6372 mAmInternal.enforceCallingPermission(
6373 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6374
6375 synchronized (mGlobalLock) {
6376 final long ident = Binder.clearCallingIdentity();
6377 try {
6378 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6379 FLAG_ACTIVITY_TASK_ON_HOME);
6380 ActivityOptions activityOptions = options != null
6381 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006382 final ActivityRecord homeActivity =
6383 mStackSupervisor.getDefaultDisplayHomeActivity();
6384 if (homeActivity != null) {
6385 activityOptions.setLaunchTaskId(homeActivity.getTask().taskId);
6386 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006387 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6388 UserHandle.CURRENT);
6389 } finally {
6390 Binder.restoreCallingIdentity(ident);
6391 }
6392 }
6393 }
6394
6395 @Override
6396 public void writeActivitiesToProto(ProtoOutputStream proto) {
6397 synchronized (mGlobalLock) {
6398 // The output proto of "activity --proto activities"
6399 // is ActivityManagerServiceDumpActivitiesProto
6400 mStackSupervisor.writeToProto(proto,
6401 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6402 }
6403 }
6404
6405 @Override
6406 public void saveANRState(String reason) {
6407 synchronized (mGlobalLock) {
6408 final StringWriter sw = new StringWriter();
6409 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6410 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6411 if (reason != null) {
6412 pw.println(" Reason: " + reason);
6413 }
6414 pw.println();
6415 getActivityStartController().dump(pw, " ", null);
6416 pw.println();
6417 pw.println("-------------------------------------------------------------------------------");
6418 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6419 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6420 "" /* header */);
6421 pw.println();
6422 pw.close();
6423
6424 mLastANRState = sw.toString();
6425 }
6426 }
6427
6428 @Override
6429 public void clearSavedANRState() {
6430 synchronized (mGlobalLock) {
6431 mLastANRState = null;
6432 }
6433 }
6434
6435 @Override
6436 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6437 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6438 synchronized (mGlobalLock) {
6439 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6440 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6441 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6442 dumpLastANRLocked(pw);
6443 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6444 dumpLastANRTracesLocked(pw);
6445 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6446 dumpActivityStarterLocked(pw, dumpPackage);
6447 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6448 dumpActivityContainersLocked(pw);
6449 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6450 if (getRecentTasks() != null) {
6451 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6452 }
6453 }
6454 }
6455 }
6456
6457 @Override
6458 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6459 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6460 int wakefulness) {
6461 synchronized (mGlobalLock) {
6462 if (mHomeProcess != null && (dumpPackage == null
6463 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6464 if (needSep) {
6465 pw.println();
6466 needSep = false;
6467 }
6468 pw.println(" mHomeProcess: " + mHomeProcess);
6469 }
6470 if (mPreviousProcess != null && (dumpPackage == null
6471 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6472 if (needSep) {
6473 pw.println();
6474 needSep = false;
6475 }
6476 pw.println(" mPreviousProcess: " + mPreviousProcess);
6477 }
6478 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6479 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6480 StringBuilder sb = new StringBuilder(128);
6481 sb.append(" mPreviousProcessVisibleTime: ");
6482 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6483 pw.println(sb);
6484 }
6485 if (mHeavyWeightProcess != null && (dumpPackage == null
6486 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6487 if (needSep) {
6488 pw.println();
6489 needSep = false;
6490 }
6491 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6492 }
6493 if (dumpPackage == null) {
6494 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6495 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6496 }
6497 if (dumpAll) {
6498 if (dumpPackage == null) {
6499 pw.println(" mConfigWillChange: "
6500 + getTopDisplayFocusedStack().mConfigWillChange);
6501 }
6502 if (mCompatModePackages.getPackages().size() > 0) {
6503 boolean printed = false;
6504 for (Map.Entry<String, Integer> entry
6505 : mCompatModePackages.getPackages().entrySet()) {
6506 String pkg = entry.getKey();
6507 int mode = entry.getValue();
6508 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6509 continue;
6510 }
6511 if (!printed) {
6512 pw.println(" mScreenCompatPackages:");
6513 printed = true;
6514 }
6515 pw.println(" " + pkg + ": " + mode);
6516 }
6517 }
6518 }
6519
6520 if (dumpPackage == null) {
6521 pw.println(" mWakefulness="
6522 + PowerManagerInternal.wakefulnessToString(wakefulness));
6523 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6524 if (mRunningVoice != null) {
6525 pw.println(" mRunningVoice=" + mRunningVoice);
6526 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6527 }
6528 pw.println(" mSleeping=" + mSleeping);
6529 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6530 pw.println(" mVrController=" + mVrController);
6531 }
6532 if (mCurAppTimeTracker != null) {
6533 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6534 }
6535 if (mAllowAppSwitchUids.size() > 0) {
6536 boolean printed = false;
6537 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6538 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6539 for (int j = 0; j < types.size(); j++) {
6540 if (dumpPackage == null ||
6541 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6542 if (needSep) {
6543 pw.println();
6544 needSep = false;
6545 }
6546 if (!printed) {
6547 pw.println(" mAllowAppSwitchUids:");
6548 printed = true;
6549 }
6550 pw.print(" User ");
6551 pw.print(mAllowAppSwitchUids.keyAt(i));
6552 pw.print(": Type ");
6553 pw.print(types.keyAt(j));
6554 pw.print(" = ");
6555 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6556 pw.println();
6557 }
6558 }
6559 }
6560 }
6561 if (dumpPackage == null) {
6562 if (mController != null) {
6563 pw.println(" mController=" + mController
6564 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6565 }
6566 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6567 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6568 }
6569
6570 return needSep;
6571 }
6572 }
6573
6574 @Override
6575 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6576 synchronized (mGlobalLock) {
6577 if (dumpPackage == null) {
6578 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6579 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6580 writeSleepStateToProto(proto);
6581 if (mController != null) {
6582 final long token = proto.start(CONTROLLER);
6583 proto.write(CONTROLLER, mController.toString());
6584 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6585 proto.end(token);
6586 }
6587 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6588 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6589 }
6590
6591 if (mHomeProcess != null && (dumpPackage == null
6592 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006593 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006594 }
6595
6596 if (mPreviousProcess != null && (dumpPackage == null
6597 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006598 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006599 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6600 }
6601
6602 if (mHeavyWeightProcess != null && (dumpPackage == null
6603 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006604 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006605 }
6606
6607 for (Map.Entry<String, Integer> entry
6608 : mCompatModePackages.getPackages().entrySet()) {
6609 String pkg = entry.getKey();
6610 int mode = entry.getValue();
6611 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6612 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6613 proto.write(PACKAGE, pkg);
6614 proto.write(MODE, mode);
6615 proto.end(compatToken);
6616 }
6617 }
6618
6619 if (mCurAppTimeTracker != null) {
6620 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6621 }
6622
6623 }
6624 }
6625
6626 @Override
6627 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6628 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6629 boolean dumpFocusedStackOnly) {
6630 synchronized (mGlobalLock) {
6631 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6632 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6633 }
6634 }
6635
6636 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006637 public void dumpForOom(PrintWriter pw) {
6638 synchronized (mGlobalLock) {
6639 pw.println(" mHomeProcess: " + mHomeProcess);
6640 pw.println(" mPreviousProcess: " + mPreviousProcess);
6641 if (mHeavyWeightProcess != null) {
6642 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6643 }
6644 }
6645 }
6646
6647 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006648 public boolean canGcNow() {
6649 synchronized (mGlobalLock) {
6650 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6651 }
6652 }
6653
6654 @Override
6655 public WindowProcessController getTopApp() {
6656 synchronized (mGlobalLock) {
6657 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6658 return top != null ? top.app : null;
6659 }
6660 }
6661
6662 @Override
6663 public void rankTaskLayersIfNeeded() {
6664 synchronized (mGlobalLock) {
6665 if (mStackSupervisor != null) {
6666 mStackSupervisor.rankTaskLayersIfNeeded();
6667 }
6668 }
6669 }
6670
6671 @Override
6672 public void scheduleDestroyAllActivities(String reason) {
6673 synchronized (mGlobalLock) {
6674 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6675 }
6676 }
6677
6678 @Override
6679 public void removeUser(int userId) {
6680 synchronized (mGlobalLock) {
6681 mStackSupervisor.removeUserLocked(userId);
6682 }
6683 }
6684
6685 @Override
6686 public boolean switchUser(int userId, UserState userState) {
6687 synchronized (mGlobalLock) {
6688 return mStackSupervisor.switchUserLocked(userId, userState);
6689 }
6690 }
6691
6692 @Override
6693 public void onHandleAppCrash(WindowProcessController wpc) {
6694 synchronized (mGlobalLock) {
6695 mStackSupervisor.handleAppCrashLocked(wpc);
6696 }
6697 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006698
6699 @Override
6700 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6701 synchronized (mGlobalLock) {
6702 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6703 }
6704 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006705
6706 @Override
6707 public void onUidActive(int uid, int procState) {
6708 synchronized (mGlobalLock) {
6709 mActiveUids.put(uid, procState);
6710 }
6711 }
6712
6713 @Override
6714 public void onUidInactive(int uid) {
6715 synchronized (mGlobalLock) {
6716 mActiveUids.remove(uid);
6717 }
6718 }
6719
6720 @Override
6721 public void onActiveUidsCleared() {
6722 synchronized (mGlobalLock) {
6723 mActiveUids.clear();
6724 }
6725 }
6726
6727 @Override
6728 public void onUidProcStateChanged(int uid, int procState) {
6729 synchronized (mGlobalLock) {
6730 if (mActiveUids.get(uid) != null) {
6731 mActiveUids.put(uid, procState);
6732 }
6733 }
6734 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006735
6736 @Override
6737 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6738 synchronized (mGlobalLock) {
6739 mPendingTempWhitelist.put(uid, tag);
6740 }
6741 }
6742
6743 @Override
6744 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6745 synchronized (mGlobalLock) {
6746 mPendingTempWhitelist.remove(uid);
6747 }
6748 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006749
6750 @Override
6751 public boolean handleAppCrashInActivityController(String processName, int pid,
6752 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6753 Runnable killCrashingAppCallback) {
6754 synchronized (mGlobalLock) {
6755 if (mController == null) {
6756 return false;
6757 }
6758
6759 try {
6760 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6761 stackTrace)) {
6762 killCrashingAppCallback.run();
6763 return true;
6764 }
6765 } catch (RemoteException e) {
6766 mController = null;
6767 Watchdog.getInstance().setActivityController(null);
6768 }
6769 return false;
6770 }
6771 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006772
6773 @Override
6774 public void removeRecentTasksByPackageName(String packageName, int userId) {
6775 synchronized (mGlobalLock) {
6776 mRecentTasks.removeTasksByPackageName(packageName, userId);
6777 }
6778 }
6779
6780 @Override
6781 public void cleanupRecentTasksForUser(int userId) {
6782 synchronized (mGlobalLock) {
6783 mRecentTasks.cleanupLocked(userId);
6784 }
6785 }
6786
6787 @Override
6788 public void loadRecentTasksForUser(int userId) {
6789 synchronized (mGlobalLock) {
6790 mRecentTasks.loadUserRecentsLocked(userId);
6791 }
6792 }
6793
6794 @Override
6795 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6796 synchronized (mGlobalLock) {
6797 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6798 }
6799 }
6800
6801 @Override
6802 public void flushRecentTasks() {
6803 mRecentTasks.flush();
6804 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006805
6806 @Override
6807 public WindowProcessController getHomeProcess() {
6808 synchronized (mGlobalLock) {
6809 return mHomeProcess;
6810 }
6811 }
6812
6813 @Override
6814 public WindowProcessController getPreviousProcess() {
6815 synchronized (mGlobalLock) {
6816 return mPreviousProcess;
6817 }
6818 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006819
6820 @Override
6821 public void clearLockedTasks(String reason) {
6822 synchronized (mGlobalLock) {
6823 getLockTaskController().clearLockedTasks(reason);
6824 }
6825 }
6826
6827 @Override
6828 public void updateUserConfiguration() {
6829 synchronized (mGlobalLock) {
6830 final Configuration configuration = new Configuration(getGlobalConfiguration());
6831 final int currentUserId = mAmInternal.getCurrentUserId();
6832 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6833 configuration, currentUserId, Settings.System.canWrite(mContext));
6834 updateConfigurationLocked(configuration, null /* starting */,
6835 false /* initLocale */, false /* persistent */, currentUserId,
6836 false /* deferResume */);
6837 }
6838 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006839
6840 @Override
6841 public boolean canShowErrorDialogs() {
6842 synchronized (mGlobalLock) {
6843 return mShowDialogs && !mSleeping && !mShuttingDown
6844 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6845 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6846 mAmInternal.getCurrentUserId())
6847 && !(UserManager.isDeviceInDemoMode(mContext)
6848 && mAmInternal.getCurrentUser().isDemo());
6849 }
6850 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006851
6852 @Override
6853 public void setProfileApp(String profileApp) {
6854 synchronized (mGlobalLock) {
6855 mProfileApp = profileApp;
6856 }
6857 }
6858
6859 @Override
6860 public void setProfileProc(WindowProcessController wpc) {
6861 synchronized (mGlobalLock) {
6862 mProfileProc = wpc;
6863 }
6864 }
6865
6866 @Override
6867 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6868 synchronized (mGlobalLock) {
6869 mProfilerInfo = profilerInfo;
6870 }
6871 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006872 }
Wale Ogunwale38f72bd2018-11-20 02:53:49 +00006873}