blob: d480fb732df3c7db2937e1d8d36d2e1c5a84caaa [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;
Wale Ogunwale59507092018-10-29 09:00:30 -070094import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
95import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
96import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
113import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
114import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
116import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
117import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
118import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800119import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
120import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700121import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
122import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800123import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
124import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800125import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
126import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
127import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700128
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.annotation.Nullable;
132import android.annotation.UserIdInt;
133import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700134import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700135import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.ActivityOptions;
137import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700138import android.app.ActivityThread;
139import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700141import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700142import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700143import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.IApplicationThread;
145import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Evan Rosky4505b352018-09-06 11:20:40 -0700247import com.android.server.AppOpsService;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800249import com.android.server.DisplayThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700277import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700279import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700280import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400282import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700285import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Map;
287import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288
289/**
290 * System service for managing activities and their containers (task, stacks, displays,... ).
291 *
292 * {@hide}
293 */
294public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700295 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700297 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
298 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
299 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
300 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
301 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700302 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700307 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308
Wale Ogunwale98875612018-10-12 07:53:02 -0700309 /** Used to indicate that an app transition should be animated. */
310 static final boolean ANIMATE = true;
311
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700312 /** Hardware-reported OpenGLES version. */
313 final int GL_ES_VERSION;
314
Wale Ogunwale31913b52018-10-13 08:29:31 -0700315 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
316 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
317 public static final String DUMP_LASTANR_CMD = "lastanr" ;
318 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
319 public static final String DUMP_STARTER_CMD = "starter" ;
320 public static final String DUMP_CONTAINERS_CMD = "containers" ;
321 public static final String DUMP_RECENTS_CMD = "recents" ;
322 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
323
Wale Ogunwale64258362018-10-16 15:13:37 -0700324 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
325 public static final int RELAUNCH_REASON_NONE = 0;
326 /** This activity is being relaunched due to windowing mode change. */
327 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
328 /** This activity is being relaunched due to a free-resize operation. */
329 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
330
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700331 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700332
Wale Ogunwalef6733932018-06-27 05:14:34 -0700333 /**
334 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
335 * change at runtime. Use mContext for non-UI purposes.
336 */
337 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700338 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700339 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700342 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700343 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800344 @VisibleForTesting
345 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 PowerManagerInternal mPowerManagerInternal;
347 private UsageStatsManagerInternal mUsageStatsInternal;
348
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700349 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 IntentFirewall mIntentFirewall;
351
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700352 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800353 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700354 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800355 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700356 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700357 private UserManagerService mUserManager;
358 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700359 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700360 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
361 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700362 /** All processes currently running that might have a window organized by name. */
363 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700364 /** All processes we currently have running mapped by pid */
365 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700366 /** This is the process holding what we currently consider to be the "home" activity. */
367 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700368 /** The currently running heavy-weight process, if any. */
369 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700370 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700371 /**
372 * This is the process holding the activity the user last visited that is in a different process
373 * from the one they are currently in.
374 */
375 WindowProcessController mPreviousProcess;
376 /** The time at which the previous process was last visible. */
377 long mPreviousProcessVisibleTime;
378
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700379 /** List of intents that were used to start the most recent tasks. */
380 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700381 /** State of external calls telling us if the device is awake or asleep. */
382 private boolean mKeyguardShown = false;
383
384 // Wrapper around VoiceInteractionServiceManager
385 private AssistUtils mAssistUtils;
386
387 // VoiceInteraction session ID that changes for each new request except when
388 // being called for multi-window assist in a single session.
389 private int mViSessionId = 1000;
390
391 // How long to wait in getAssistContextExtras for the activity and foreground services
392 // to respond with the result.
393 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
394
395 // How long top wait when going through the modern assist (which doesn't need to block
396 // on getting this result before starting to launch its UI).
397 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
398
399 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
400 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
401
Alison Cichowlas3e340502018-08-07 17:15:01 -0400402 // Permission tokens are used to temporarily granted a trusted app the ability to call
403 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
404 // showing any appropriate error messages to the user.
405 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
406 10 * MINUTE_IN_MILLIS;
407
408 // How long before the service actually expires a token. This is slightly longer than
409 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
410 // expiration exception.
411 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
412 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
413
414 // How long the service will remember expired tokens, for the purpose of providing error
415 // messaging when a client uses an expired token.
416 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
417 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
418
419 // Activity tokens of system activities that are delegating their call to
420 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
421 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
422
423 // Permission tokens that have expired, but we remember for error reporting.
424 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
425
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700426 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
427
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700428 // Keeps track of the active voice interaction service component, notified from
429 // VoiceInteractionManagerService
430 ComponentName mActiveVoiceInteractionServiceComponent;
431
Wale Ogunwalee2172292018-10-25 10:11:10 -0700432 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700433 KeyguardController mKeyguardController;
434 private final ClientLifecycleManager mLifecycleManager;
435 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700436 /** The controller for all operations related to locktask. */
437 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700438 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700440 boolean mSuppressResizeConfigChanges;
441
442 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
443 new UpdateConfigurationResult();
444
445 static final class UpdateConfigurationResult {
446 // Configuration changes that were updated.
447 int changes;
448 // If the activity was relaunched to match the new configuration.
449 boolean activityRelaunched;
450
451 void reset() {
452 changes = 0;
453 activityRelaunched = false;
454 }
455 }
456
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700457 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700458 private int mConfigurationSeq;
459 // To cache the list of supported system locales
460 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700461
462 /**
463 * Temp object used when global and/or display override configuration is updated. It is also
464 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
465 * anyone...
466 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700467 private Configuration mTempConfig = new Configuration();
468
Wale Ogunwalef6733932018-06-27 05:14:34 -0700469 /** Temporary to avoid allocations. */
470 final StringBuilder mStringBuilder = new StringBuilder(256);
471
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700472 // Amount of time after a call to stopAppSwitches() during which we will
473 // prevent further untrusted switches from happening.
474 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
475
476 /**
477 * The time at which we will allow normal application switches again,
478 * after a call to {@link #stopAppSwitches()}.
479 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700480 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 /**
482 * This is set to true after the first switch after mAppSwitchesAllowedTime
483 * is set; any switches after that will clear the time.
484 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700485 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486
487 IActivityController mController = null;
488 boolean mControllerIsAMonkey = false;
489
Wale Ogunwale214f3482018-10-04 11:00:47 -0700490 final int mFactoryTest;
491
492 /** Used to control how we initialize the service. */
493 ComponentName mTopComponent;
494 String mTopAction = Intent.ACTION_MAIN;
495 String mTopData;
496
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800497 /** Profiling app information. */
498 String mProfileApp = null;
499 WindowProcessController mProfileProc = null;
500 ProfilerInfo mProfilerInfo = null;
501
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700503 * Dump of the activity state at the time of the last ANR. Cleared after
504 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
505 */
506 String mLastANRState;
507
508 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509 * Used to retain an update lock when the foreground activity is in
510 * immersive mode.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513
514 /**
515 * Packages that are being allowed to perform unrestricted app switches. Mapping is
516 * User -> Type -> uid.
517 */
518 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
519
520 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700521 private int mThumbnailWidth;
522 private int mThumbnailHeight;
523 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700524
525 /**
526 * Flag that indicates if multi-window is enabled.
527 *
528 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
529 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
530 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
531 * At least one of the forms of multi-window must be enabled in order for this flag to be
532 * initialized to 'true'.
533 *
534 * @see #mSupportsSplitScreenMultiWindow
535 * @see #mSupportsFreeformWindowManagement
536 * @see #mSupportsPictureInPicture
537 * @see #mSupportsMultiDisplay
538 */
539 boolean mSupportsMultiWindow;
540 boolean mSupportsSplitScreenMultiWindow;
541 boolean mSupportsFreeformWindowManagement;
542 boolean mSupportsPictureInPicture;
543 boolean mSupportsMultiDisplay;
544 boolean mForceResizableActivities;
545
546 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
547
548 // VR Vr2d Display Id.
549 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700550
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 /**
552 * Set while we are wanting to sleep, to prevent any
553 * activities from being started/resumed.
554 *
555 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
556 *
557 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
558 * while in the sleep state until there is a pending transition out of sleep, in which case
559 * mSleeping is set to false, and remains false while awake.
560 *
561 * Whether mSleeping can quickly toggled between true/false without the device actually
562 * display changing states is undefined.
563 */
564 private boolean mSleeping = false;
565
566 /**
567 * The process state used for processes that are running the top activities.
568 * This changes between TOP and TOP_SLEEPING to following mSleeping.
569 */
570 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
571
572 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
573 // automatically. Important for devices without direct input devices.
574 private boolean mShowDialogs = true;
575
576 /** Set if we are shutting down the system, similar to sleeping. */
577 boolean mShuttingDown = false;
578
579 /**
580 * We want to hold a wake lock while running a voice interaction session, since
581 * this may happen with the screen off and we need to keep the CPU running to
582 * be able to continue to interact with the user.
583 */
584 PowerManager.WakeLock mVoiceWakeLock;
585
586 /**
587 * Set while we are running a voice interaction. This overrides sleeping while it is active.
588 */
589 IVoiceInteractionSession mRunningVoice;
590
591 /**
592 * The last resumed activity. This is identical to the current resumed activity most
593 * of the time but could be different when we're pausing one activity before we resume
594 * another activity.
595 */
596 ActivityRecord mLastResumedActivity;
597
598 /**
599 * The activity that is currently being traced as the active resumed activity.
600 *
601 * @see #updateResumedAppTrace
602 */
603 private @Nullable ActivityRecord mTracedResumedActivity;
604
605 /** If non-null, we are tracking the time the user spends in the currently focused app. */
606 AppTimeTracker mCurAppTimeTracker;
607
Wale Ogunwale008163e2018-07-23 23:11:08 -0700608 private AppWarnings mAppWarnings;
609
Wale Ogunwale53783742018-09-16 10:21:51 -0700610 /**
611 * Packages that the user has asked to have run in screen size
612 * compatibility mode instead of filling the screen.
613 */
614 CompatModePackages mCompatModePackages;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 private FontScaleSettingObserver mFontScaleSettingObserver;
617
618 private final class FontScaleSettingObserver extends ContentObserver {
619 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
620 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
621
622 public FontScaleSettingObserver() {
623 super(mH);
624 final ContentResolver resolver = mContext.getContentResolver();
625 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
626 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
627 UserHandle.USER_ALL);
628 }
629
630 @Override
631 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
632 if (mFontScaleUri.equals(uri)) {
633 updateFontScaleIfNeeded(userId);
634 } else if (mHideErrorDialogsUri.equals(uri)) {
635 synchronized (mGlobalLock) {
636 updateShouldShowDialogsLocked(getGlobalConfiguration());
637 }
638 }
639 }
640 }
641
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700642 ActivityTaskManagerService(Context context) {
643 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700644 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700645 mSystemThread = ActivityThread.currentActivityThread();
646 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700647 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800648 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700649 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700650 }
651
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700652 public void onSystemReady() {
653 synchronized (mGlobalLock) {
654 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
655 PackageManager.FEATURE_CANT_SAVE_STATE);
656 mAssistUtils = new AssistUtils(mContext);
657 mVrController.onSystemReady();
658 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700659 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700660 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700661 }
662
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700663 public void onInitPowerManagement() {
664 synchronized (mGlobalLock) {
665 mStackSupervisor.initPowerManagement();
666 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
667 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
668 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
669 mVoiceWakeLock.setReferenceCounted(false);
670 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 }
672
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700673 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700674 mFontScaleSettingObserver = new FontScaleSettingObserver();
675 }
676
Wale Ogunwale59507092018-10-29 09:00:30 -0700677 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700678 final boolean freeformWindowManagement =
679 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
680 || Settings.Global.getInt(
681 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
682
683 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
684 final boolean supportsPictureInPicture = supportsMultiWindow &&
685 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
686 final boolean supportsSplitScreenMultiWindow =
687 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
688 final boolean supportsMultiDisplay = mContext.getPackageManager()
689 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700690 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
691 final boolean forceResizable = Settings.Global.getInt(
692 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700693 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700694
695 // Transfer any global setting for forcing RTL layout, into a System Property
696 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
697
698 final Configuration configuration = new Configuration();
699 Settings.System.getConfiguration(resolver, configuration);
700 if (forceRtl) {
701 // This will take care of setting the correct layout direction flags
702 configuration.setLayoutDirection(configuration.locale);
703 }
704
705 synchronized (mGlobalLock) {
706 mForceResizableActivities = forceResizable;
707 final boolean multiWindowFormEnabled = freeformWindowManagement
708 || supportsSplitScreenMultiWindow
709 || supportsPictureInPicture
710 || supportsMultiDisplay;
711 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
712 mSupportsMultiWindow = true;
713 mSupportsFreeformWindowManagement = freeformWindowManagement;
714 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
715 mSupportsPictureInPicture = supportsPictureInPicture;
716 mSupportsMultiDisplay = supportsMultiDisplay;
717 } else {
718 mSupportsMultiWindow = false;
719 mSupportsFreeformWindowManagement = false;
720 mSupportsSplitScreenMultiWindow = false;
721 mSupportsPictureInPicture = false;
722 mSupportsMultiDisplay = false;
723 }
724 mWindowManager.setForceResizableTasks(mForceResizableActivities);
725 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700726 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
727 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728 // This happens before any activities are started, so we can change global configuration
729 // in-place.
730 updateConfigurationLocked(configuration, null, true);
731 final Configuration globalConfig = getGlobalConfiguration();
732 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
733
734 // Load resources only after the current configuration has been set.
735 final Resources res = mContext.getResources();
736 mThumbnailWidth = res.getDimensionPixelSize(
737 com.android.internal.R.dimen.thumbnail_width);
738 mThumbnailHeight = res.getDimensionPixelSize(
739 com.android.internal.R.dimen.thumbnail_height);
740
741 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
742 mFullscreenThumbnailScale = (float) res
743 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
744 (float) globalConfig.screenWidthDp;
745 } else {
746 mFullscreenThumbnailScale = res.getFraction(
747 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
748 }
749 }
750 }
751
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800752 public WindowManagerGlobalLock getGlobalLock() {
753 return mGlobalLock;
754 }
755
756 public void setActivityManagerService(IntentFirewall intentFirewall,
757 PendingIntentController intentController) {
758 mH = new H();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700759 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700760 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700761 final File systemDir = SystemServiceManager.ensureSystemDir();
762 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
763 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700764 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700765
766 mTempConfig.setToDefaults();
767 mTempConfig.setLocales(LocaleList.getDefault());
768 mConfigurationSeq = mTempConfig.seq = 1;
769 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800770 mRootActivityContainer = new RootActivityContainer(this);
771 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700772
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700773 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700775 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700776 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700777 mRecentTasks = createRecentTasks();
778 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700779 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700780 mKeyguardController = mStackSupervisor.getKeyguardController();
781 }
782
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700783 public void onActivityManagerInternalAdded() {
784 synchronized (mGlobalLock) {
785 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
786 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
787 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700788 }
789
Yunfan Chen75157d72018-07-27 14:47:21 +0900790 int increaseConfigurationSeqLocked() {
791 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
792 return mConfigurationSeq;
793 }
794
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700795 protected ActivityStackSupervisor createStackSupervisor() {
796 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
797 supervisor.initialize();
798 return supervisor;
799 }
800
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700801 public void setWindowManager(WindowManagerService wm) {
802 synchronized (mGlobalLock) {
803 mWindowManager = wm;
804 mLockTaskController.setWindowManager(wm);
805 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800806 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700807 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
811 synchronized (mGlobalLock) {
812 mUsageStatsInternal = usageStatsManager;
813 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700814 }
815
Wale Ogunwalef6733932018-06-27 05:14:34 -0700816 UserManagerService getUserManager() {
817 if (mUserManager == null) {
818 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
819 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
820 }
821 return mUserManager;
822 }
823
824 AppOpsService getAppOpsService() {
825 if (mAppOpsService == null) {
826 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
827 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
828 }
829 return mAppOpsService;
830 }
831
832 boolean hasUserRestriction(String restriction, int userId) {
833 return getUserManager().hasUserRestriction(restriction, userId);
834 }
835
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700836 protected RecentTasks createRecentTasks() {
837 return new RecentTasks(this, mStackSupervisor);
838 }
839
840 RecentTasks getRecentTasks() {
841 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700842 }
843
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700844 ClientLifecycleManager getLifecycleManager() {
845 return mLifecycleManager;
846 }
847
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700848 ActivityStartController getActivityStartController() {
849 return mActivityStartController;
850 }
851
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700852 TaskChangeNotificationController getTaskChangeNotificationController() {
853 return mTaskChangeNotificationController;
854 }
855
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700856 LockTaskController getLockTaskController() {
857 return mLockTaskController;
858 }
859
Yunfan Chen75157d72018-07-27 14:47:21 +0900860 /**
861 * Return the global configuration used by the process corresponding to the input pid. This is
862 * usually the global configuration with some overrides specific to that process.
863 */
864 Configuration getGlobalConfigurationForCallingPid() {
865 final int pid = Binder.getCallingPid();
866 if (pid == MY_PID || pid < 0) {
867 return getGlobalConfiguration();
868 }
869 synchronized (mGlobalLock) {
870 final WindowProcessController app = mPidMap.get(pid);
871 return app != null ? app.getConfiguration() : getGlobalConfiguration();
872 }
873 }
874
875 /**
876 * Return the device configuration info used by the process corresponding to the input pid.
877 * The value is consistent with the global configuration for the process.
878 */
879 @Override
880 public ConfigurationInfo getDeviceConfigurationInfo() {
881 ConfigurationInfo config = new ConfigurationInfo();
882 synchronized (mGlobalLock) {
883 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
884 config.reqTouchScreen = globalConfig.touchscreen;
885 config.reqKeyboardType = globalConfig.keyboard;
886 config.reqNavigation = globalConfig.navigation;
887 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
888 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
889 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
890 }
891 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
892 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
893 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
894 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700895 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900896 }
897 return config;
898 }
899
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700900 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700901 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700902 }
903
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700904 public static final class Lifecycle extends SystemService {
905 private final ActivityTaskManagerService mService;
906
907 public Lifecycle(Context context) {
908 super(context);
909 mService = new ActivityTaskManagerService(context);
910 }
911
912 @Override
913 public void onStart() {
914 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700915 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700916 }
917
Garfield Tan891146c2018-10-09 12:14:00 -0700918 @Override
919 public void onUnlockUser(int userId) {
920 synchronized (mService.getGlobalLock()) {
921 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
922 }
923 }
924
925 @Override
926 public void onCleanupUser(int userId) {
927 synchronized (mService.getGlobalLock()) {
928 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
929 }
930 }
931
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700932 public ActivityTaskManagerService getService() {
933 return mService;
934 }
935 }
936
937 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700938 public final int startActivity(IApplicationThread caller, String callingPackage,
939 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
940 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
941 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
942 resultWho, requestCode, startFlags, profilerInfo, bOptions,
943 UserHandle.getCallingUserId());
944 }
945
946 @Override
947 public final int startActivities(IApplicationThread caller, String callingPackage,
948 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
949 int userId) {
950 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700951 enforceNotIsolatedCaller(reason);
952 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700953 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700954 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100955 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
956 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700957 }
958
959 @Override
960 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
961 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
962 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
963 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
964 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
965 true /*validateIncomingUser*/);
966 }
967
968 int startActivityAsUser(IApplicationThread caller, String callingPackage,
969 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
970 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
971 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700972 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700973
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700974 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700975 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
976
977 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700978 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700979 .setCaller(caller)
980 .setCallingPackage(callingPackage)
981 .setResolvedType(resolvedType)
982 .setResultTo(resultTo)
983 .setResultWho(resultWho)
984 .setRequestCode(requestCode)
985 .setStartFlags(startFlags)
986 .setProfilerInfo(profilerInfo)
987 .setActivityOptions(bOptions)
988 .setMayWait(userId)
989 .execute();
990
991 }
992
993 @Override
994 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
995 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700996 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
997 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700998 // Refuse possible leaked file descriptors
999 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1000 throw new IllegalArgumentException("File descriptors passed in Intent");
1001 }
1002
1003 if (!(target instanceof PendingIntentRecord)) {
1004 throw new IllegalArgumentException("Bad PendingIntent object");
1005 }
1006
1007 PendingIntentRecord pir = (PendingIntentRecord)target;
1008
1009 synchronized (mGlobalLock) {
1010 // If this is coming from the currently resumed activity, it is
1011 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001012 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 if (stack.mResumedActivity != null &&
1014 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 }
1017 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001018 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 }
1021
1022 @Override
1023 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1024 Bundle bOptions) {
1025 // Refuse possible leaked file descriptors
1026 if (intent != null && intent.hasFileDescriptors()) {
1027 throw new IllegalArgumentException("File descriptors passed in Intent");
1028 }
1029 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1030
1031 synchronized (mGlobalLock) {
1032 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1033 if (r == null) {
1034 SafeActivityOptions.abort(options);
1035 return false;
1036 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001037 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 // The caller is not running... d'oh!
1039 SafeActivityOptions.abort(options);
1040 return false;
1041 }
1042 intent = new Intent(intent);
1043 // The caller is not allowed to change the data.
1044 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1045 // And we are resetting to find the next component...
1046 intent.setComponent(null);
1047
1048 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1049
1050 ActivityInfo aInfo = null;
1051 try {
1052 List<ResolveInfo> resolves =
1053 AppGlobals.getPackageManager().queryIntentActivities(
1054 intent, r.resolvedType,
1055 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1056 UserHandle.getCallingUserId()).getList();
1057
1058 // Look for the original activity in the list...
1059 final int N = resolves != null ? resolves.size() : 0;
1060 for (int i=0; i<N; i++) {
1061 ResolveInfo rInfo = resolves.get(i);
1062 if (rInfo.activityInfo.packageName.equals(r.packageName)
1063 && rInfo.activityInfo.name.equals(r.info.name)) {
1064 // We found the current one... the next matching is
1065 // after it.
1066 i++;
1067 if (i<N) {
1068 aInfo = resolves.get(i).activityInfo;
1069 }
1070 if (debug) {
1071 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1072 + "/" + r.info.name);
1073 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1074 ? "null" : aInfo.packageName + "/" + aInfo.name));
1075 }
1076 break;
1077 }
1078 }
1079 } catch (RemoteException e) {
1080 }
1081
1082 if (aInfo == null) {
1083 // Nobody who is next!
1084 SafeActivityOptions.abort(options);
1085 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1086 return false;
1087 }
1088
1089 intent.setComponent(new ComponentName(
1090 aInfo.applicationInfo.packageName, aInfo.name));
1091 intent.setFlags(intent.getFlags()&~(
1092 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1093 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1094 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1095 FLAG_ACTIVITY_NEW_TASK));
1096
1097 // Okay now we need to start the new activity, replacing the currently running activity.
1098 // This is a little tricky because we want to start the new one as if the current one is
1099 // finished, but not finish the current one first so that there is no flicker.
1100 // And thus...
1101 final boolean wasFinishing = r.finishing;
1102 r.finishing = true;
1103
1104 // Propagate reply information over to the new activity.
1105 final ActivityRecord resultTo = r.resultTo;
1106 final String resultWho = r.resultWho;
1107 final int requestCode = r.requestCode;
1108 r.resultTo = null;
1109 if (resultTo != null) {
1110 resultTo.removeResultsLocked(r, resultWho, requestCode);
1111 }
1112
1113 final long origId = Binder.clearCallingIdentity();
1114 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001115 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001116 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001117 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001118 .setResolvedType(r.resolvedType)
1119 .setActivityInfo(aInfo)
1120 .setResultTo(resultTo != null ? resultTo.appToken : null)
1121 .setResultWho(resultWho)
1122 .setRequestCode(requestCode)
1123 .setCallingPid(-1)
1124 .setCallingUid(r.launchedFromUid)
1125 .setCallingPackage(r.launchedFromPackage)
1126 .setRealCallingPid(-1)
1127 .setRealCallingUid(r.launchedFromUid)
1128 .setActivityOptions(options)
1129 .execute();
1130 Binder.restoreCallingIdentity(origId);
1131
1132 r.finishing = wasFinishing;
1133 if (res != ActivityManager.START_SUCCESS) {
1134 return false;
1135 }
1136 return true;
1137 }
1138 }
1139
1140 @Override
1141 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1142 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1143 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1144 final WaitResult res = new WaitResult();
1145 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001146 enforceNotIsolatedCaller("startActivityAndWait");
1147 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1148 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001149 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001150 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001151 .setCaller(caller)
1152 .setCallingPackage(callingPackage)
1153 .setResolvedType(resolvedType)
1154 .setResultTo(resultTo)
1155 .setResultWho(resultWho)
1156 .setRequestCode(requestCode)
1157 .setStartFlags(startFlags)
1158 .setActivityOptions(bOptions)
1159 .setMayWait(userId)
1160 .setProfilerInfo(profilerInfo)
1161 .setWaitResult(res)
1162 .execute();
1163 }
1164 return res;
1165 }
1166
1167 @Override
1168 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1169 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1170 int startFlags, Configuration config, Bundle bOptions, int userId) {
1171 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001172 enforceNotIsolatedCaller("startActivityWithConfig");
1173 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1174 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001176 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .setCaller(caller)
1178 .setCallingPackage(callingPackage)
1179 .setResolvedType(resolvedType)
1180 .setResultTo(resultTo)
1181 .setResultWho(resultWho)
1182 .setRequestCode(requestCode)
1183 .setStartFlags(startFlags)
1184 .setGlobalConfiguration(config)
1185 .setActivityOptions(bOptions)
1186 .setMayWait(userId)
1187 .execute();
1188 }
1189 }
1190
Alison Cichowlas3e340502018-08-07 17:15:01 -04001191
1192 @Override
1193 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1194 int callingUid = Binder.getCallingUid();
1195 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1196 throw new SecurityException("Only the system process can request a permission token, "
1197 + "received request from uid: " + callingUid);
1198 }
1199 IBinder permissionToken = new Binder();
1200 synchronized (mGlobalLock) {
1201 mStartActivitySources.put(permissionToken, delegatorToken);
1202 }
1203
1204 Message expireMsg = PooledLambda.obtainMessage(
1205 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1206 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1207
1208 Message forgetMsg = PooledLambda.obtainMessage(
1209 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1210 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1211
1212 return permissionToken;
1213 }
1214
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001215 @Override
1216 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1217 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001218 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1219 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001221 // permission grants) as any app that may launch one of your own activities. So we only
1222 // allow this in two cases:
1223 // 1) The caller is an activity that is part of the core framework, and then only when it
1224 // is running as the system.
1225 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1226 // can only be requested by a system activity, which may then delegate this call to
1227 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 final ActivityRecord sourceRecord;
1229 final int targetUid;
1230 final String targetPackage;
1231 final boolean isResolver;
1232 synchronized (mGlobalLock) {
1233 if (resultTo == null) {
1234 throw new SecurityException("Must be called from an activity");
1235 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001236 final IBinder sourceToken;
1237 if (permissionToken != null) {
1238 // To even attempt to use a permissionToken, an app must also have this signature
1239 // permission.
1240 mAmInternal.enforceCallingPermission(
1241 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1242 "startActivityAsCaller");
1243 // If called with a permissionToken, we want the sourceRecord from the delegator
1244 // activity that requested this token.
1245 sourceToken = mStartActivitySources.remove(permissionToken);
1246 if (sourceToken == null) {
1247 // Invalid permissionToken, check if it recently expired.
1248 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1249 throw new SecurityException("Called with expired permission token: "
1250 + permissionToken);
1251 } else {
1252 throw new SecurityException("Called with invalid permission token: "
1253 + permissionToken);
1254 }
1255 }
1256 } else {
1257 // This method was called directly by the source.
1258 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001259 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001260
Wale Ogunwaled32da472018-11-16 07:19:28 -08001261 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001262 if (sourceRecord == null) {
1263 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 }
1265 if (sourceRecord.app == null) {
1266 throw new SecurityException("Called without a process attached to activity");
1267 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268
1269 // Whether called directly or from a delegate, the source activity must be from the
1270 // android package.
1271 if (!sourceRecord.info.packageName.equals("android")) {
1272 throw new SecurityException("Must be called from an activity that is "
1273 + "declared in the android package");
1274 }
1275
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001276 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001277 // This is still okay, as long as this activity is running under the
1278 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001279 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001281 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 + " must be system uid or original calling uid "
1283 + sourceRecord.launchedFromUid);
1284 }
1285 }
1286 if (ignoreTargetSecurity) {
1287 if (intent.getComponent() == null) {
1288 throw new SecurityException(
1289 "Component must be specified with ignoreTargetSecurity");
1290 }
1291 if (intent.getSelector() != null) {
1292 throw new SecurityException(
1293 "Selector not allowed with ignoreTargetSecurity");
1294 }
1295 }
1296 targetUid = sourceRecord.launchedFromUid;
1297 targetPackage = sourceRecord.launchedFromPackage;
1298 isResolver = sourceRecord.isResolverOrChildActivity();
1299 }
1300
1301 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001302 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001303 }
1304
1305 // TODO: Switch to user app stacks here.
1306 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001307 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001308 .setCallingUid(targetUid)
1309 .setCallingPackage(targetPackage)
1310 .setResolvedType(resolvedType)
1311 .setResultTo(resultTo)
1312 .setResultWho(resultWho)
1313 .setRequestCode(requestCode)
1314 .setStartFlags(startFlags)
1315 .setActivityOptions(bOptions)
1316 .setMayWait(userId)
1317 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1318 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1319 .execute();
1320 } catch (SecurityException e) {
1321 // XXX need to figure out how to propagate to original app.
1322 // A SecurityException here is generally actually a fault of the original
1323 // calling activity (such as a fairly granting permissions), so propagate it
1324 // back to them.
1325 /*
1326 StringBuilder msg = new StringBuilder();
1327 msg.append("While launching");
1328 msg.append(intent.toString());
1329 msg.append(": ");
1330 msg.append(e.getMessage());
1331 */
1332 throw e;
1333 }
1334 }
1335
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001336 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1337 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1338 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1339 }
1340
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 @Override
1342 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1343 Intent intent, String resolvedType, IVoiceInteractionSession session,
1344 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1345 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001346 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 if (session == null || interactor == null) {
1348 throw new NullPointerException("null session or interactor");
1349 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001350 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001352 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 .setCallingUid(callingUid)
1354 .setCallingPackage(callingPackage)
1355 .setResolvedType(resolvedType)
1356 .setVoiceSession(session)
1357 .setVoiceInteractor(interactor)
1358 .setStartFlags(startFlags)
1359 .setProfilerInfo(profilerInfo)
1360 .setActivityOptions(bOptions)
1361 .setMayWait(userId)
1362 .execute();
1363 }
1364
1365 @Override
1366 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1367 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001368 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1369 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001371 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 .setCallingUid(callingUid)
1373 .setCallingPackage(callingPackage)
1374 .setResolvedType(resolvedType)
1375 .setActivityOptions(bOptions)
1376 .setMayWait(userId)
1377 .execute();
1378 }
1379
1380 @Override
1381 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1382 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001383 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 final int callingPid = Binder.getCallingPid();
1385 final long origId = Binder.clearCallingIdentity();
1386 try {
1387 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001388 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1389 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390
1391 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001392 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1393 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1395 recentsUid, assistDataReceiver);
1396 }
1397 } finally {
1398 Binder.restoreCallingIdentity(origId);
1399 }
1400 }
1401
1402 @Override
1403 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001404 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 "startActivityFromRecents()");
1406
1407 final int callingPid = Binder.getCallingPid();
1408 final int callingUid = Binder.getCallingUid();
1409 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1410 final long origId = Binder.clearCallingIdentity();
1411 try {
1412 synchronized (mGlobalLock) {
1413 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1414 safeOptions);
1415 }
1416 } finally {
1417 Binder.restoreCallingIdentity(origId);
1418 }
1419 }
1420
1421 /**
1422 * This is the internal entry point for handling Activity.finish().
1423 *
1424 * @param token The Binder token referencing the Activity we want to finish.
1425 * @param resultCode Result code, if any, from this Activity.
1426 * @param resultData Result data (Intent), if any, from this Activity.
1427 * @param finishTask Whether to finish the task associated with this Activity.
1428 *
1429 * @return Returns true if the activity successfully finished, or false if it is still running.
1430 */
1431 @Override
1432 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1433 int finishTask) {
1434 // Refuse possible leaked file descriptors
1435 if (resultData != null && resultData.hasFileDescriptors()) {
1436 throw new IllegalArgumentException("File descriptors passed in Intent");
1437 }
1438
1439 synchronized (mGlobalLock) {
1440 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1441 if (r == null) {
1442 return true;
1443 }
1444 // Keep track of the root activity of the task before we finish it
1445 TaskRecord tr = r.getTask();
1446 ActivityRecord rootR = tr.getRootActivity();
1447 if (rootR == null) {
1448 Slog.w(TAG, "Finishing task with all activities already finished");
1449 }
1450 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1451 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001452 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 return false;
1454 }
1455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001456 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1457 // We should consolidate.
1458 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 // Find the first activity that is not finishing.
1460 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1461 if (next != null) {
1462 // ask watcher if this is allowed
1463 boolean resumeOK = true;
1464 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001467 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 Watchdog.getInstance().setActivityController(null);
1469 }
1470
1471 if (!resumeOK) {
1472 Slog.i(TAG, "Not finishing activity because controller resumed");
1473 return false;
1474 }
1475 }
1476 }
1477 final long origId = Binder.clearCallingIdentity();
1478 try {
1479 boolean res;
1480 final boolean finishWithRootActivity =
1481 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1482 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1483 || (finishWithRootActivity && r == rootR)) {
1484 // If requested, remove the task that is associated to this activity only if it
1485 // was the root activity in the task. The result code and data is ignored
1486 // because we don't support returning them across task boundaries. Also, to
1487 // keep backwards compatibility we remove the task from recents when finishing
1488 // task with root activity.
1489 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1490 finishWithRootActivity, "finish-activity");
1491 if (!res) {
1492 Slog.i(TAG, "Removing task failed to finish activity");
1493 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001494 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001495 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 } else {
1497 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1498 resultData, "app-request", true);
1499 if (!res) {
1500 Slog.i(TAG, "Failed to finish by app-request");
1501 }
1502 }
1503 return res;
1504 } finally {
1505 Binder.restoreCallingIdentity(origId);
1506 }
1507 }
1508 }
1509
1510 @Override
1511 public boolean finishActivityAffinity(IBinder token) {
1512 synchronized (mGlobalLock) {
1513 final long origId = Binder.clearCallingIdentity();
1514 try {
1515 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1516 if (r == null) {
1517 return false;
1518 }
1519
1520 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1521 // can finish.
1522 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001523 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001524 return false;
1525 }
1526 return task.getStack().finishActivityAffinityLocked(r);
1527 } finally {
1528 Binder.restoreCallingIdentity(origId);
1529 }
1530 }
1531 }
1532
1533 @Override
1534 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1535 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001536 try {
1537 WindowProcessController proc = null;
1538 synchronized (mGlobalLock) {
1539 ActivityStack stack = ActivityRecord.getStackLocked(token);
1540 if (stack == null) {
1541 return;
1542 }
1543 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1544 false /* fromTimeout */, false /* processPausingActivities */, config);
1545 if (r != null) {
1546 proc = r.app;
1547 }
1548 if (stopProfiling && proc != null) {
1549 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 }
1551 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001552 } finally {
1553 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 }
1556
1557 @Override
1558 public final void activityResumed(IBinder token) {
1559 final long origId = Binder.clearCallingIdentity();
1560 synchronized (mGlobalLock) {
1561 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001562 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 }
1564 Binder.restoreCallingIdentity(origId);
1565 }
1566
1567 @Override
1568 public final void activityPaused(IBinder token) {
1569 final long origId = Binder.clearCallingIdentity();
1570 synchronized (mGlobalLock) {
1571 ActivityStack stack = ActivityRecord.getStackLocked(token);
1572 if (stack != null) {
1573 stack.activityPausedLocked(token, false);
1574 }
1575 }
1576 Binder.restoreCallingIdentity(origId);
1577 }
1578
1579 @Override
1580 public final void activityStopped(IBinder token, Bundle icicle,
1581 PersistableBundle persistentState, CharSequence description) {
1582 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1583
1584 // Refuse possible leaked file descriptors
1585 if (icicle != null && icicle.hasFileDescriptors()) {
1586 throw new IllegalArgumentException("File descriptors passed in Bundle");
1587 }
1588
1589 final long origId = Binder.clearCallingIdentity();
1590
1591 synchronized (mGlobalLock) {
1592 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1593 if (r != null) {
1594 r.activityStoppedLocked(icicle, persistentState, description);
1595 }
1596 }
1597
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001598 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001599
1600 Binder.restoreCallingIdentity(origId);
1601 }
1602
1603 @Override
1604 public final void activityDestroyed(IBinder token) {
1605 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1606 synchronized (mGlobalLock) {
1607 ActivityStack stack = ActivityRecord.getStackLocked(token);
1608 if (stack != null) {
1609 stack.activityDestroyedLocked(token, "activityDestroyed");
1610 }
1611 }
1612 }
1613
1614 @Override
1615 public final void activityRelaunched(IBinder token) {
1616 final long origId = Binder.clearCallingIdentity();
1617 synchronized (mGlobalLock) {
1618 mStackSupervisor.activityRelaunchedLocked(token);
1619 }
1620 Binder.restoreCallingIdentity(origId);
1621 }
1622
1623 public final void activitySlept(IBinder token) {
1624 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1625
1626 final long origId = Binder.clearCallingIdentity();
1627
1628 synchronized (mGlobalLock) {
1629 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1630 if (r != null) {
1631 mStackSupervisor.activitySleptLocked(r);
1632 }
1633 }
1634
1635 Binder.restoreCallingIdentity(origId);
1636 }
1637
1638 @Override
1639 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1640 synchronized (mGlobalLock) {
1641 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1642 if (r == null) {
1643 return;
1644 }
1645 final long origId = Binder.clearCallingIdentity();
1646 try {
1647 r.setRequestedOrientation(requestedOrientation);
1648 } finally {
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public int getRequestedOrientation(IBinder token) {
1656 synchronized (mGlobalLock) {
1657 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1658 if (r == null) {
1659 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1660 }
1661 return r.getRequestedOrientation();
1662 }
1663 }
1664
1665 @Override
1666 public void setImmersive(IBinder token, boolean immersive) {
1667 synchronized (mGlobalLock) {
1668 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1669 if (r == null) {
1670 throw new IllegalArgumentException();
1671 }
1672 r.immersive = immersive;
1673
1674 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001675 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001677 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 }
1679 }
1680 }
1681
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001682 void applyUpdateLockStateLocked(ActivityRecord r) {
1683 // Modifications to the UpdateLock state are done on our handler, outside
1684 // the activity manager's locks. The new state is determined based on the
1685 // state *now* of the relevant activity record. The object is passed to
1686 // the handler solely for logging detail, not to be consulted/modified.
1687 final boolean nextState = r != null && r.immersive;
1688 mH.post(() -> {
1689 if (mUpdateLock.isHeld() != nextState) {
1690 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1691 "Applying new update lock state '" + nextState + "' for " + r);
1692 if (nextState) {
1693 mUpdateLock.acquire();
1694 } else {
1695 mUpdateLock.release();
1696 }
1697 }
1698 });
1699 }
1700
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 @Override
1702 public boolean isImmersive(IBinder token) {
1703 synchronized (mGlobalLock) {
1704 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1705 if (r == null) {
1706 throw new IllegalArgumentException();
1707 }
1708 return r.immersive;
1709 }
1710 }
1711
1712 @Override
1713 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001714 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001716 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 return (r != null) ? r.immersive : false;
1718 }
1719 }
1720
1721 @Override
1722 public void overridePendingTransition(IBinder token, String packageName,
1723 int enterAnim, int exitAnim) {
1724 synchronized (mGlobalLock) {
1725 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1726 if (self == null) {
1727 return;
1728 }
1729
1730 final long origId = Binder.clearCallingIdentity();
1731
1732 if (self.isState(
1733 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001734 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1735 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 }
1737
1738 Binder.restoreCallingIdentity(origId);
1739 }
1740 }
1741
1742 @Override
1743 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001744 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001746 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001747 if (r == null) {
1748 return ActivityManager.COMPAT_MODE_UNKNOWN;
1749 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001750 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001751 }
1752 }
1753
1754 @Override
1755 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001756 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001758 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001760 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001761 if (r == null) {
1762 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1763 return;
1764 }
1765 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001766 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001767 }
1768 }
1769
1770 @Override
1771 public int getLaunchedFromUid(IBinder activityToken) {
1772 ActivityRecord srec;
1773 synchronized (mGlobalLock) {
1774 srec = ActivityRecord.forTokenLocked(activityToken);
1775 }
1776 if (srec == null) {
1777 return -1;
1778 }
1779 return srec.launchedFromUid;
1780 }
1781
1782 @Override
1783 public String getLaunchedFromPackage(IBinder activityToken) {
1784 ActivityRecord srec;
1785 synchronized (mGlobalLock) {
1786 srec = ActivityRecord.forTokenLocked(activityToken);
1787 }
1788 if (srec == null) {
1789 return null;
1790 }
1791 return srec.launchedFromPackage;
1792 }
1793
1794 @Override
1795 public boolean convertFromTranslucent(IBinder token) {
1796 final long origId = Binder.clearCallingIdentity();
1797 try {
1798 synchronized (mGlobalLock) {
1799 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1800 if (r == null) {
1801 return false;
1802 }
1803 final boolean translucentChanged = r.changeWindowTranslucency(true);
1804 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001805 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001807 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 return translucentChanged;
1809 }
1810 } finally {
1811 Binder.restoreCallingIdentity(origId);
1812 }
1813 }
1814
1815 @Override
1816 public boolean convertToTranslucent(IBinder token, Bundle options) {
1817 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1818 final long origId = Binder.clearCallingIdentity();
1819 try {
1820 synchronized (mGlobalLock) {
1821 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 if (r == null) {
1823 return false;
1824 }
1825 final TaskRecord task = r.getTask();
1826 int index = task.mActivities.lastIndexOf(r);
1827 if (index > 0) {
1828 ActivityRecord under = task.mActivities.get(index - 1);
1829 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1830 }
1831 final boolean translucentChanged = r.changeWindowTranslucency(false);
1832 if (translucentChanged) {
1833 r.getStack().convertActivityToTranslucent(r);
1834 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001835 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837 return translucentChanged;
1838 }
1839 } finally {
1840 Binder.restoreCallingIdentity(origId);
1841 }
1842 }
1843
1844 @Override
1845 public void notifyActivityDrawn(IBinder token) {
1846 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1847 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001848 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 if (r != null) {
1850 r.getStack().notifyActivityDrawnLocked(r);
1851 }
1852 }
1853 }
1854
1855 @Override
1856 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1857 synchronized (mGlobalLock) {
1858 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 return;
1861 }
1862 r.reportFullyDrawnLocked(restoredFromBundle);
1863 }
1864 }
1865
1866 @Override
1867 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1868 synchronized (mGlobalLock) {
1869 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1870 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1871 return stack.mDisplayId;
1872 }
1873 return DEFAULT_DISPLAY;
1874 }
1875 }
1876
1877 @Override
1878 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001879 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 long ident = Binder.clearCallingIdentity();
1881 try {
1882 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001883 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001885 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 }
1887 return null;
1888 }
1889 } finally {
1890 Binder.restoreCallingIdentity(ident);
1891 }
1892 }
1893
1894 @Override
1895 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001896 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001897 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1898 final long callingId = Binder.clearCallingIdentity();
1899 try {
1900 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001901 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 if (stack == null) {
1903 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1904 return;
1905 }
1906 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001907 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001908 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 }
1910 }
1911 } finally {
1912 Binder.restoreCallingIdentity(callingId);
1913 }
1914 }
1915
1916 @Override
1917 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1920 final long callingId = Binder.clearCallingIdentity();
1921 try {
1922 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001923 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001924 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 if (task == null) {
1926 return;
1927 }
1928 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001929 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001930 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001931 }
1932 }
1933 } finally {
1934 Binder.restoreCallingIdentity(callingId);
1935 }
1936 }
1937
1938 @Override
1939 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001940 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 synchronized (mGlobalLock) {
1942 final long ident = Binder.clearCallingIdentity();
1943 try {
1944 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1945 "remove-task");
1946 } finally {
1947 Binder.restoreCallingIdentity(ident);
1948 }
1949 }
1950 }
1951
1952 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001953 public void removeAllVisibleRecentTasks() {
1954 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1955 synchronized (mGlobalLock) {
1956 final long ident = Binder.clearCallingIdentity();
1957 try {
1958 getRecentTasks().removeAllVisibleTasks();
1959 } finally {
1960 Binder.restoreCallingIdentity(ident);
1961 }
1962 }
1963 }
1964
1965 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1967 synchronized (mGlobalLock) {
1968 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1969 if (srec != null) {
1970 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1971 }
1972 }
1973 return false;
1974 }
1975
1976 @Override
1977 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1978 Intent resultData) {
1979
1980 synchronized (mGlobalLock) {
1981 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1982 if (r != null) {
1983 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1984 }
1985 return false;
1986 }
1987 }
1988
1989 /**
1990 * Attempts to move a task backwards in z-order (the order of activities within the task is
1991 * unchanged).
1992 *
1993 * There are several possible results of this call:
1994 * - if the task is locked, then we will show the lock toast
1995 * - if there is a task behind the provided task, then that task is made visible and resumed as
1996 * this task is moved to the back
1997 * - otherwise, if there are no other tasks in the stack:
1998 * - if this task is in the pinned stack, then we remove the stack completely, which will
1999 * have the effect of moving the task to the top or bottom of the fullscreen stack
2000 * (depending on whether it is visible)
2001 * - otherwise, we simply return home and hide this task
2002 *
2003 * @param token A reference to the activity we wish to move
2004 * @param nonRoot If false then this only works if the activity is the root
2005 * of a task; if true it will work for any activity in a task.
2006 * @return Returns true if the move completed, false if not.
2007 */
2008 @Override
2009 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002010 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 synchronized (mGlobalLock) {
2012 final long origId = Binder.clearCallingIdentity();
2013 try {
2014 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002015 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 if (task != null) {
2017 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2018 }
2019 } finally {
2020 Binder.restoreCallingIdentity(origId);
2021 }
2022 }
2023 return false;
2024 }
2025
2026 @Override
2027 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002028 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 long ident = Binder.clearCallingIdentity();
2030 Rect rect = new Rect();
2031 try {
2032 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002033 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2035 if (task == null) {
2036 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2037 return rect;
2038 }
2039 if (task.getStack() != null) {
2040 // Return the bounds from window manager since it will be adjusted for various
2041 // things like the presense of a docked stack for tasks that aren't resizeable.
2042 task.getWindowContainerBounds(rect);
2043 } else {
2044 // Task isn't in window manager yet since it isn't associated with a stack.
2045 // Return the persist value from activity manager
2046 if (!task.matchParentBounds()) {
2047 rect.set(task.getBounds());
2048 } else if (task.mLastNonFullscreenBounds != null) {
2049 rect.set(task.mLastNonFullscreenBounds);
2050 }
2051 }
2052 }
2053 } finally {
2054 Binder.restoreCallingIdentity(ident);
2055 }
2056 return rect;
2057 }
2058
2059 @Override
2060 public ActivityManager.TaskDescription getTaskDescription(int id) {
2061 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002062 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002064 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002065 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2066 if (tr != null) {
2067 return tr.lastTaskDescription;
2068 }
2069 }
2070 return null;
2071 }
2072
2073 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002074 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2075 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2076 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2077 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2078 return;
2079 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002080 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002081 synchronized (mGlobalLock) {
2082 final long ident = Binder.clearCallingIdentity();
2083 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002084 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002085 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002086 if (task == null) {
2087 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2088 return;
2089 }
2090
2091 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2092 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2093
2094 if (!task.isActivityTypeStandardOrUndefined()) {
2095 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2096 + " non-standard task " + taskId + " to windowing mode="
2097 + windowingMode);
2098 }
2099
2100 final ActivityStack stack = task.getStack();
2101 if (toTop) {
2102 stack.moveToFront("setTaskWindowingMode", task);
2103 }
2104 stack.setWindowingMode(windowingMode);
2105 } finally {
2106 Binder.restoreCallingIdentity(ident);
2107 }
2108 }
2109 }
2110
2111 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002113 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002114 ActivityRecord r = getCallingRecordLocked(token);
2115 return r != null ? r.info.packageName : null;
2116 }
2117 }
2118
2119 @Override
2120 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002121 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 ActivityRecord r = getCallingRecordLocked(token);
2123 return r != null ? r.intent.getComponent() : null;
2124 }
2125 }
2126
2127 private ActivityRecord getCallingRecordLocked(IBinder token) {
2128 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2129 if (r == null) {
2130 return null;
2131 }
2132 return r.resultTo;
2133 }
2134
2135 @Override
2136 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002137 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138
2139 synchronized (mGlobalLock) {
2140 final long origId = Binder.clearCallingIdentity();
2141 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002142 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002143 } finally {
2144 Binder.restoreCallingIdentity(origId);
2145 }
2146 }
2147 }
2148
2149 /**
2150 * TODO: Add mController hook
2151 */
2152 @Override
2153 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002154 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155
2156 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2157 synchronized (mGlobalLock) {
2158 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2159 false /* fromRecents */);
2160 }
2161 }
2162
2163 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2164 boolean fromRecents) {
2165
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002166 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 Binder.getCallingUid(), -1, -1, "Task to front")) {
2168 SafeActivityOptions.abort(options);
2169 return;
2170 }
2171 final long origId = Binder.clearCallingIdentity();
2172 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002173 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 if (task == null) {
2175 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002176 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 return;
2178 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002179 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002181 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 return;
2183 }
2184 ActivityOptions realOptions = options != null
2185 ? options.getOptions(mStackSupervisor)
2186 : null;
2187 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2188 false /* forceNonResizable */);
2189
2190 final ActivityRecord topActivity = task.getTopActivity();
2191 if (topActivity != null) {
2192
2193 // We are reshowing a task, use a starting window to hide the initial draw delay
2194 // so the transition can start earlier.
2195 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2196 true /* taskSwitch */, fromRecents);
2197 }
2198 } finally {
2199 Binder.restoreCallingIdentity(origId);
2200 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 }
2202
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002203 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2204 int callingPid, int callingUid, String name) {
2205 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2206 return true;
2207 }
2208
2209 if (getRecentTasks().isCallerRecents(sourceUid)) {
2210 return true;
2211 }
2212
2213 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2214 if (perm == PackageManager.PERMISSION_GRANTED) {
2215 return true;
2216 }
2217 if (checkAllowAppSwitchUid(sourceUid)) {
2218 return true;
2219 }
2220
2221 // If the actual IPC caller is different from the logical source, then
2222 // also see if they are allowed to control app switches.
2223 if (callingUid != -1 && callingUid != sourceUid) {
2224 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2225 if (perm == PackageManager.PERMISSION_GRANTED) {
2226 return true;
2227 }
2228 if (checkAllowAppSwitchUid(callingUid)) {
2229 return true;
2230 }
2231 }
2232
2233 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2234 return false;
2235 }
2236
2237 private boolean checkAllowAppSwitchUid(int uid) {
2238 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2239 if (types != null) {
2240 for (int i = types.size() - 1; i >= 0; i--) {
2241 if (types.valueAt(i).intValue() == uid) {
2242 return true;
2243 }
2244 }
2245 }
2246 return false;
2247 }
2248
2249 @Override
2250 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2251 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2252 "setActivityController()");
2253 synchronized (mGlobalLock) {
2254 mController = controller;
2255 mControllerIsAMonkey = imAMonkey;
2256 Watchdog.getInstance().setActivityController(controller);
2257 }
2258 }
2259
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002260 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002261 synchronized (mGlobalLock) {
2262 return mController != null && mControllerIsAMonkey;
2263 }
2264 }
2265
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002266 @Override
2267 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2268 synchronized (mGlobalLock) {
2269 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2270 }
2271 }
2272
2273 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002274 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2275 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2276 }
2277
2278 @Override
2279 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2280 @WindowConfiguration.ActivityType int ignoreActivityType,
2281 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2282 final int callingUid = Binder.getCallingUid();
2283 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2284
2285 synchronized (mGlobalLock) {
2286 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2287
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002288 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002289 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002290 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002291 ignoreWindowingMode, callingUid, allowed);
2292 }
2293
2294 return list;
2295 }
2296
2297 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2299 synchronized (mGlobalLock) {
2300 final long origId = Binder.clearCallingIdentity();
2301 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2302 if (r != null) {
2303 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2304 }
2305 Binder.restoreCallingIdentity(origId);
2306 }
2307 }
2308
2309 @Override
2310 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002311 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 ActivityStack stack = ActivityRecord.getStackLocked(token);
2313 if (stack != null) {
2314 return stack.willActivityBeVisibleLocked(token);
2315 }
2316 return false;
2317 }
2318 }
2319
2320 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002321 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002322 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002323 synchronized (mGlobalLock) {
2324 final long ident = Binder.clearCallingIdentity();
2325 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002326 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002327 if (task == null) {
2328 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2329 return;
2330 }
2331
2332 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2333 + " to stackId=" + stackId + " toTop=" + toTop);
2334
Wale Ogunwaled32da472018-11-16 07:19:28 -08002335 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002336 if (stack == null) {
2337 throw new IllegalStateException(
2338 "moveTaskToStack: No stack for stackId=" + stackId);
2339 }
2340 if (!stack.isActivityTypeStandardOrUndefined()) {
2341 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2342 + taskId + " to stack " + stackId);
2343 }
2344 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002345 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002346 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2347 }
2348 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2349 "moveTaskToStack");
2350 } finally {
2351 Binder.restoreCallingIdentity(ident);
2352 }
2353 }
2354 }
2355
2356 @Override
2357 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2358 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002359 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002360
2361 final long ident = Binder.clearCallingIdentity();
2362 try {
2363 synchronized (mGlobalLock) {
2364 if (animate) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002365 final PinnedActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002366 if (stack == null) {
2367 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2368 return;
2369 }
2370 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2371 throw new IllegalArgumentException("Stack: " + stackId
2372 + " doesn't support animated resize.");
2373 }
2374 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2375 animationDuration, false /* fromFullscreen */);
2376 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002377 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002378 if (stack == null) {
2379 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2380 return;
2381 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002382 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002383 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2384 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2385 }
2386 }
2387 } finally {
2388 Binder.restoreCallingIdentity(ident);
2389 }
2390 }
2391
2392 /**
2393 * Moves the specified task to the primary-split-screen stack.
2394 *
2395 * @param taskId Id of task to move.
2396 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2397 * exist already. See
2398 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2399 * and
2400 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2401 * @param toTop If the task and stack should be moved to the top.
2402 * @param animate Whether we should play an animation for the moving the task.
2403 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2404 * stack. Pass {@code null} to use default bounds.
2405 * @param showRecents If the recents activity should be shown on the other side of the task
2406 * going into split-screen mode.
2407 */
2408 @Override
2409 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2410 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002411 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002412 "setTaskWindowingModeSplitScreenPrimary()");
2413 synchronized (mGlobalLock) {
2414 final long ident = Binder.clearCallingIdentity();
2415 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002416 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002417 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002418 if (task == null) {
2419 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2420 return false;
2421 }
2422 if (DEBUG_STACK) Slog.d(TAG_STACK,
2423 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2424 + " to createMode=" + createMode + " toTop=" + toTop);
2425 if (!task.isActivityTypeStandardOrUndefined()) {
2426 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2427 + " non-standard task " + taskId + " to split-screen windowing mode");
2428 }
2429
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002430 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002431 final int windowingMode = task.getWindowingMode();
2432 final ActivityStack stack = task.getStack();
2433 if (toTop) {
2434 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2435 }
2436 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002437 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2438 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439 return windowingMode != task.getWindowingMode();
2440 } finally {
2441 Binder.restoreCallingIdentity(ident);
2442 }
2443 }
2444 }
2445
2446 /**
2447 * Removes stacks in the input windowing modes from the system if they are of activity type
2448 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2449 */
2450 @Override
2451 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002452 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002453 "removeStacksInWindowingModes()");
2454
2455 synchronized (mGlobalLock) {
2456 final long ident = Binder.clearCallingIdentity();
2457 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002458 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002459 } finally {
2460 Binder.restoreCallingIdentity(ident);
2461 }
2462 }
2463 }
2464
2465 @Override
2466 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002468 "removeStacksWithActivityTypes()");
2469
2470 synchronized (mGlobalLock) {
2471 final long ident = Binder.clearCallingIdentity();
2472 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002473 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002474 } finally {
2475 Binder.restoreCallingIdentity(ident);
2476 }
2477 }
2478 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002479
2480 @Override
2481 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2482 int userId) {
2483 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002484 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2485 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002487 final boolean detailed = checkGetTasksPermission(
2488 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2489 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002490 == PackageManager.PERMISSION_GRANTED;
2491
2492 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002493 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002494 callingUid);
2495 }
2496 }
2497
2498 @Override
2499 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002500 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002501 long ident = Binder.clearCallingIdentity();
2502 try {
2503 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002504 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002505 }
2506 } finally {
2507 Binder.restoreCallingIdentity(ident);
2508 }
2509 }
2510
2511 @Override
2512 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002514 long ident = Binder.clearCallingIdentity();
2515 try {
2516 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002517 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 }
2519 } finally {
2520 Binder.restoreCallingIdentity(ident);
2521 }
2522 }
2523
2524 @Override
2525 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002526 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002527 final long callingUid = Binder.getCallingUid();
2528 final long origId = Binder.clearCallingIdentity();
2529 try {
2530 synchronized (mGlobalLock) {
2531 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002532 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002533 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2534 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2535 }
2536 } finally {
2537 Binder.restoreCallingIdentity(origId);
2538 }
2539 }
2540
2541 @Override
2542 public void startLockTaskModeByToken(IBinder token) {
2543 synchronized (mGlobalLock) {
2544 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2545 if (r == null) {
2546 return;
2547 }
2548 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2549 }
2550 }
2551
2552 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002553 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002554 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002555 // This makes inner call to look as if it was initiated by system.
2556 long ident = Binder.clearCallingIdentity();
2557 try {
2558 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002559 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002560 MATCH_TASK_IN_STACKS_ONLY);
2561 if (task == null) {
2562 return;
2563 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002564
2565 // When starting lock task mode the stack must be in front and focused
2566 task.getStack().moveToFront("startSystemLockTaskMode");
2567 startLockTaskModeLocked(task, true /* isSystemCaller */);
2568 }
2569 } finally {
2570 Binder.restoreCallingIdentity(ident);
2571 }
2572 }
2573
2574 @Override
2575 public void stopLockTaskModeByToken(IBinder token) {
2576 synchronized (mGlobalLock) {
2577 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2578 if (r == null) {
2579 return;
2580 }
2581 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2582 }
2583 }
2584
2585 /**
2586 * This API should be called by SystemUI only when user perform certain action to dismiss
2587 * lock task mode. We should only dismiss pinned lock task mode in this case.
2588 */
2589 @Override
2590 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002591 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002592 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2593 }
2594
2595 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2596 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2597 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2598 return;
2599 }
2600
Wale Ogunwaled32da472018-11-16 07:19:28 -08002601 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002602 if (stack == null || task != stack.topTask()) {
2603 throw new IllegalArgumentException("Invalid task, not in foreground");
2604 }
2605
2606 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2607 // system or a specific app.
2608 // * System-initiated requests will only start the pinned mode (screen pinning)
2609 // * App-initiated requests
2610 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2611 // - will start the pinned mode, otherwise
2612 final int callingUid = Binder.getCallingUid();
2613 long ident = Binder.clearCallingIdentity();
2614 try {
2615 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002616 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002617
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002618 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002619 } finally {
2620 Binder.restoreCallingIdentity(ident);
2621 }
2622 }
2623
2624 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2625 final int callingUid = Binder.getCallingUid();
2626 long ident = Binder.clearCallingIdentity();
2627 try {
2628 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002629 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002630 }
2631 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2632 // task and jumping straight into a call in the case of emergency call back.
2633 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2634 if (tm != null) {
2635 tm.showInCallScreen(false);
2636 }
2637 } finally {
2638 Binder.restoreCallingIdentity(ident);
2639 }
2640 }
2641
2642 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002643 public void updateLockTaskPackages(int userId, String[] packages) {
2644 final int callingUid = Binder.getCallingUid();
2645 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2646 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2647 "updateLockTaskPackages()");
2648 }
2649 synchronized (this) {
2650 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2651 + Arrays.toString(packages));
2652 getLockTaskController().updateLockTaskPackages(userId, packages);
2653 }
2654 }
2655
2656 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002657 public boolean isInLockTaskMode() {
2658 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2659 }
2660
2661 @Override
2662 public int getLockTaskModeState() {
2663 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002664 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 }
2666 }
2667
2668 @Override
2669 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2670 synchronized (mGlobalLock) {
2671 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2672 if (r != null) {
2673 r.setTaskDescription(td);
2674 final TaskRecord task = r.getTask();
2675 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002676 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002677 }
2678 }
2679 }
2680
2681 @Override
2682 public Bundle getActivityOptions(IBinder token) {
2683 final long origId = Binder.clearCallingIdentity();
2684 try {
2685 synchronized (mGlobalLock) {
2686 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2687 if (r != null) {
2688 final ActivityOptions activityOptions = r.takeOptionsLocked();
2689 return activityOptions == null ? null : activityOptions.toBundle();
2690 }
2691 return null;
2692 }
2693 } finally {
2694 Binder.restoreCallingIdentity(origId);
2695 }
2696 }
2697
2698 @Override
2699 public List<IBinder> getAppTasks(String callingPackage) {
2700 int callingUid = Binder.getCallingUid();
2701 long ident = Binder.clearCallingIdentity();
2702 try {
2703 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002704 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002705 }
2706 } finally {
2707 Binder.restoreCallingIdentity(ident);
2708 }
2709 }
2710
2711 @Override
2712 public void finishVoiceTask(IVoiceInteractionSession session) {
2713 synchronized (mGlobalLock) {
2714 final long origId = Binder.clearCallingIdentity();
2715 try {
2716 // TODO: VI Consider treating local voice interactions and voice tasks
2717 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002718 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002719 } finally {
2720 Binder.restoreCallingIdentity(origId);
2721 }
2722 }
2723
2724 }
2725
2726 @Override
2727 public boolean isTopOfTask(IBinder token) {
2728 synchronized (mGlobalLock) {
2729 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002730 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002731 }
2732 }
2733
2734 @Override
2735 public void notifyLaunchTaskBehindComplete(IBinder token) {
2736 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2737 }
2738
2739 @Override
2740 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002741 mH.post(() -> {
2742 synchronized (mGlobalLock) {
2743 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002744 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002745 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002746 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002747 } catch (RemoteException e) {
2748 }
2749 }
2750 }
2751
2752 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002753 }
2754
2755 /** Called from an app when assist data is ready. */
2756 @Override
2757 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2758 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760 synchronized (pae) {
2761 pae.result = extras;
2762 pae.structure = structure;
2763 pae.content = content;
2764 if (referrer != null) {
2765 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2766 }
2767 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002768 // Pre-fill the task/activity component for all assist data receivers
2769 structure.setTaskId(pae.activity.getTask().taskId);
2770 structure.setActivityComponent(pae.activity.realActivity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 structure.setHomeActivity(pae.isHome);
2772 }
2773 pae.haveResult = true;
2774 pae.notifyAll();
2775 if (pae.intent == null && pae.receiver == null) {
2776 // Caller is just waiting for the result.
2777 return;
2778 }
2779 }
2780 // We are now ready to launch the assist activity.
2781 IAssistDataReceiver sendReceiver = null;
2782 Bundle sendBundle = null;
2783 synchronized (mGlobalLock) {
2784 buildAssistBundleLocked(pae, extras);
2785 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002786 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 if (!exists) {
2788 // Timed out.
2789 return;
2790 }
2791
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 // Caller wants result sent back to them.
2794 sendBundle = new Bundle();
2795 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2796 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2797 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2798 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2799 }
2800 }
2801 if (sendReceiver != null) {
2802 try {
2803 sendReceiver.onHandleAssistData(sendBundle);
2804 } catch (RemoteException e) {
2805 }
2806 return;
2807 }
2808
2809 final long ident = Binder.clearCallingIdentity();
2810 try {
2811 if (TextUtils.equals(pae.intent.getAction(),
2812 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2813 pae.intent.putExtras(pae.extras);
2814 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2815 } else {
2816 pae.intent.replaceExtras(pae.extras);
2817 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2818 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2819 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002820 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821
2822 try {
2823 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2824 } catch (ActivityNotFoundException e) {
2825 Slog.w(TAG, "No activity to handle assist action.", e);
2826 }
2827 }
2828 } finally {
2829 Binder.restoreCallingIdentity(ident);
2830 }
2831 }
2832
2833 @Override
2834 public int addAppTask(IBinder activityToken, Intent intent,
2835 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2836 final int callingUid = Binder.getCallingUid();
2837 final long callingIdent = Binder.clearCallingIdentity();
2838
2839 try {
2840 synchronized (mGlobalLock) {
2841 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2842 if (r == null) {
2843 throw new IllegalArgumentException("Activity does not exist; token="
2844 + activityToken);
2845 }
2846 ComponentName comp = intent.getComponent();
2847 if (comp == null) {
2848 throw new IllegalArgumentException("Intent " + intent
2849 + " must specify explicit component");
2850 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002851 if (thumbnail.getWidth() != mThumbnailWidth
2852 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 throw new IllegalArgumentException("Bad thumbnail size: got "
2854 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002855 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 }
2857 if (intent.getSelector() != null) {
2858 intent.setSelector(null);
2859 }
2860 if (intent.getSourceBounds() != null) {
2861 intent.setSourceBounds(null);
2862 }
2863 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2864 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2865 // The caller has added this as an auto-remove task... that makes no
2866 // sense, so turn off auto-remove.
2867 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2868 }
2869 }
2870 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2871 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2872 if (ainfo.applicationInfo.uid != callingUid) {
2873 throw new SecurityException(
2874 "Can't add task for another application: target uid="
2875 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2876 }
2877
2878 final ActivityStack stack = r.getStack();
2879 final TaskRecord task = stack.createTaskRecord(
2880 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2881 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002882 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 // The app has too many tasks already and we can't add any more
2884 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2885 return INVALID_TASK_ID;
2886 }
2887 task.lastTaskDescription.copyFrom(description);
2888
2889 // TODO: Send the thumbnail to WM to store it.
2890
2891 return task.taskId;
2892 }
2893 } finally {
2894 Binder.restoreCallingIdentity(callingIdent);
2895 }
2896 }
2897
2898 @Override
2899 public Point getAppTaskThumbnailSize() {
2900 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002901 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903 }
2904
2905 @Override
2906 public void setTaskResizeable(int taskId, int resizeableMode) {
2907 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002908 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2910 if (task == null) {
2911 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2912 return;
2913 }
2914 task.setResizeMode(resizeableMode);
2915 }
2916 }
2917
2918 @Override
2919 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002920 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 long ident = Binder.clearCallingIdentity();
2922 try {
2923 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002924 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002925 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 if (task == null) {
2927 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2928 return;
2929 }
2930 // Place the task in the right stack if it isn't there already based on
2931 // the requested bounds.
2932 // The stack transition logic is:
2933 // - a null bounds on a freeform task moves that task to fullscreen
2934 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2935 // that task to freeform
2936 // - otherwise the task is not moved
2937 ActivityStack stack = task.getStack();
2938 if (!task.getWindowConfiguration().canResizeTask()) {
2939 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2940 }
2941 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2942 stack = stack.getDisplay().getOrCreateStack(
2943 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2944 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2945 stack = stack.getDisplay().getOrCreateStack(
2946 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2947 }
2948
2949 // Reparent the task to the right stack if necessary
2950 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2951 if (stack != task.getStack()) {
2952 // Defer resume until the task is resized below
2953 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2954 DEFER_RESUME, "resizeTask");
2955 preserveWindow = false;
2956 }
2957
2958 // After reparenting (which only resizes the task to the stack bounds), resize the
2959 // task to the actual bounds provided
2960 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2961 }
2962 } finally {
2963 Binder.restoreCallingIdentity(ident);
2964 }
2965 }
2966
2967 @Override
2968 public boolean releaseActivityInstance(IBinder token) {
2969 synchronized (mGlobalLock) {
2970 final long origId = Binder.clearCallingIdentity();
2971 try {
2972 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2973 if (r == null) {
2974 return false;
2975 }
2976 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2977 } finally {
2978 Binder.restoreCallingIdentity(origId);
2979 }
2980 }
2981 }
2982
2983 @Override
2984 public void releaseSomeActivities(IApplicationThread appInt) {
2985 synchronized (mGlobalLock) {
2986 final long origId = Binder.clearCallingIdentity();
2987 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002988 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002989 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 } finally {
2991 Binder.restoreCallingIdentity(origId);
2992 }
2993 }
2994 }
2995
2996 @Override
2997 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002998 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002999 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 != PackageManager.PERMISSION_GRANTED) {
3001 throw new SecurityException("Requires permission "
3002 + android.Manifest.permission.DEVICE_POWER);
3003 }
3004
3005 synchronized (mGlobalLock) {
3006 long ident = Binder.clearCallingIdentity();
3007 if (mKeyguardShown != keyguardShowing) {
3008 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003009 final Message msg = PooledLambda.obtainMessage(
3010 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3011 keyguardShowing);
3012 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 }
3014 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003015 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003016 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003017 } finally {
3018 Binder.restoreCallingIdentity(ident);
3019 }
3020 }
3021
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003022 mH.post(() -> {
3023 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3024 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3025 }
3026 });
3027 }
3028
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003029 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003030 mH.post(() -> {
3031 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3032 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3033 }
3034 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 }
3036
3037 @Override
3038 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003039 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3040 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041
3042 final File passedIconFile = new File(filePath);
3043 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3044 passedIconFile.getName());
3045 if (!legitIconFile.getPath().equals(filePath)
3046 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3047 throw new IllegalArgumentException("Bad file path: " + filePath
3048 + " passed for userId " + userId);
3049 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003050 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 }
3052
3053 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003054 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3056 final ActivityOptions activityOptions = safeOptions != null
3057 ? safeOptions.getOptions(mStackSupervisor)
3058 : null;
3059 if (activityOptions == null
3060 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3061 || activityOptions.getCustomInPlaceResId() == 0) {
3062 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3063 "with valid animation");
3064 }
lumark588a3e82018-07-20 18:53:54 +08003065 // Get top display of front most application.
3066 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3067 if (focusedStack != null) {
3068 final DisplayWindowController dwc =
3069 focusedStack.getDisplay().getWindowContainerController();
3070 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3071 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3072 activityOptions.getCustomInPlaceResId());
3073 dwc.executeAppTransition();
3074 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 }
3076
3077 @Override
3078 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003079 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 synchronized (mGlobalLock) {
3081 final long ident = Binder.clearCallingIdentity();
3082 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003083 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003084 if (stack == null) {
3085 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3086 return;
3087 }
3088 if (!stack.isActivityTypeStandardOrUndefined()) {
3089 throw new IllegalArgumentException(
3090 "Removing non-standard stack is not allowed.");
3091 }
3092 mStackSupervisor.removeStack(stack);
3093 } finally {
3094 Binder.restoreCallingIdentity(ident);
3095 }
3096 }
3097 }
3098
3099 @Override
3100 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003101 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102
3103 synchronized (mGlobalLock) {
3104 final long ident = Binder.clearCallingIdentity();
3105 try {
3106 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3107 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003108 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109 } finally {
3110 Binder.restoreCallingIdentity(ident);
3111 }
3112 }
3113 }
3114
3115 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 public void exitFreeformMode(IBinder token) {
3117 synchronized (mGlobalLock) {
3118 long ident = Binder.clearCallingIdentity();
3119 try {
3120 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3121 if (r == null) {
3122 throw new IllegalArgumentException(
3123 "exitFreeformMode: No activity record matching token=" + token);
3124 }
3125
3126 final ActivityStack stack = r.getStack();
3127 if (stack == null || !stack.inFreeformWindowingMode()) {
3128 throw new IllegalStateException(
3129 "exitFreeformMode: You can only go fullscreen from freeform.");
3130 }
3131
3132 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3133 } finally {
3134 Binder.restoreCallingIdentity(ident);
3135 }
3136 }
3137 }
3138
3139 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3140 @Override
3141 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003142 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003144 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 }
3146
3147 /** Unregister a task stack listener so that it stops receiving callbacks. */
3148 @Override
3149 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003150 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003152 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 }
3154
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003155 @Override
3156 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3157 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3158 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3159 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3160 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3161 }
3162
3163 @Override
3164 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3165 IBinder activityToken, int flags) {
3166 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3167 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3168 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3169 }
3170
3171 @Override
3172 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3173 Bundle args) {
3174 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3175 true /* focused */, true /* newSessionId */, userHandle, args,
3176 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3177 }
3178
3179 @Override
3180 public Bundle getAssistContextExtras(int requestType) {
3181 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3182 null, null, true /* focused */, true /* newSessionId */,
3183 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3184 if (pae == null) {
3185 return null;
3186 }
3187 synchronized (pae) {
3188 while (!pae.haveResult) {
3189 try {
3190 pae.wait();
3191 } catch (InterruptedException e) {
3192 }
3193 }
3194 }
3195 synchronized (mGlobalLock) {
3196 buildAssistBundleLocked(pae, pae.result);
3197 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003198 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003199 }
3200 return pae.extras;
3201 }
3202
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003203 /**
3204 * Binder IPC calls go through the public entry point.
3205 * This can be called with or without the global lock held.
3206 */
3207 private static int checkCallingPermission(String permission) {
3208 return checkPermission(
3209 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3210 }
3211
3212 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003213 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003214 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3215 mAmInternal.enforceCallingPermission(permission, func);
3216 }
3217 }
3218
3219 @VisibleForTesting
3220 int checkGetTasksPermission(String permission, int pid, int uid) {
3221 return checkPermission(permission, pid, uid);
3222 }
3223
3224 static int checkPermission(String permission, int pid, int uid) {
3225 if (permission == null) {
3226 return PackageManager.PERMISSION_DENIED;
3227 }
3228 return checkComponentPermission(permission, pid, uid, -1, true);
3229 }
3230
Wale Ogunwale214f3482018-10-04 11:00:47 -07003231 public static int checkComponentPermission(String permission, int pid, int uid,
3232 int owningUid, boolean exported) {
3233 return ActivityManagerService.checkComponentPermission(
3234 permission, pid, uid, owningUid, exported);
3235 }
3236
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003237 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3238 if (getRecentTasks().isCallerRecents(callingUid)) {
3239 // Always allow the recents component to get tasks
3240 return true;
3241 }
3242
3243 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3244 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3245 if (!allowed) {
3246 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3247 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3248 // Temporary compatibility: some existing apps on the system image may
3249 // still be requesting the old permission and not switched to the new
3250 // one; if so, we'll still allow them full access. This means we need
3251 // to see if they are holding the old permission and are a system app.
3252 try {
3253 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3254 allowed = true;
3255 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3256 + " is using old GET_TASKS but privileged; allowing");
3257 }
3258 } catch (RemoteException e) {
3259 }
3260 }
3261 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3262 + " does not hold REAL_GET_TASKS; limiting output");
3263 }
3264 return allowed;
3265 }
3266
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3268 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3269 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3270 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003271 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003272 "enqueueAssistContext()");
3273
3274 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003275 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 if (activity == null) {
3277 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3278 return null;
3279 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003280 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3282 return null;
3283 }
3284 if (focused) {
3285 if (activityToken != null) {
3286 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3287 if (activity != caller) {
3288 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3289 + " is not current top " + activity);
3290 return null;
3291 }
3292 }
3293 } else {
3294 activity = ActivityRecord.forTokenLocked(activityToken);
3295 if (activity == null) {
3296 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3297 + " couldn't be found");
3298 return null;
3299 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003300 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003301 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3302 return null;
3303 }
3304 }
3305
3306 PendingAssistExtras pae;
3307 Bundle extras = new Bundle();
3308 if (args != null) {
3309 extras.putAll(args);
3310 }
3311 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003312 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313
3314 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3315 userHandle);
3316 pae.isHome = activity.isActivityTypeHome();
3317
3318 // Increment the sessionId if necessary
3319 if (newSessionId) {
3320 mViSessionId++;
3321 }
3322 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003323 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3324 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003326 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 } catch (RemoteException e) {
3328 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3329 return null;
3330 }
3331 return pae;
3332 }
3333 }
3334
3335 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3336 if (result != null) {
3337 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3338 }
3339 if (pae.hint != null) {
3340 pae.extras.putBoolean(pae.hint, true);
3341 }
3342 }
3343
3344 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3345 IAssistDataReceiver receiver;
3346 synchronized (mGlobalLock) {
3347 mPendingAssistExtras.remove(pae);
3348 receiver = pae.receiver;
3349 }
3350 if (receiver != null) {
3351 // Caller wants result sent back to them.
3352 Bundle sendBundle = new Bundle();
3353 // At least return the receiver extras
3354 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3355 try {
3356 pae.receiver.onHandleAssistData(sendBundle);
3357 } catch (RemoteException e) {
3358 }
3359 }
3360 }
3361
3362 public class PendingAssistExtras extends Binder implements Runnable {
3363 public final ActivityRecord activity;
3364 public boolean isHome;
3365 public final Bundle extras;
3366 public final Intent intent;
3367 public final String hint;
3368 public final IAssistDataReceiver receiver;
3369 public final int userHandle;
3370 public boolean haveResult = false;
3371 public Bundle result = null;
3372 public AssistStructure structure = null;
3373 public AssistContent content = null;
3374 public Bundle receiverExtras;
3375
3376 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3377 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3378 int _userHandle) {
3379 activity = _activity;
3380 extras = _extras;
3381 intent = _intent;
3382 hint = _hint;
3383 receiver = _receiver;
3384 receiverExtras = _receiverExtras;
3385 userHandle = _userHandle;
3386 }
3387
3388 @Override
3389 public void run() {
3390 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3391 synchronized (this) {
3392 haveResult = true;
3393 notifyAll();
3394 }
3395 pendingAssistExtrasTimedOut(this);
3396 }
3397 }
3398
3399 @Override
3400 public boolean isAssistDataAllowedOnCurrentActivity() {
3401 int userId;
3402 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003403 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3405 return false;
3406 }
3407
3408 final ActivityRecord activity = focusedStack.getTopActivity();
3409 if (activity == null) {
3410 return false;
3411 }
3412 userId = activity.userId;
3413 }
3414 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3415 }
3416
3417 @Override
3418 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3419 long ident = Binder.clearCallingIdentity();
3420 try {
3421 synchronized (mGlobalLock) {
3422 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003423 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 if (top != caller) {
3425 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3426 + " is not current top " + top);
3427 return false;
3428 }
3429 if (!top.nowVisible) {
3430 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3431 + " is not visible");
3432 return false;
3433 }
3434 }
3435 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3436 token);
3437 } finally {
3438 Binder.restoreCallingIdentity(ident);
3439 }
3440 }
3441
3442 @Override
3443 public boolean isRootVoiceInteraction(IBinder token) {
3444 synchronized (mGlobalLock) {
3445 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3446 if (r == null) {
3447 return false;
3448 }
3449 return r.rootVoiceInteraction;
3450 }
3451 }
3452
Wale Ogunwalef6733932018-06-27 05:14:34 -07003453 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3454 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3455 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3456 if (activityToCallback == null) return;
3457 activityToCallback.setVoiceSessionLocked(voiceSession);
3458
3459 // Inform the activity
3460 try {
3461 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3462 voiceInteractor);
3463 long token = Binder.clearCallingIdentity();
3464 try {
3465 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3466 } finally {
3467 Binder.restoreCallingIdentity(token);
3468 }
3469 // TODO: VI Should we cache the activity so that it's easier to find later
3470 // rather than scan through all the stacks and activities?
3471 } catch (RemoteException re) {
3472 activityToCallback.clearVoiceSessionLocked();
3473 // TODO: VI Should this terminate the voice session?
3474 }
3475 }
3476
3477 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3478 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3479 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3480 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3481 boolean wasRunningVoice = mRunningVoice != null;
3482 mRunningVoice = session;
3483 if (!wasRunningVoice) {
3484 mVoiceWakeLock.acquire();
3485 updateSleepIfNeededLocked();
3486 }
3487 }
3488 }
3489
3490 void finishRunningVoiceLocked() {
3491 if (mRunningVoice != null) {
3492 mRunningVoice = null;
3493 mVoiceWakeLock.release();
3494 updateSleepIfNeededLocked();
3495 }
3496 }
3497
3498 @Override
3499 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3500 synchronized (mGlobalLock) {
3501 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3502 if (keepAwake) {
3503 mVoiceWakeLock.acquire();
3504 } else {
3505 mVoiceWakeLock.release();
3506 }
3507 }
3508 }
3509 }
3510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 @Override
3512 public ComponentName getActivityClassForToken(IBinder token) {
3513 synchronized (mGlobalLock) {
3514 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3515 if (r == null) {
3516 return null;
3517 }
3518 return r.intent.getComponent();
3519 }
3520 }
3521
3522 @Override
3523 public String getPackageForToken(IBinder token) {
3524 synchronized (mGlobalLock) {
3525 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3526 if (r == null) {
3527 return null;
3528 }
3529 return r.packageName;
3530 }
3531 }
3532
3533 @Override
3534 public void showLockTaskEscapeMessage(IBinder token) {
3535 synchronized (mGlobalLock) {
3536 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3537 if (r == null) {
3538 return;
3539 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003540 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003541 }
3542 }
3543
3544 @Override
3545 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003546 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003547 final long token = Binder.clearCallingIdentity();
3548 try {
3549 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003550 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003551 }
3552 } finally {
3553 Binder.restoreCallingIdentity(token);
3554 }
3555 }
3556
3557 /**
3558 * Try to place task to provided position. The final position might be different depending on
3559 * current user and stacks state. The task will be moved to target stack if it's currently in
3560 * different stack.
3561 */
3562 @Override
3563 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003564 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003565 synchronized (mGlobalLock) {
3566 long ident = Binder.clearCallingIdentity();
3567 try {
3568 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3569 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003570 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 if (task == null) {
3572 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3573 + taskId);
3574 }
3575
Wale Ogunwaled32da472018-11-16 07:19:28 -08003576 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003577
3578 if (stack == null) {
3579 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3580 + stackId);
3581 }
3582 if (!stack.isActivityTypeStandardOrUndefined()) {
3583 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3584 + " the position of task " + taskId + " in/to non-standard stack");
3585 }
3586
3587 // TODO: Have the callers of this API call a separate reparent method if that is
3588 // what they intended to do vs. having this method also do reparenting.
3589 if (task.getStack() == stack) {
3590 // Change position in current stack.
3591 stack.positionChildAt(task, position);
3592 } else {
3593 // Reparent to new stack.
3594 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3595 !DEFER_RESUME, "positionTaskInStack");
3596 }
3597 } finally {
3598 Binder.restoreCallingIdentity(ident);
3599 }
3600 }
3601 }
3602
3603 @Override
3604 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3605 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3606 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3607 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3608 synchronized (mGlobalLock) {
3609 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3610 if (record == null) {
3611 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3612 + "found for: " + token);
3613 }
3614 record.setSizeConfigurations(horizontalSizeConfiguration,
3615 verticalSizeConfigurations, smallestSizeConfigurations);
3616 }
3617 }
3618
3619 /**
3620 * Dismisses split-screen multi-window mode.
3621 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3622 */
3623 @Override
3624 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003625 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003626 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3627 final long ident = Binder.clearCallingIdentity();
3628 try {
3629 synchronized (mGlobalLock) {
3630 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003631 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 if (stack == null) {
3633 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3634 return;
3635 }
3636
3637 if (toTop) {
3638 // Caller wants the current split-screen primary stack to be the top stack after
3639 // it goes fullscreen, so move it to the front.
3640 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003641 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642 // In this case the current split-screen primary stack shouldn't be the top
3643 // stack after it goes fullscreen, but it current has focus, so we move the
3644 // focus to the top-most split-screen secondary stack next to it.
3645 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3646 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3647 if (otherStack != null) {
3648 otherStack.moveToFront("dismissSplitScreenMode_other");
3649 }
3650 }
3651
Evan Rosky10475742018-09-05 19:02:48 -07003652 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003653 }
3654 } finally {
3655 Binder.restoreCallingIdentity(ident);
3656 }
3657 }
3658
3659 /**
3660 * Dismisses Pip
3661 * @param animate True if the dismissal should be animated.
3662 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3663 * default animation duration should be used.
3664 */
3665 @Override
3666 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003667 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 final long ident = Binder.clearCallingIdentity();
3669 try {
3670 synchronized (mGlobalLock) {
3671 final PinnedActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003672 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003673 if (stack == null) {
3674 Slog.w(TAG, "dismissPip: pinned stack not found.");
3675 return;
3676 }
3677 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3678 throw new IllegalArgumentException("Stack: " + stack
3679 + " doesn't support animated resize.");
3680 }
3681 if (animate) {
3682 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3683 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3684 } else {
3685 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3686 }
3687 }
3688 } finally {
3689 Binder.restoreCallingIdentity(ident);
3690 }
3691 }
3692
3693 @Override
3694 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003695 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 synchronized (mGlobalLock) {
3697 mSuppressResizeConfigChanges = suppress;
3698 }
3699 }
3700
3701 /**
3702 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3703 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3704 * activity and clearing the task at the same time.
3705 */
3706 @Override
3707 // TODO: API should just be about changing windowing modes...
3708 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003709 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003710 "moveTasksToFullscreenStack()");
3711 synchronized (mGlobalLock) {
3712 final long origId = Binder.clearCallingIdentity();
3713 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003714 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003715 if (stack != null){
3716 if (!stack.isActivityTypeStandardOrUndefined()) {
3717 throw new IllegalArgumentException(
3718 "You can't move tasks from non-standard stacks.");
3719 }
3720 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3721 }
3722 } finally {
3723 Binder.restoreCallingIdentity(origId);
3724 }
3725 }
3726 }
3727
3728 /**
3729 * Moves the top activity in the input stackId to the pinned stack.
3730 *
3731 * @param stackId Id of stack to move the top activity to pinned stack.
3732 * @param bounds Bounds to use for pinned stack.
3733 *
3734 * @return True if the top activity of the input stack was successfully moved to the pinned
3735 * stack.
3736 */
3737 @Override
3738 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003739 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 "moveTopActivityToPinnedStack()");
3741 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003742 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003743 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3744 + "Device doesn't support picture-in-picture mode");
3745 }
3746
3747 long ident = Binder.clearCallingIdentity();
3748 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003749 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003750 } finally {
3751 Binder.restoreCallingIdentity(ident);
3752 }
3753 }
3754 }
3755
3756 @Override
3757 public boolean isInMultiWindowMode(IBinder token) {
3758 final long origId = Binder.clearCallingIdentity();
3759 try {
3760 synchronized (mGlobalLock) {
3761 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3762 if (r == null) {
3763 return false;
3764 }
3765 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3766 return r.inMultiWindowMode();
3767 }
3768 } finally {
3769 Binder.restoreCallingIdentity(origId);
3770 }
3771 }
3772
3773 @Override
3774 public boolean isInPictureInPictureMode(IBinder token) {
3775 final long origId = Binder.clearCallingIdentity();
3776 try {
3777 synchronized (mGlobalLock) {
3778 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3779 }
3780 } finally {
3781 Binder.restoreCallingIdentity(origId);
3782 }
3783 }
3784
3785 private boolean isInPictureInPictureMode(ActivityRecord r) {
3786 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3787 || r.getStack().isInStackLocked(r) == null) {
3788 return false;
3789 }
3790
3791 // If we are animating to fullscreen then we have already dispatched the PIP mode
3792 // changed, so we should reflect that check here as well.
3793 final PinnedActivityStack stack = r.getStack();
3794 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3795 return !windowController.isAnimatingBoundsToFullscreen();
3796 }
3797
3798 @Override
3799 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3800 final long origId = Binder.clearCallingIdentity();
3801 try {
3802 synchronized (mGlobalLock) {
3803 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3804 "enterPictureInPictureMode", token, params);
3805
3806 // If the activity is already in picture in picture mode, then just return early
3807 if (isInPictureInPictureMode(r)) {
3808 return true;
3809 }
3810
3811 // Activity supports picture-in-picture, now check that we can enter PiP at this
3812 // point, if it is
3813 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3814 false /* beforeStopping */)) {
3815 return false;
3816 }
3817
3818 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003819 synchronized (mGlobalLock) {
3820 // Only update the saved args from the args that are set
3821 r.pictureInPictureArgs.copyOnlySet(params);
3822 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3823 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3824 // Adjust the source bounds by the insets for the transition down
3825 final Rect sourceBounds = new Rect(
3826 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003827 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003828 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3829 final PinnedActivityStack stack = r.getStack();
3830 stack.setPictureInPictureAspectRatio(aspectRatio);
3831 stack.setPictureInPictureActions(actions);
3832 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3833 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3834 logPictureInPictureArgs(params);
3835 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 };
3837
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003838 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 // If the keyguard is showing or occluded, then try and dismiss it before
3840 // entering picture-in-picture (this will prompt the user to authenticate if the
3841 // device is currently locked).
3842 dismissKeyguard(token, new KeyguardDismissCallback() {
3843 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003844 public void onDismissSucceeded() {
3845 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846 }
3847 }, null /* message */);
3848 } else {
3849 // Enter picture in picture immediately otherwise
3850 enterPipRunnable.run();
3851 }
3852 return true;
3853 }
3854 } finally {
3855 Binder.restoreCallingIdentity(origId);
3856 }
3857 }
3858
3859 @Override
3860 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3861 final long origId = Binder.clearCallingIdentity();
3862 try {
3863 synchronized (mGlobalLock) {
3864 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3865 "setPictureInPictureParams", token, params);
3866
3867 // Only update the saved args from the args that are set
3868 r.pictureInPictureArgs.copyOnlySet(params);
3869 if (r.inPinnedWindowingMode()) {
3870 // If the activity is already in picture-in-picture, update the pinned stack now
3871 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3872 // be used the next time the activity enters PiP
3873 final PinnedActivityStack stack = r.getStack();
3874 if (!stack.isAnimatingBoundsToFullscreen()) {
3875 stack.setPictureInPictureAspectRatio(
3876 r.pictureInPictureArgs.getAspectRatio());
3877 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3878 }
3879 }
3880 logPictureInPictureArgs(params);
3881 }
3882 } finally {
3883 Binder.restoreCallingIdentity(origId);
3884 }
3885 }
3886
3887 @Override
3888 public int getMaxNumPictureInPictureActions(IBinder token) {
3889 // Currently, this is a static constant, but later, we may change this to be dependent on
3890 // the context of the activity
3891 return 3;
3892 }
3893
3894 private void logPictureInPictureArgs(PictureInPictureParams params) {
3895 if (params.hasSetActions()) {
3896 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3897 params.getActions().size());
3898 }
3899 if (params.hasSetAspectRatio()) {
3900 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3901 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3902 MetricsLogger.action(lm);
3903 }
3904 }
3905
3906 /**
3907 * Checks the state of the system and the activity associated with the given {@param token} to
3908 * verify that picture-in-picture is supported for that activity.
3909 *
3910 * @return the activity record for the given {@param token} if all the checks pass.
3911 */
3912 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3913 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003914 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 throw new IllegalStateException(caller
3916 + ": Device doesn't support picture-in-picture mode.");
3917 }
3918
3919 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3920 if (r == null) {
3921 throw new IllegalStateException(caller
3922 + ": Can't find activity for token=" + token);
3923 }
3924
3925 if (!r.supportsPictureInPicture()) {
3926 throw new IllegalStateException(caller
3927 + ": Current activity does not support picture-in-picture.");
3928 }
3929
3930 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003931 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 params.getAspectRatio())) {
3933 final float minAspectRatio = mContext.getResources().getFloat(
3934 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3935 final float maxAspectRatio = mContext.getResources().getFloat(
3936 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3937 throw new IllegalArgumentException(String.format(caller
3938 + ": Aspect ratio is too extreme (must be between %f and %f).",
3939 minAspectRatio, maxAspectRatio));
3940 }
3941
3942 // Truncate the number of actions if necessary
3943 params.truncateActions(getMaxNumPictureInPictureActions(token));
3944
3945 return r;
3946 }
3947
3948 @Override
3949 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003950 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 synchronized (mGlobalLock) {
3952 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3953 if (r == null) {
3954 throw new IllegalArgumentException("Activity does not exist; token="
3955 + activityToken);
3956 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003957 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 }
3959 }
3960
3961 @Override
3962 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3963 Rect tempDockedTaskInsetBounds,
3964 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003965 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 long ident = Binder.clearCallingIdentity();
3967 try {
3968 synchronized (mGlobalLock) {
3969 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3970 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3971 PRESERVE_WINDOWS);
3972 }
3973 } finally {
3974 Binder.restoreCallingIdentity(ident);
3975 }
3976 }
3977
3978 @Override
3979 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003980 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 final long ident = Binder.clearCallingIdentity();
3982 try {
3983 synchronized (mGlobalLock) {
3984 mStackSupervisor.setSplitScreenResizing(resizing);
3985 }
3986 } finally {
3987 Binder.restoreCallingIdentity(ident);
3988 }
3989 }
3990
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003991 /**
3992 * Check that we have the features required for VR-related API calls, and throw an exception if
3993 * not.
3994 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003995 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003996 if (!mContext.getPackageManager().hasSystemFeature(
3997 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3998 throw new UnsupportedOperationException("VR mode not supported on this device!");
3999 }
4000 }
4001
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 @Override
4003 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004004 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005
4006 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4007
4008 ActivityRecord r;
4009 synchronized (mGlobalLock) {
4010 r = ActivityRecord.isInStackLocked(token);
4011 }
4012
4013 if (r == null) {
4014 throw new IllegalArgumentException();
4015 }
4016
4017 int err;
4018 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
4019 VrManagerInternal.NO_ERROR) {
4020 return err;
4021 }
4022
4023 // Clear the binder calling uid since this path may call moveToTask().
4024 final long callingId = Binder.clearCallingIdentity();
4025 try {
4026 synchronized (mGlobalLock) {
4027 r.requestedVrComponent = (enabled) ? packageName : null;
4028
4029 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004030 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004031 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 }
4033 return 0;
4034 }
4035 } finally {
4036 Binder.restoreCallingIdentity(callingId);
4037 }
4038 }
4039
4040 @Override
4041 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4042 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4043 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004044 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4046 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4047 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004048 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049 || activity.voiceSession != null) {
4050 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4051 return;
4052 }
4053 if (activity.pendingVoiceInteractionStart) {
4054 Slog.w(TAG, "Pending start of voice interaction already.");
4055 return;
4056 }
4057 activity.pendingVoiceInteractionStart = true;
4058 }
4059 LocalServices.getService(VoiceInteractionManagerInternal.class)
4060 .startLocalVoiceInteraction(callingActivity, options);
4061 }
4062
4063 @Override
4064 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4065 LocalServices.getService(VoiceInteractionManagerInternal.class)
4066 .stopLocalVoiceInteraction(callingActivity);
4067 }
4068
4069 @Override
4070 public boolean supportsLocalVoiceInteraction() {
4071 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4072 .supportsLocalVoiceInteraction();
4073 }
4074
4075 /** Notifies all listeners when the pinned stack animation starts. */
4076 @Override
4077 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004078 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 }
4080
4081 /** Notifies all listeners when the pinned stack animation ends. */
4082 @Override
4083 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004084 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 }
4086
4087 @Override
4088 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004089 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 final long ident = Binder.clearCallingIdentity();
4091 try {
4092 synchronized (mGlobalLock) {
4093 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4094 }
4095 } finally {
4096 Binder.restoreCallingIdentity(ident);
4097 }
4098 }
4099
4100 @Override
4101 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004102 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103
4104 synchronized (mGlobalLock) {
4105 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004106 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107 // Call might come when display is not yet added or has already been removed.
4108 if (DEBUG_CONFIGURATION) {
4109 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4110 + displayId);
4111 }
4112 return false;
4113 }
4114
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004115 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004117 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 }
4119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004120 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004121 final Message msg = PooledLambda.obtainMessage(
4122 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4123 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 }
4125
4126 final long origId = Binder.clearCallingIdentity();
4127 try {
4128 if (values != null) {
4129 Settings.System.clearConfiguration(values);
4130 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004131 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4133 return mTmpUpdateConfigurationResult.changes != 0;
4134 } finally {
4135 Binder.restoreCallingIdentity(origId);
4136 }
4137 }
4138 }
4139
4140 @Override
4141 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004142 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143
4144 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004145 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004146 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 }
4149
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004150 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004151 final Message msg = PooledLambda.obtainMessage(
4152 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4153 DEFAULT_DISPLAY);
4154 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004155 }
4156
4157 final long origId = Binder.clearCallingIdentity();
4158 try {
4159 if (values != null) {
4160 Settings.System.clearConfiguration(values);
4161 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004162 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 UserHandle.USER_NULL, false /* deferResume */,
4164 mTmpUpdateConfigurationResult);
4165 return mTmpUpdateConfigurationResult.changes != 0;
4166 } finally {
4167 Binder.restoreCallingIdentity(origId);
4168 }
4169 }
4170 }
4171
4172 @Override
4173 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4174 CharSequence message) {
4175 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004176 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4178 }
4179 final long callingId = Binder.clearCallingIdentity();
4180 try {
4181 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004182 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004183 }
4184 } finally {
4185 Binder.restoreCallingIdentity(callingId);
4186 }
4187 }
4188
4189 @Override
4190 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 "cancelTaskWindowTransition()");
4193 final long ident = Binder.clearCallingIdentity();
4194 try {
4195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004196 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197 MATCH_TASK_IN_STACKS_ONLY);
4198 if (task == null) {
4199 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4200 return;
4201 }
4202 task.cancelWindowTransition();
4203 }
4204 } finally {
4205 Binder.restoreCallingIdentity(ident);
4206 }
4207 }
4208
4209 @Override
4210 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004211 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 final long ident = Binder.clearCallingIdentity();
4213 try {
4214 final TaskRecord task;
4215 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004216 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004217 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4218 if (task == null) {
4219 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4220 return null;
4221 }
4222 }
4223 // Don't call this while holding the lock as this operation might hit the disk.
4224 return task.getSnapshot(reducedResolution);
4225 } finally {
4226 Binder.restoreCallingIdentity(ident);
4227 }
4228 }
4229
4230 @Override
4231 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4232 synchronized (mGlobalLock) {
4233 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4234 if (r == null) {
4235 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4236 + token);
4237 return;
4238 }
4239 final long origId = Binder.clearCallingIdentity();
4240 try {
4241 r.setDisablePreviewScreenshots(disable);
4242 } finally {
4243 Binder.restoreCallingIdentity(origId);
4244 }
4245 }
4246 }
4247
4248 /** Return the user id of the last resumed activity. */
4249 @Override
4250 public @UserIdInt
4251 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004252 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004253 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4254 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004255 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004258 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 }
4260 }
4261
4262 @Override
4263 public void updateLockTaskFeatures(int userId, int flags) {
4264 final int callingUid = Binder.getCallingUid();
4265 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004266 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004267 "updateLockTaskFeatures()");
4268 }
4269 synchronized (mGlobalLock) {
4270 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4271 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004272 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004273 }
4274 }
4275
4276 @Override
4277 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4278 synchronized (mGlobalLock) {
4279 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4280 if (r == null) {
4281 return;
4282 }
4283 final long origId = Binder.clearCallingIdentity();
4284 try {
4285 r.setShowWhenLocked(showWhenLocked);
4286 } finally {
4287 Binder.restoreCallingIdentity(origId);
4288 }
4289 }
4290 }
4291
4292 @Override
4293 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4294 synchronized (mGlobalLock) {
4295 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4296 if (r == null) {
4297 return;
4298 }
4299 final long origId = Binder.clearCallingIdentity();
4300 try {
4301 r.setTurnScreenOn(turnScreenOn);
4302 } finally {
4303 Binder.restoreCallingIdentity(origId);
4304 }
4305 }
4306 }
4307
4308 @Override
4309 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 "registerRemoteAnimations");
4312 definition.setCallingPid(Binder.getCallingPid());
4313 synchronized (mGlobalLock) {
4314 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4315 if (r == null) {
4316 return;
4317 }
4318 final long origId = Binder.clearCallingIdentity();
4319 try {
4320 r.registerRemoteAnimations(definition);
4321 } finally {
4322 Binder.restoreCallingIdentity(origId);
4323 }
4324 }
4325 }
4326
4327 @Override
4328 public void registerRemoteAnimationForNextActivityStart(String packageName,
4329 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004330 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004331 "registerRemoteAnimationForNextActivityStart");
4332 adapter.setCallingPid(Binder.getCallingPid());
4333 synchronized (mGlobalLock) {
4334 final long origId = Binder.clearCallingIdentity();
4335 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004336 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004337 packageName, adapter);
4338 } finally {
4339 Binder.restoreCallingIdentity(origId);
4340 }
4341 }
4342 }
4343
4344 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4345 @Override
4346 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4347 synchronized (mGlobalLock) {
4348 final long origId = Binder.clearCallingIdentity();
4349 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004350 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 } finally {
4352 Binder.restoreCallingIdentity(origId);
4353 }
4354 }
4355 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004356
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004357 @Override
4358 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004360 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004361 final int pid = Binder.getCallingPid();
4362 final WindowProcessController wpc = mPidMap.get(pid);
4363 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004364 }
4365 }
4366
4367 @Override
4368 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004369 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004370 != PERMISSION_GRANTED) {
4371 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4372 + Binder.getCallingPid()
4373 + ", uid=" + Binder.getCallingUid()
4374 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4375 Slog.w(TAG, msg);
4376 throw new SecurityException(msg);
4377 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004378 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004379 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004380 final int pid = Binder.getCallingPid();
4381 final WindowProcessController proc = mPidMap.get(pid);
4382 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004383 }
4384 }
4385
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 @Override
4387 public void stopAppSwitches() {
4388 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4389 synchronized (mGlobalLock) {
4390 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4391 mDidAppSwitch = false;
4392 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4393 }
4394 }
4395
4396 @Override
4397 public void resumeAppSwitches() {
4398 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4399 synchronized (mGlobalLock) {
4400 // Note that we don't execute any pending app switches... we will
4401 // let those wait until either the timeout, or the next start
4402 // activity request.
4403 mAppSwitchesAllowedTime = 0;
4404 }
4405 }
4406
4407 void onStartActivitySetDidAppSwitch() {
4408 if (mDidAppSwitch) {
4409 // This is the second allowed switch since we stopped switches, so now just generally
4410 // allow switches. Use case:
4411 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4412 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4413 // anyone to switch again).
4414 mAppSwitchesAllowedTime = 0;
4415 } else {
4416 mDidAppSwitch = true;
4417 }
4418 }
4419
4420 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 boolean shouldDisableNonVrUiLocked() {
4422 return mVrController.shouldDisableNonVrUiLocked();
4423 }
4424
Wale Ogunwale53783742018-09-16 10:21:51 -07004425 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004426 // VR apps are expected to run in a main display. If an app is turning on VR for
4427 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4428 // fullscreen stack before enabling VR Mode.
4429 // TODO: The goal of this code is to keep the VR app on the main display. When the
4430 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4431 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4432 // option would be a better choice here.
4433 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4434 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4435 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004436 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004437 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4438 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4439 }
4440 mH.post(() -> {
4441 if (!mVrController.onVrModeChanged(r)) {
4442 return;
4443 }
4444 synchronized (mGlobalLock) {
4445 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4446 mWindowManager.disableNonVrUi(disableNonVrUi);
4447 if (disableNonVrUi) {
4448 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4449 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004450 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004451 }
4452 }
4453 });
4454 }
4455
Wale Ogunwale53783742018-09-16 10:21:51 -07004456 @Override
4457 public int getPackageScreenCompatMode(String packageName) {
4458 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4459 synchronized (mGlobalLock) {
4460 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4461 }
4462 }
4463
4464 @Override
4465 public void setPackageScreenCompatMode(String packageName, int mode) {
4466 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4467 "setPackageScreenCompatMode");
4468 synchronized (mGlobalLock) {
4469 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4470 }
4471 }
4472
4473 @Override
4474 public boolean getPackageAskScreenCompat(String packageName) {
4475 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4476 synchronized (mGlobalLock) {
4477 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4478 }
4479 }
4480
4481 @Override
4482 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4483 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4484 "setPackageAskScreenCompat");
4485 synchronized (mGlobalLock) {
4486 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4487 }
4488 }
4489
Wale Ogunwale64258362018-10-16 15:13:37 -07004490 public static String relaunchReasonToString(int relaunchReason) {
4491 switch (relaunchReason) {
4492 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4493 return "window_resize";
4494 case RELAUNCH_REASON_FREE_RESIZE:
4495 return "free_resize";
4496 default:
4497 return null;
4498 }
4499 }
4500
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004501 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004502 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 }
4504
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004505 /** Pokes the task persister. */
4506 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4507 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4508 }
4509
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004510 boolean isKeyguardLocked() {
4511 return mKeyguardController.isKeyguardLocked();
4512 }
4513
Wale Ogunwale31913b52018-10-13 08:29:31 -07004514 void dumpLastANRLocked(PrintWriter pw) {
4515 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4516 if (mLastANRState == null) {
4517 pw.println(" <no ANR has occurred since boot>");
4518 } else {
4519 pw.println(mLastANRState);
4520 }
4521 }
4522
4523 void dumpLastANRTracesLocked(PrintWriter pw) {
4524 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4525
4526 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4527 if (ArrayUtils.isEmpty(files)) {
4528 pw.println(" <no ANR has occurred since boot>");
4529 return;
4530 }
4531 // Find the latest file.
4532 File latest = null;
4533 for (File f : files) {
4534 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4535 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004536 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004537 }
4538 pw.print("File: ");
4539 pw.print(latest.getName());
4540 pw.println();
4541 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4542 String line;
4543 while ((line = in.readLine()) != null) {
4544 pw.println(line);
4545 }
4546 } catch (IOException e) {
4547 pw.print("Unable to read: ");
4548 pw.print(e);
4549 pw.println();
4550 }
4551 }
4552
4553 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4554 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4555 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4556 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4557 }
4558
4559 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4560 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4561 pw.println(header);
4562
Wale Ogunwaled32da472018-11-16 07:19:28 -08004563 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004564 dumpPackage);
4565 boolean needSep = printedAnything;
4566
4567 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004568 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004569 " ResumedActivity: ");
4570 if (printed) {
4571 printedAnything = true;
4572 needSep = false;
4573 }
4574
4575 if (dumpPackage == null) {
4576 if (needSep) {
4577 pw.println();
4578 }
4579 printedAnything = true;
4580 mStackSupervisor.dump(pw, " ");
4581 }
4582
4583 if (!printedAnything) {
4584 pw.println(" (nothing)");
4585 }
4586 }
4587
4588 void dumpActivityContainersLocked(PrintWriter pw) {
4589 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004590 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004591 pw.println(" ");
4592 }
4593
4594 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4595 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4596 getActivityStartController().dump(pw, "", dumpPackage);
4597 }
4598
4599 /**
4600 * There are three things that cmd can be:
4601 * - a flattened component name that matches an existing activity
4602 * - the cmd arg isn't the flattened component name of an existing activity:
4603 * dump all activity whose component contains the cmd as a substring
4604 * - A hex number of the ActivityRecord object instance.
4605 *
4606 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4607 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4608 */
4609 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4610 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4611 ArrayList<ActivityRecord> activities;
4612
4613 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004614 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004615 dumpFocusedStackOnly);
4616 }
4617
4618 if (activities.size() <= 0) {
4619 return false;
4620 }
4621
4622 String[] newArgs = new String[args.length - opti];
4623 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4624
4625 TaskRecord lastTask = null;
4626 boolean needSep = false;
4627 for (int i = activities.size() - 1; i >= 0; i--) {
4628 ActivityRecord r = activities.get(i);
4629 if (needSep) {
4630 pw.println();
4631 }
4632 needSep = true;
4633 synchronized (mGlobalLock) {
4634 final TaskRecord task = r.getTask();
4635 if (lastTask != task) {
4636 lastTask = task;
4637 pw.print("TASK "); pw.print(lastTask.affinity);
4638 pw.print(" id="); pw.print(lastTask.taskId);
4639 pw.print(" userId="); pw.println(lastTask.userId);
4640 if (dumpAll) {
4641 lastTask.dump(pw, " ");
4642 }
4643 }
4644 }
4645 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4646 }
4647 return true;
4648 }
4649
4650 /**
4651 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4652 * there is a thread associated with the activity.
4653 */
4654 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4655 final ActivityRecord r, String[] args, boolean dumpAll) {
4656 String innerPrefix = prefix + " ";
4657 synchronized (mGlobalLock) {
4658 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4659 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4660 pw.print(" pid=");
4661 if (r.hasProcess()) pw.println(r.app.getPid());
4662 else pw.println("(not running)");
4663 if (dumpAll) {
4664 r.dump(pw, innerPrefix);
4665 }
4666 }
4667 if (r.attachedToProcess()) {
4668 // flush anything that is already in the PrintWriter since the thread is going
4669 // to write to the file descriptor directly
4670 pw.flush();
4671 try {
4672 TransferPipe tp = new TransferPipe();
4673 try {
4674 r.app.getThread().dumpActivity(tp.getWriteFd(),
4675 r.appToken, innerPrefix, args);
4676 tp.go(fd);
4677 } finally {
4678 tp.kill();
4679 }
4680 } catch (IOException e) {
4681 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4682 } catch (RemoteException e) {
4683 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4684 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004685 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004686 }
4687
Wale Ogunwalef6733932018-06-27 05:14:34 -07004688 void writeSleepStateToProto(ProtoOutputStream proto) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004689 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004690 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4691 st.toString());
4692 }
4693
4694 if (mRunningVoice != null) {
4695 final long vrToken = proto.start(
4696 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4697 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4698 mRunningVoice.toString());
4699 mVoiceWakeLock.writeToProto(
4700 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4701 proto.end(vrToken);
4702 }
4703
4704 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4705 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4706 mShuttingDown);
4707 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004708 }
4709
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004710 int getCurrentUserId() {
4711 return mAmInternal.getCurrentUserId();
4712 }
4713
4714 private void enforceNotIsolatedCaller(String caller) {
4715 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4716 throw new SecurityException("Isolated process not allowed to call " + caller);
4717 }
4718 }
4719
Wale Ogunwalef6733932018-06-27 05:14:34 -07004720 public Configuration getConfiguration() {
4721 Configuration ci;
4722 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004723 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004724 ci.userSetLocale = false;
4725 }
4726 return ci;
4727 }
4728
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004729 /**
4730 * Current global configuration information. Contains general settings for the entire system,
4731 * also corresponds to the merged configuration of the default display.
4732 */
4733 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004734 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004735 }
4736
4737 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4738 boolean initLocale) {
4739 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4740 }
4741
4742 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4743 boolean initLocale, boolean deferResume) {
4744 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4745 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4746 UserHandle.USER_NULL, deferResume);
4747 }
4748
Wale Ogunwale59507092018-10-29 09:00:30 -07004749 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004750 final long origId = Binder.clearCallingIdentity();
4751 try {
4752 synchronized (mGlobalLock) {
4753 updateConfigurationLocked(values, null, false, true, userId,
4754 false /* deferResume */);
4755 }
4756 } finally {
4757 Binder.restoreCallingIdentity(origId);
4758 }
4759 }
4760
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004761 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4762 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4763 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4764 deferResume, null /* result */);
4765 }
4766
4767 /**
4768 * Do either or both things: (1) change the current configuration, and (2)
4769 * make sure the given activity is running with the (now) current
4770 * configuration. Returns true if the activity has been left running, or
4771 * false if <var>starting</var> is being destroyed to match the new
4772 * configuration.
4773 *
4774 * @param userId is only used when persistent parameter is set to true to persist configuration
4775 * for that particular user
4776 */
4777 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4778 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4779 ActivityTaskManagerService.UpdateConfigurationResult result) {
4780 int changes = 0;
4781 boolean kept = true;
4782
4783 if (mWindowManager != null) {
4784 mWindowManager.deferSurfaceLayout();
4785 }
4786 try {
4787 if (values != null) {
4788 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4789 deferResume);
4790 }
4791
4792 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4793 } finally {
4794 if (mWindowManager != null) {
4795 mWindowManager.continueSurfaceLayout();
4796 }
4797 }
4798
4799 if (result != null) {
4800 result.changes = changes;
4801 result.activityRelaunched = !kept;
4802 }
4803 return kept;
4804 }
4805
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004806 /** Update default (global) configuration and notify listeners about changes. */
4807 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4808 boolean persistent, int userId, boolean deferResume) {
4809 mTempConfig.setTo(getGlobalConfiguration());
4810 final int changes = mTempConfig.updateFrom(values);
4811 if (changes == 0) {
4812 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4813 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4814 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4815 // (even if there are no actual changes) to unfreeze the window.
4816 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4817 return 0;
4818 }
4819
4820 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4821 "Updating global configuration to: " + values);
4822
4823 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4824 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4825 values.colorMode,
4826 values.densityDpi,
4827 values.fontScale,
4828 values.hardKeyboardHidden,
4829 values.keyboard,
4830 values.keyboardHidden,
4831 values.mcc,
4832 values.mnc,
4833 values.navigation,
4834 values.navigationHidden,
4835 values.orientation,
4836 values.screenHeightDp,
4837 values.screenLayout,
4838 values.screenWidthDp,
4839 values.smallestScreenWidthDp,
4840 values.touchscreen,
4841 values.uiMode);
4842
4843
4844 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4845 final LocaleList locales = values.getLocales();
4846 int bestLocaleIndex = 0;
4847 if (locales.size() > 1) {
4848 if (mSupportedSystemLocales == null) {
4849 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4850 }
4851 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4852 }
4853 SystemProperties.set("persist.sys.locale",
4854 locales.get(bestLocaleIndex).toLanguageTag());
4855 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004856
4857 final Message m = PooledLambda.obtainMessage(
4858 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4859 locales.get(bestLocaleIndex));
4860 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004861 }
4862
Yunfan Chen75157d72018-07-27 14:47:21 +09004863 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004864
4865 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004866 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004867
4868 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4869 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004870 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004871
4872 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004873 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004874
4875 AttributeCache ac = AttributeCache.instance();
4876 if (ac != null) {
4877 ac.updateConfiguration(mTempConfig);
4878 }
4879
4880 // Make sure all resources in our process are updated right now, so that anyone who is going
4881 // to retrieve resource values after we return will be sure to get the new ones. This is
4882 // especially important during boot, where the first config change needs to guarantee all
4883 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004884 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004885
4886 // We need another copy of global config because we're scheduling some calls instead of
4887 // running them in place. We need to be sure that object we send will be handled unchanged.
4888 final Configuration configCopy = new Configuration(mTempConfig);
4889 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004890 final Message msg = PooledLambda.obtainMessage(
4891 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4892 this, userId, configCopy);
4893 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004894 }
4895
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004896 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004897 final int pid = mPidMap.keyAt(i);
4898 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004899 if (DEBUG_CONFIGURATION) {
4900 Slog.v(TAG_CONFIGURATION, "Update process config of "
4901 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004902 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004903 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004904 }
4905
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004906 final Message msg = PooledLambda.obtainMessage(
4907 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4908 mAmInternal, changes, initLocale);
4909 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004910
4911 // Override configuration of the default display duplicates global config, so we need to
4912 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004913 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004914 DEFAULT_DISPLAY);
4915
4916 return changes;
4917 }
4918
4919 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4920 boolean deferResume, int displayId) {
4921 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4922 displayId, null /* result */);
4923 }
4924
4925 /**
4926 * Updates override configuration specific for the selected display. If no config is provided,
4927 * new one will be computed in WM based on current display info.
4928 */
4929 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4930 ActivityRecord starting, boolean deferResume, int displayId,
4931 ActivityTaskManagerService.UpdateConfigurationResult result) {
4932 int changes = 0;
4933 boolean kept = true;
4934
4935 if (mWindowManager != null) {
4936 mWindowManager.deferSurfaceLayout();
4937 }
4938 try {
4939 if (values != null) {
4940 if (displayId == DEFAULT_DISPLAY) {
4941 // Override configuration of the default display duplicates global config, so
4942 // we're calling global config update instead for default display. It will also
4943 // apply the correct override config.
4944 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4945 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4946 } else {
4947 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4948 }
4949 }
4950
4951 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4952 } finally {
4953 if (mWindowManager != null) {
4954 mWindowManager.continueSurfaceLayout();
4955 }
4956 }
4957
4958 if (result != null) {
4959 result.changes = changes;
4960 result.activityRelaunched = !kept;
4961 }
4962 return kept;
4963 }
4964
4965 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4966 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004967 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004968 final int changes = mTempConfig.updateFrom(values);
4969 if (changes != 0) {
4970 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4971 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08004972 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004973
4974 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4975 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004976 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004977
Wale Ogunwale5c918702018-10-18 11:06:33 -07004978 // Post message to start process to avoid possible deadlock of calling into AMS with
4979 // the ATMS lock held.
4980 final Message msg = PooledLambda.obtainMessage(
4981 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4982 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4983 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004984 }
4985 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004986 return changes;
4987 }
4988
Wale Ogunwalef6733932018-06-27 05:14:34 -07004989 private void updateEventDispatchingLocked(boolean booted) {
4990 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4991 }
4992
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004993 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4994 final ContentResolver resolver = mContext.getContentResolver();
4995 Settings.System.putConfigurationForUser(resolver, config, userId);
4996 }
4997
4998 private void sendLocaleToMountDaemonMsg(Locale l) {
4999 try {
5000 IBinder service = ServiceManager.getService("mount");
5001 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5002 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5003 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5004 } catch (RemoteException e) {
5005 Log.e(TAG, "Error storing locale for decryption UI", e);
5006 }
5007 }
5008
Alison Cichowlas3e340502018-08-07 17:15:01 -04005009 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5010 mStartActivitySources.remove(permissionToken);
5011 mExpiredStartAsCallerTokens.add(permissionToken);
5012 }
5013
5014 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5015 mExpiredStartAsCallerTokens.remove(permissionToken);
5016 }
5017
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005018 boolean isActivityStartsLoggingEnabled() {
5019 return mAmInternal.isActivityStartsLoggingEnabled();
5020 }
5021
Wale Ogunwalef6733932018-06-27 05:14:34 -07005022 void enableScreenAfterBoot(boolean booted) {
5023 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5024 SystemClock.uptimeMillis());
5025 mWindowManager.enableScreenAfterBoot();
5026
5027 synchronized (mGlobalLock) {
5028 updateEventDispatchingLocked(booted);
5029 }
5030 }
5031
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005032 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5033 if (r == null || !r.hasProcess()) {
5034 return KEY_DISPATCHING_TIMEOUT_MS;
5035 }
5036 return getInputDispatchingTimeoutLocked(r.app);
5037 }
5038
5039 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005040 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005041 }
5042
Wale Ogunwalef6733932018-06-27 05:14:34 -07005043 /**
5044 * Decide based on the configuration whether we should show the ANR,
5045 * crash, etc dialogs. The idea is that if there is no affordance to
5046 * press the on-screen buttons, or the user experience would be more
5047 * greatly impacted than the crash itself, we shouldn't show the dialog.
5048 *
5049 * A thought: SystemUI might also want to get told about this, the Power
5050 * dialog / global actions also might want different behaviors.
5051 */
5052 private void updateShouldShowDialogsLocked(Configuration config) {
5053 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5054 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5055 && config.navigation == Configuration.NAVIGATION_NONAV);
5056 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5057 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5058 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5059 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5060 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5061 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5062 HIDE_ERROR_DIALOGS, 0) != 0;
5063 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5064 }
5065
5066 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5067 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5068 FONT_SCALE, 1.0f, userId);
5069
5070 synchronized (this) {
5071 if (getGlobalConfiguration().fontScale == scaleFactor) {
5072 return;
5073 }
5074
5075 final Configuration configuration
5076 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5077 configuration.fontScale = scaleFactor;
5078 updatePersistentConfiguration(configuration, userId);
5079 }
5080 }
5081
5082 // Actually is sleeping or shutting down or whatever else in the future
5083 // is an inactive state.
5084 boolean isSleepingOrShuttingDownLocked() {
5085 return isSleepingLocked() || mShuttingDown;
5086 }
5087
5088 boolean isSleepingLocked() {
5089 return mSleeping;
5090 }
5091
Riddle Hsu16567132018-08-16 21:37:47 +08005092 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005093 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
5094 final TaskRecord task = r.getTask();
5095 if (task.isActivityTypeStandard()) {
5096 if (mCurAppTimeTracker != r.appTimeTracker) {
5097 // We are switching app tracking. Complete the current one.
5098 if (mCurAppTimeTracker != null) {
5099 mCurAppTimeTracker.stop();
5100 mH.obtainMessage(
5101 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005102 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005103 mCurAppTimeTracker = null;
5104 }
5105 if (r.appTimeTracker != null) {
5106 mCurAppTimeTracker = r.appTimeTracker;
5107 startTimeTrackingFocusedActivityLocked();
5108 }
5109 } else {
5110 startTimeTrackingFocusedActivityLocked();
5111 }
5112 } else {
5113 r.appTimeTracker = null;
5114 }
5115 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5116 // TODO: Probably not, because we don't want to resume voice on switching
5117 // back to this activity
5118 if (task.voiceInteractor != null) {
5119 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5120 } else {
5121 finishRunningVoiceLocked();
5122
5123 if (mLastResumedActivity != null) {
5124 final IVoiceInteractionSession session;
5125
5126 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5127 if (lastResumedActivityTask != null
5128 && lastResumedActivityTask.voiceSession != null) {
5129 session = lastResumedActivityTask.voiceSession;
5130 } else {
5131 session = mLastResumedActivity.voiceSession;
5132 }
5133
5134 if (session != null) {
5135 // We had been in a voice interaction session, but now focused has
5136 // move to something different. Just finish the session, we can't
5137 // return to it and retain the proper state and synchronization with
5138 // the voice interaction service.
5139 finishVoiceTask(session);
5140 }
5141 }
5142 }
5143
5144 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5145 mAmInternal.sendForegroundProfileChanged(r.userId);
5146 }
5147 updateResumedAppTrace(r);
5148 mLastResumedActivity = r;
5149
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005150 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005151
5152 applyUpdateLockStateLocked(r);
5153 applyUpdateVrModeLocked(r);
5154
5155 EventLogTags.writeAmSetResumedActivity(
5156 r == null ? -1 : r.userId,
5157 r == null ? "NULL" : r.shortComponentName,
5158 reason);
5159 }
5160
5161 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5162 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005163 final ActivityTaskManagerInternal.SleepToken token =
5164 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005165 updateSleepIfNeededLocked();
5166 return token;
5167 }
5168 }
5169
5170 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005171 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005172 final boolean wasSleeping = mSleeping;
5173 boolean updateOomAdj = false;
5174
5175 if (!shouldSleep) {
5176 // If wasSleeping is true, we need to wake up activity manager state from when
5177 // we started sleeping. In either case, we need to apply the sleep tokens, which
5178 // will wake up stacks or put them to sleep as appropriate.
5179 if (wasSleeping) {
5180 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005181 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5182 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005183 startTimeTrackingFocusedActivityLocked();
5184 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5185 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5186 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005187 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005188 if (wasSleeping) {
5189 updateOomAdj = true;
5190 }
5191 } else if (!mSleeping && shouldSleep) {
5192 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005193 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5194 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005195 if (mCurAppTimeTracker != null) {
5196 mCurAppTimeTracker.stop();
5197 }
5198 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5199 mStackSupervisor.goingToSleepLocked();
5200 updateResumedAppTrace(null /* resumed */);
5201 updateOomAdj = true;
5202 }
5203 if (updateOomAdj) {
5204 mH.post(mAmInternal::updateOomAdj);
5205 }
5206 }
5207
5208 void updateOomAdj() {
5209 mH.post(mAmInternal::updateOomAdj);
5210 }
5211
Wale Ogunwale53783742018-09-16 10:21:51 -07005212 void updateCpuStats() {
5213 mH.post(mAmInternal::updateCpuStats);
5214 }
5215
5216 void updateUsageStats(ActivityRecord component, boolean resumed) {
5217 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5218 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5219 mH.sendMessage(m);
5220 }
5221
5222 void setBooting(boolean booting) {
5223 mAmInternal.setBooting(booting);
5224 }
5225
5226 boolean isBooting() {
5227 return mAmInternal.isBooting();
5228 }
5229
5230 void setBooted(boolean booted) {
5231 mAmInternal.setBooted(booted);
5232 }
5233
5234 boolean isBooted() {
5235 return mAmInternal.isBooted();
5236 }
5237
5238 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5239 mH.post(() -> {
5240 if (finishBooting) {
5241 mAmInternal.finishBooting();
5242 }
5243 if (enableScreen) {
5244 mInternal.enableScreenAfterBoot(isBooted());
5245 }
5246 });
5247 }
5248
5249 void setHeavyWeightProcess(ActivityRecord root) {
5250 mHeavyWeightProcess = root.app;
5251 final Message m = PooledLambda.obtainMessage(
5252 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5253 root.app, root.intent, root.userId);
5254 mH.sendMessage(m);
5255 }
5256
5257 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5258 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5259 return;
5260 }
5261
5262 mHeavyWeightProcess = null;
5263 final Message m = PooledLambda.obtainMessage(
5264 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5265 proc.mUserId);
5266 mH.sendMessage(m);
5267 }
5268
5269 private void cancelHeavyWeightProcessNotification(int userId) {
5270 final INotificationManager inm = NotificationManager.getService();
5271 if (inm == null) {
5272 return;
5273 }
5274 try {
5275 inm.cancelNotificationWithTag("android", null,
5276 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5277 } catch (RuntimeException e) {
5278 Slog.w(TAG, "Error canceling notification for service", e);
5279 } catch (RemoteException e) {
5280 }
5281
5282 }
5283
5284 private void postHeavyWeightProcessNotification(
5285 WindowProcessController proc, Intent intent, int userId) {
5286 if (proc == null) {
5287 return;
5288 }
5289
5290 final INotificationManager inm = NotificationManager.getService();
5291 if (inm == null) {
5292 return;
5293 }
5294
5295 try {
5296 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5297 String text = mContext.getString(R.string.heavy_weight_notification,
5298 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5299 Notification notification =
5300 new Notification.Builder(context,
5301 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5302 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5303 .setWhen(0)
5304 .setOngoing(true)
5305 .setTicker(text)
5306 .setColor(mContext.getColor(
5307 com.android.internal.R.color.system_notification_accent_color))
5308 .setContentTitle(text)
5309 .setContentText(
5310 mContext.getText(R.string.heavy_weight_notification_detail))
5311 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5312 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5313 new UserHandle(userId)))
5314 .build();
5315 try {
5316 inm.enqueueNotificationWithTag("android", "android", null,
5317 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5318 } catch (RuntimeException e) {
5319 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5320 } catch (RemoteException e) {
5321 }
5322 } catch (PackageManager.NameNotFoundException e) {
5323 Slog.w(TAG, "Unable to create context for heavy notification", e);
5324 }
5325
5326 }
5327
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005328 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5329 IBinder token, String resultWho, int requestCode, Intent[] intents,
5330 String[] resolvedTypes, int flags, Bundle bOptions) {
5331
5332 ActivityRecord activity = null;
5333 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5334 activity = ActivityRecord.isInStackLocked(token);
5335 if (activity == null) {
5336 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5337 return null;
5338 }
5339 if (activity.finishing) {
5340 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5341 return null;
5342 }
5343 }
5344
5345 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5346 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5347 bOptions);
5348 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5349 if (noCreate) {
5350 return rec;
5351 }
5352 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5353 if (activity.pendingResults == null) {
5354 activity.pendingResults = new HashSet<>();
5355 }
5356 activity.pendingResults.add(rec.ref);
5357 }
5358 return rec;
5359 }
5360
Andrii Kulian52d255c2018-07-13 11:32:19 -07005361 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005362 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005363 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005364 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5365 mCurAppTimeTracker.start(resumedActivity.packageName);
5366 }
5367 }
5368
5369 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5370 if (mTracedResumedActivity != null) {
5371 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5372 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5373 }
5374 if (resumed != null) {
5375 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5376 constructResumedTraceName(resumed.packageName), 0);
5377 }
5378 mTracedResumedActivity = resumed;
5379 }
5380
5381 private String constructResumedTraceName(String packageName) {
5382 return "focused app: " + packageName;
5383 }
5384
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005385 /** Applies latest configuration and/or visibility updates if needed. */
5386 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5387 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005388 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005389 // mainStack is null during startup.
5390 if (mainStack != null) {
5391 if (changes != 0 && starting == null) {
5392 // If the configuration changed, and the caller is not already
5393 // in the process of starting an activity, then find the top
5394 // activity to check if its configuration needs to change.
5395 starting = mainStack.topRunningActivityLocked();
5396 }
5397
5398 if (starting != null) {
5399 kept = starting.ensureActivityConfiguration(changes,
5400 false /* preserveWindow */);
5401 // And we need to make sure at this point that all other activities
5402 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005403 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005404 !PRESERVE_WINDOWS);
5405 }
5406 }
5407
5408 return kept;
5409 }
5410
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005411 void scheduleAppGcsLocked() {
5412 mH.post(() -> mAmInternal.scheduleAppGcs());
5413 }
5414
Wale Ogunwale53783742018-09-16 10:21:51 -07005415 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5416 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5417 }
5418
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005419 /**
5420 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5421 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5422 * on demand.
5423 */
5424 IPackageManager getPackageManager() {
5425 return AppGlobals.getPackageManager();
5426 }
5427
5428 PackageManagerInternal getPackageManagerInternalLocked() {
5429 if (mPmInternal == null) {
5430 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5431 }
5432 return mPmInternal;
5433 }
5434
Wale Ogunwale008163e2018-07-23 23:11:08 -07005435 AppWarnings getAppWarningsLocked() {
5436 return mAppWarnings;
5437 }
5438
Wale Ogunwale214f3482018-10-04 11:00:47 -07005439 Intent getHomeIntent() {
5440 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5441 intent.setComponent(mTopComponent);
5442 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5443 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5444 intent.addCategory(Intent.CATEGORY_HOME);
5445 }
5446 return intent;
5447 }
5448
Wale Ogunwale214f3482018-10-04 11:00:47 -07005449 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5450 if (info == null) return null;
5451 ApplicationInfo newInfo = new ApplicationInfo(info);
5452 newInfo.initForUser(userId);
5453 return newInfo;
5454 }
5455
Wale Ogunwale9c103022018-10-18 07:44:54 -07005456 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005457 if (uid == SYSTEM_UID) {
5458 // The system gets to run in any process. If there are multiple processes with the same
5459 // uid, just pick the first (this should never happen).
5460 final SparseArray<WindowProcessController> procs =
5461 mProcessNames.getMap().get(processName);
5462 if (procs == null) return null;
5463 final int procCount = procs.size();
5464 for (int i = 0; i < procCount; i++) {
5465 final int procUid = procs.keyAt(i);
5466 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5467 // Don't use an app process or different user process for system component.
5468 continue;
5469 }
5470 return procs.valueAt(i);
5471 }
5472 }
5473
5474 return mProcessNames.get(processName, uid);
5475 }
5476
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005477 WindowProcessController getProcessController(IApplicationThread thread) {
5478 if (thread == null) {
5479 return null;
5480 }
5481
5482 final IBinder threadBinder = thread.asBinder();
5483 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5484 for (int i = pmap.size()-1; i >= 0; i--) {
5485 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5486 for (int j = procs.size() - 1; j >= 0; j--) {
5487 final WindowProcessController proc = procs.valueAt(j);
5488 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5489 return proc;
5490 }
5491 }
5492 }
5493
5494 return null;
5495 }
5496
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005497 int getUidStateLocked(int uid) {
5498 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5499 }
5500
Wale Ogunwale9de19442018-10-18 19:05:03 -07005501 /**
5502 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5503 * the whitelist
5504 */
5505 String getPendingTempWhitelistTagForUidLocked(int uid) {
5506 return mPendingTempWhitelist.get(uid);
5507 }
5508
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005509 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5510 if (true || Build.IS_USER) {
5511 return;
5512 }
5513
5514 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5515 StrictMode.allowThreadDiskWrites();
5516 try {
5517 File tracesDir = new File("/data/anr");
5518 File tracesFile = null;
5519 try {
5520 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5521
5522 StringBuilder sb = new StringBuilder();
5523 Time tobj = new Time();
5524 tobj.set(System.currentTimeMillis());
5525 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5526 sb.append(": ");
5527 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5528 sb.append(" since ");
5529 sb.append(msg);
5530 FileOutputStream fos = new FileOutputStream(tracesFile);
5531 fos.write(sb.toString().getBytes());
5532 if (app == null) {
5533 fos.write("\n*** No application process!".getBytes());
5534 }
5535 fos.close();
5536 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5537 } catch (IOException e) {
5538 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5539 return;
5540 }
5541
5542 if (app != null && app.getPid() > 0) {
5543 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5544 firstPids.add(app.getPid());
5545 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5546 }
5547
5548 File lastTracesFile = null;
5549 File curTracesFile = null;
5550 for (int i=9; i>=0; i--) {
5551 String name = String.format(Locale.US, "slow%02d.txt", i);
5552 curTracesFile = new File(tracesDir, name);
5553 if (curTracesFile.exists()) {
5554 if (lastTracesFile != null) {
5555 curTracesFile.renameTo(lastTracesFile);
5556 } else {
5557 curTracesFile.delete();
5558 }
5559 }
5560 lastTracesFile = curTracesFile;
5561 }
5562 tracesFile.renameTo(curTracesFile);
5563 } finally {
5564 StrictMode.setThreadPolicy(oldPolicy);
5565 }
5566 }
5567
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005568 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005570
5571
Wale Ogunwale98875612018-10-12 07:53:02 -07005572 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5573 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005575 public H() {
5576 super(DisplayThread.get().getLooper());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005577 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005578
5579 @Override
5580 public void handleMessage(Message msg) {
5581 switch (msg.what) {
5582 case REPORT_TIME_TRACKER_MSG: {
5583 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5584 tracker.deliverResult(mContext);
5585 } break;
5586 }
5587 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005588 }
5589
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005590 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005592
5593 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005594 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005595 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005596
5597 @Override
5598 public void handleMessage(Message msg) {
5599 switch (msg.what) {
5600 case DISMISS_DIALOG_UI_MSG: {
5601 final Dialog d = (Dialog) msg.obj;
5602 d.dismiss();
5603 break;
5604 }
5605 }
5606 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005607 }
5608
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005609 final class LocalService extends ActivityTaskManagerInternal {
5610 @Override
5611 public SleepToken acquireSleepToken(String tag, int displayId) {
5612 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005613 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005614 }
5615
5616 @Override
5617 public ComponentName getHomeActivityForUser(int userId) {
5618 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005619 final ActivityRecord homeActivity =
5620 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005621 return homeActivity == null ? null : homeActivity.realActivity;
5622 }
5623 }
5624
5625 @Override
5626 public void onLocalVoiceInteractionStarted(IBinder activity,
5627 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5628 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005629 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005630 }
5631 }
5632
5633 @Override
5634 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5635 synchronized (mGlobalLock) {
5636 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5637 reasons, timestamp);
5638 }
5639 }
5640
5641 @Override
5642 public void notifyAppTransitionFinished() {
5643 synchronized (mGlobalLock) {
5644 mStackSupervisor.notifyAppTransitionDone();
5645 }
5646 }
5647
5648 @Override
5649 public void notifyAppTransitionCancelled() {
5650 synchronized (mGlobalLock) {
5651 mStackSupervisor.notifyAppTransitionDone();
5652 }
5653 }
5654
5655 @Override
5656 public List<IBinder> getTopVisibleActivities() {
5657 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005658 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005659 }
5660 }
5661
5662 @Override
5663 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5664 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005665 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005666 }
5667 }
5668
5669 @Override
5670 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5671 Bundle bOptions) {
5672 Preconditions.checkNotNull(intents, "intents");
5673 final String[] resolvedTypes = new String[intents.length];
5674
5675 // UID of the package on user userId.
5676 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5677 // packageUid may not be initialized.
5678 int packageUid = 0;
5679 final long ident = Binder.clearCallingIdentity();
5680
5681 try {
5682 for (int i = 0; i < intents.length; i++) {
5683 resolvedTypes[i] =
5684 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5685 }
5686
5687 packageUid = AppGlobals.getPackageManager().getPackageUid(
5688 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5689 } catch (RemoteException e) {
5690 // Shouldn't happen.
5691 } finally {
5692 Binder.restoreCallingIdentity(ident);
5693 }
5694
5695 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005696 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005697 packageUid, packageName,
5698 intents, resolvedTypes, null /* resultTo */,
5699 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005700 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005701 }
5702 }
5703
5704 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005705 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5706 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5707 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5708 synchronized (mGlobalLock) {
5709 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5710 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5711 originatingPendingIntent);
5712 }
5713 }
5714
5715 @Override
5716 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5717 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5718 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5719 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5720 PendingIntentRecord originatingPendingIntent) {
5721 synchronized (mGlobalLock) {
5722 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5723 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5724 requestCode, startFlags, options, userId, inTask, reason,
5725 validateIncomingUser, originatingPendingIntent);
5726 }
5727 }
5728
5729 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005730 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5731 Intent intent, Bundle options, int userId) {
5732 return ActivityTaskManagerService.this.startActivityAsUser(
5733 caller, callerPacakge, intent,
5734 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5735 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5736 false /*validateIncomingUser*/);
5737 }
5738
5739 @Override
lumark588a3e82018-07-20 18:53:54 +08005740 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005741 synchronized (mGlobalLock) {
5742
5743 // We might change the visibilities here, so prepare an empty app transition which
5744 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005745 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005746 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005747 if (activityDisplay == null) {
5748 return;
5749 }
5750 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005751 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005752 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005753 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005754 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005755 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005756
5757 // If there was a transition set already we don't want to interfere with it as we
5758 // might be starting it too early.
5759 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005760 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005761 }
5762 }
5763 if (callback != null) {
5764 callback.run();
5765 }
5766 }
5767
5768 @Override
5769 public void notifyKeyguardTrustedChanged() {
5770 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005771 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005772 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005773 }
5774 }
5775 }
5776
5777 /**
5778 * Called after virtual display Id is updated by
5779 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5780 * {@param vrVr2dDisplayId}.
5781 */
5782 @Override
5783 public void setVr2dDisplayId(int vr2dDisplayId) {
5784 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5785 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005786 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005787 }
5788 }
5789
5790 @Override
5791 public void setFocusedActivity(IBinder token) {
5792 synchronized (mGlobalLock) {
5793 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5794 if (r == null) {
5795 throw new IllegalArgumentException(
5796 "setFocusedActivity: No activity record matching token=" + token);
5797 }
Louis Chang19443452018-10-09 12:10:21 +08005798 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005799 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005800 }
5801 }
5802 }
5803
5804 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005805 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005806 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005807 }
5808
5809 @Override
5810 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005811 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005812 }
5813
5814 @Override
5815 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005816 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005817 }
5818
5819 @Override
5820 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5821 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5822 }
5823
5824 @Override
5825 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005826 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005827 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005828
5829 @Override
5830 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5831 synchronized (mGlobalLock) {
5832 mActiveVoiceInteractionServiceComponent = component;
5833 }
5834 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005835
5836 @Override
5837 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5838 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5839 return;
5840 }
5841 synchronized (mGlobalLock) {
5842 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5843 if (types == null) {
5844 if (uid < 0) {
5845 return;
5846 }
5847 types = new ArrayMap<>();
5848 mAllowAppSwitchUids.put(userId, types);
5849 }
5850 if (uid < 0) {
5851 types.remove(type);
5852 } else {
5853 types.put(type, uid);
5854 }
5855 }
5856 }
5857
5858 @Override
5859 public void onUserStopped(int userId) {
5860 synchronized (mGlobalLock) {
5861 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5862 mAllowAppSwitchUids.remove(userId);
5863 }
5864 }
5865
5866 @Override
5867 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5868 synchronized (mGlobalLock) {
5869 return ActivityTaskManagerService.this.isGetTasksAllowed(
5870 caller, callingPid, callingUid);
5871 }
5872 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005873
5874 @Override
5875 public void onProcessAdded(WindowProcessController proc) {
5876 synchronized (mGlobalLock) {
5877 mProcessNames.put(proc.mName, proc.mUid, proc);
5878 }
5879 }
5880
5881 @Override
5882 public void onProcessRemoved(String name, int uid) {
5883 synchronized (mGlobalLock) {
5884 mProcessNames.remove(name, uid);
5885 }
5886 }
5887
5888 @Override
5889 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5890 synchronized (mGlobalLock) {
5891 if (proc == mHomeProcess) {
5892 mHomeProcess = null;
5893 }
5894 if (proc == mPreviousProcess) {
5895 mPreviousProcess = null;
5896 }
5897 }
5898 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005899
5900 @Override
5901 public int getTopProcessState() {
5902 synchronized (mGlobalLock) {
5903 return mTopProcessState;
5904 }
5905 }
5906
5907 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005908 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5909 synchronized (mGlobalLock) {
5910 return proc == mHeavyWeightProcess;
5911 }
5912 }
5913
5914 @Override
5915 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5916 synchronized (mGlobalLock) {
5917 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5918 }
5919 }
5920
5921 @Override
5922 public void finishHeavyWeightApp() {
5923 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005924 if (mHeavyWeightProcess != null) {
5925 mHeavyWeightProcess.finishActivities();
5926 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005927 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5928 mHeavyWeightProcess);
5929 }
5930 }
5931
5932 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005933 public boolean isSleeping() {
5934 synchronized (mGlobalLock) {
5935 return isSleepingLocked();
5936 }
5937 }
5938
5939 @Override
5940 public boolean isShuttingDown() {
5941 synchronized (mGlobalLock) {
5942 return mShuttingDown;
5943 }
5944 }
5945
5946 @Override
5947 public boolean shuttingDown(boolean booted, int timeout) {
5948 synchronized (mGlobalLock) {
5949 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005950 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005951 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005952 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005953 return mStackSupervisor.shutdownLocked(timeout);
5954 }
5955 }
5956
5957 @Override
5958 public void enableScreenAfterBoot(boolean booted) {
5959 synchronized (mGlobalLock) {
5960 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5961 SystemClock.uptimeMillis());
5962 mWindowManager.enableScreenAfterBoot();
5963 updateEventDispatchingLocked(booted);
5964 }
5965 }
5966
5967 @Override
5968 public boolean showStrictModeViolationDialog() {
5969 synchronized (mGlobalLock) {
5970 return mShowDialogs && !mSleeping && !mShuttingDown;
5971 }
5972 }
5973
5974 @Override
5975 public void showSystemReadyErrorDialogsIfNeeded() {
5976 synchronized (mGlobalLock) {
5977 try {
5978 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5979 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5980 + " data partition or your device will be unstable.");
5981 mUiHandler.post(() -> {
5982 if (mShowDialogs) {
5983 AlertDialog d = new BaseErrorDialog(mUiContext);
5984 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5985 d.setCancelable(false);
5986 d.setTitle(mUiContext.getText(R.string.android_system_label));
5987 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5988 d.setButton(DialogInterface.BUTTON_POSITIVE,
5989 mUiContext.getText(R.string.ok),
5990 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5991 d.show();
5992 }
5993 });
5994 }
5995 } catch (RemoteException e) {
5996 }
5997
5998 if (!Build.isBuildConsistent()) {
5999 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6000 mUiHandler.post(() -> {
6001 if (mShowDialogs) {
6002 AlertDialog d = new BaseErrorDialog(mUiContext);
6003 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6004 d.setCancelable(false);
6005 d.setTitle(mUiContext.getText(R.string.android_system_label));
6006 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6007 d.setButton(DialogInterface.BUTTON_POSITIVE,
6008 mUiContext.getText(R.string.ok),
6009 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6010 d.show();
6011 }
6012 });
6013 }
6014 }
6015 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006016
6017 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006018 public void onProcessMapped(int pid, WindowProcessController proc) {
6019 synchronized (mGlobalLock) {
6020 mPidMap.put(pid, proc);
6021 }
6022 }
6023
6024 @Override
6025 public void onProcessUnMapped(int pid) {
6026 synchronized (mGlobalLock) {
6027 mPidMap.remove(pid);
6028 }
6029 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006030
6031 @Override
6032 public void onPackageDataCleared(String name) {
6033 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006034 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006035 mAppWarnings.onPackageDataCleared(name);
6036 }
6037 }
6038
6039 @Override
6040 public void onPackageUninstalled(String name) {
6041 synchronized (mGlobalLock) {
6042 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006043 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006044 }
6045 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006046
6047 @Override
6048 public void onPackageAdded(String name, boolean replacing) {
6049 synchronized (mGlobalLock) {
6050 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6051 }
6052 }
6053
6054 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006055 public void onPackageReplaced(ApplicationInfo aInfo) {
6056 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006057 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006058 }
6059 }
6060
6061 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006062 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6063 synchronized (mGlobalLock) {
6064 return compatibilityInfoForPackageLocked(ai);
6065 }
6066 }
6067
Yunfan Chen75157d72018-07-27 14:47:21 +09006068 /**
6069 * Set the corresponding display information for the process global configuration. To be
6070 * called when we need to show IME on a different display.
6071 *
6072 * @param pid The process id associated with the IME window.
6073 * @param displayId The ID of the display showing the IME.
6074 */
6075 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006076 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006077 if (pid == MY_PID || pid < 0) {
6078 if (DEBUG_CONFIGURATION) {
6079 Slog.w(TAG,
6080 "Trying to update display configuration for system/invalid process.");
6081 }
6082 return;
6083 }
6084 mH.post(() -> {
6085 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006086 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006087 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006088 if (activityDisplay == null) {
6089 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006090 if (DEBUG_CONFIGURATION) {
6091 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006092 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006093 }
6094 return;
6095 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006096 final WindowProcessController process = mPidMap.get(pid);
6097 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006098 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006099 Slog.w(TAG, "Trying to update display configuration for invalid "
6100 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006101 }
6102 return;
6103 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006104 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006105 }
6106 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006107
Yunfan Chen75157d72018-07-27 14:47:21 +09006108 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006109
6110 @Override
6111 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6112 int requestCode, int resultCode, Intent data) {
6113 synchronized (mGlobalLock) {
6114 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6115 if (r != null && r.getStack() != null) {
6116 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6117 resultCode, data);
6118 }
6119 }
6120 }
6121
6122 @Override
6123 public void clearPendingResultForActivity(IBinder activityToken,
6124 WeakReference<PendingIntentRecord> pir) {
6125 synchronized (mGlobalLock) {
6126 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6127 if (r != null && r.pendingResults != null) {
6128 r.pendingResults.remove(pir);
6129 }
6130 }
6131 }
6132
6133 @Override
6134 public IIntentSender getIntentSender(int type, String packageName,
6135 int callingUid, int userId, IBinder token, String resultWho,
6136 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6137 Bundle bOptions) {
6138 synchronized (mGlobalLock) {
6139 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6140 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6141 }
6142 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006143
6144 @Override
6145 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6146 synchronized (mGlobalLock) {
6147 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6148 if (r == null) {
6149 return null;
6150 }
6151 if (r.mServiceConnectionsHolder == null) {
6152 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6153 ActivityTaskManagerService.this, r);
6154 }
6155
6156 return r.mServiceConnectionsHolder;
6157 }
6158 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006159
6160 @Override
6161 public Intent getHomeIntent() {
6162 synchronized (mGlobalLock) {
6163 return ActivityTaskManagerService.this.getHomeIntent();
6164 }
6165 }
6166
6167 @Override
6168 public boolean startHomeActivity(int userId, String reason) {
6169 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006170 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006171 }
6172 }
6173
6174 @Override
6175 public boolean startHomeOnAllDisplays(int userId, String reason) {
6176 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006177 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006178 }
6179 }
6180
6181 @Override
6182 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6183 synchronized (mGlobalLock) {
6184 if (mFactoryTest == FACTORY_TEST_OFF) {
6185 return false;
6186 }
6187 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6188 && wpc.mName.equals(mTopComponent.getPackageName())) {
6189 return true;
6190 }
6191 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6192 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6193 }
6194 }
6195
6196 @Override
6197 public void updateTopComponentForFactoryTest() {
6198 synchronized (mGlobalLock) {
6199 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6200 return;
6201 }
6202 final ResolveInfo ri = mContext.getPackageManager()
6203 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6204 final CharSequence errorMsg;
6205 if (ri != null) {
6206 final ActivityInfo ai = ri.activityInfo;
6207 final ApplicationInfo app = ai.applicationInfo;
6208 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6209 mTopAction = Intent.ACTION_FACTORY_TEST;
6210 mTopData = null;
6211 mTopComponent = new ComponentName(app.packageName, ai.name);
6212 errorMsg = null;
6213 } else {
6214 errorMsg = mContext.getResources().getText(
6215 com.android.internal.R.string.factorytest_not_system);
6216 }
6217 } else {
6218 errorMsg = mContext.getResources().getText(
6219 com.android.internal.R.string.factorytest_no_action);
6220 }
6221 if (errorMsg == null) {
6222 return;
6223 }
6224
6225 mTopAction = null;
6226 mTopData = null;
6227 mTopComponent = null;
6228 mUiHandler.post(() -> {
6229 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6230 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006231 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006232 });
6233 }
6234 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006235
6236 @Override
6237 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6238 Runnable finishInstrumentationCallback) {
6239 synchronized (mGlobalLock) {
6240 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006241 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006242
6243 wpc.clearRecentTasks();
6244 wpc.clearActivities();
6245
6246 if (wpc.isInstrumenting()) {
6247 finishInstrumentationCallback.run();
6248 }
6249
6250 mWindowManager.deferSurfaceLayout();
6251 try {
6252 if (!restarting && hasVisibleActivities
Wale Ogunwaled32da472018-11-16 07:19:28 -08006253 && !mRootActivityContainer.resumeFocusedStacksTopActivities()) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006254 // If there was nothing to resume, and we are not already restarting this
6255 // process, but there is a visible activity that is hosted by the process...
6256 // then make sure all visible activities are running, taking care of
6257 // restarting this process.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006258 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006259 }
6260 } finally {
6261 mWindowManager.continueSurfaceLayout();
6262 }
6263 }
6264 }
6265
6266 @Override
6267 public void closeSystemDialogs(String reason) {
6268 enforceNotIsolatedCaller("closeSystemDialogs");
6269
6270 final int pid = Binder.getCallingPid();
6271 final int uid = Binder.getCallingUid();
6272 final long origId = Binder.clearCallingIdentity();
6273 try {
6274 synchronized (mGlobalLock) {
6275 // Only allow this from foreground processes, so that background
6276 // applications can't abuse it to prevent system UI from being shown.
6277 if (uid >= FIRST_APPLICATION_UID) {
6278 final WindowProcessController proc = mPidMap.get(pid);
6279 if (!proc.isPerceptible()) {
6280 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6281 + " from background process " + proc);
6282 return;
6283 }
6284 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006285 mWindowManager.closeSystemDialogs(reason);
6286
Wale Ogunwaled32da472018-11-16 07:19:28 -08006287 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006288 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006289 // Call into AM outside the synchronized block.
6290 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006291 } finally {
6292 Binder.restoreCallingIdentity(origId);
6293 }
6294 }
6295
6296 @Override
6297 public void cleanupDisabledPackageComponents(
6298 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6299 synchronized (mGlobalLock) {
6300 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006301 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006302 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006303 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006304 mStackSupervisor.scheduleIdleLocked();
6305 }
6306
6307 // Clean-up disabled tasks
6308 getRecentTasks().cleanupDisabledPackageTasksLocked(
6309 packageName, disabledClasses, userId);
6310 }
6311 }
6312
6313 @Override
6314 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6315 int userId) {
6316 synchronized (mGlobalLock) {
6317
6318 boolean didSomething =
6319 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006320 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006321 null, doit, evenPersistent, userId);
6322 return didSomething;
6323 }
6324 }
6325
6326 @Override
6327 public void resumeTopActivities(boolean scheduleIdle) {
6328 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006329 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006330 if (scheduleIdle) {
6331 mStackSupervisor.scheduleIdleLocked();
6332 }
6333 }
6334 }
6335
6336 @Override
6337 public void preBindApplication(WindowProcessController wpc) {
6338 synchronized (mGlobalLock) {
6339 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6340 }
6341 }
6342
6343 @Override
6344 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6345 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006346 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006347 }
6348 }
6349
6350 @Override
6351 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6352 try {
6353 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6354 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6355 }
6356 } catch (RemoteException ex) {
6357 throw new SecurityException("Fail to check is caller a privileged app", ex);
6358 }
6359
6360 synchronized (mGlobalLock) {
6361 final long ident = Binder.clearCallingIdentity();
6362 try {
6363 if (mAmInternal.shouldConfirmCredentials(userId)) {
6364 if (mKeyguardController.isKeyguardLocked()) {
6365 // Showing launcher to avoid user entering credential twice.
6366 startHomeActivity(currentUserId, "notifyLockedProfile");
6367 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006368 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006369 }
6370 } finally {
6371 Binder.restoreCallingIdentity(ident);
6372 }
6373 }
6374 }
6375
6376 @Override
6377 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6378 mAmInternal.enforceCallingPermission(
6379 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6380
6381 synchronized (mGlobalLock) {
6382 final long ident = Binder.clearCallingIdentity();
6383 try {
6384 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6385 FLAG_ACTIVITY_TASK_ON_HOME);
6386 ActivityOptions activityOptions = options != null
6387 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006388 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006389 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006390 if (homeActivity != null) {
6391 activityOptions.setLaunchTaskId(homeActivity.getTask().taskId);
6392 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006393 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6394 UserHandle.CURRENT);
6395 } finally {
6396 Binder.restoreCallingIdentity(ident);
6397 }
6398 }
6399 }
6400
6401 @Override
6402 public void writeActivitiesToProto(ProtoOutputStream proto) {
6403 synchronized (mGlobalLock) {
6404 // The output proto of "activity --proto activities"
6405 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006406 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006407 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6408 }
6409 }
6410
6411 @Override
6412 public void saveANRState(String reason) {
6413 synchronized (mGlobalLock) {
6414 final StringWriter sw = new StringWriter();
6415 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6416 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6417 if (reason != null) {
6418 pw.println(" Reason: " + reason);
6419 }
6420 pw.println();
6421 getActivityStartController().dump(pw, " ", null);
6422 pw.println();
6423 pw.println("-------------------------------------------------------------------------------");
6424 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6425 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6426 "" /* header */);
6427 pw.println();
6428 pw.close();
6429
6430 mLastANRState = sw.toString();
6431 }
6432 }
6433
6434 @Override
6435 public void clearSavedANRState() {
6436 synchronized (mGlobalLock) {
6437 mLastANRState = null;
6438 }
6439 }
6440
6441 @Override
6442 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6443 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6444 synchronized (mGlobalLock) {
6445 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6446 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6447 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6448 dumpLastANRLocked(pw);
6449 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6450 dumpLastANRTracesLocked(pw);
6451 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6452 dumpActivityStarterLocked(pw, dumpPackage);
6453 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6454 dumpActivityContainersLocked(pw);
6455 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6456 if (getRecentTasks() != null) {
6457 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6458 }
6459 }
6460 }
6461 }
6462
6463 @Override
6464 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6465 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6466 int wakefulness) {
6467 synchronized (mGlobalLock) {
6468 if (mHomeProcess != null && (dumpPackage == null
6469 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6470 if (needSep) {
6471 pw.println();
6472 needSep = false;
6473 }
6474 pw.println(" mHomeProcess: " + mHomeProcess);
6475 }
6476 if (mPreviousProcess != null && (dumpPackage == null
6477 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6478 if (needSep) {
6479 pw.println();
6480 needSep = false;
6481 }
6482 pw.println(" mPreviousProcess: " + mPreviousProcess);
6483 }
6484 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6485 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6486 StringBuilder sb = new StringBuilder(128);
6487 sb.append(" mPreviousProcessVisibleTime: ");
6488 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6489 pw.println(sb);
6490 }
6491 if (mHeavyWeightProcess != null && (dumpPackage == null
6492 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6493 if (needSep) {
6494 pw.println();
6495 needSep = false;
6496 }
6497 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6498 }
6499 if (dumpPackage == null) {
6500 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006501 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006502 }
6503 if (dumpAll) {
6504 if (dumpPackage == null) {
6505 pw.println(" mConfigWillChange: "
6506 + getTopDisplayFocusedStack().mConfigWillChange);
6507 }
6508 if (mCompatModePackages.getPackages().size() > 0) {
6509 boolean printed = false;
6510 for (Map.Entry<String, Integer> entry
6511 : mCompatModePackages.getPackages().entrySet()) {
6512 String pkg = entry.getKey();
6513 int mode = entry.getValue();
6514 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6515 continue;
6516 }
6517 if (!printed) {
6518 pw.println(" mScreenCompatPackages:");
6519 printed = true;
6520 }
6521 pw.println(" " + pkg + ": " + mode);
6522 }
6523 }
6524 }
6525
6526 if (dumpPackage == null) {
6527 pw.println(" mWakefulness="
6528 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006529 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006530 if (mRunningVoice != null) {
6531 pw.println(" mRunningVoice=" + mRunningVoice);
6532 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6533 }
6534 pw.println(" mSleeping=" + mSleeping);
6535 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6536 pw.println(" mVrController=" + mVrController);
6537 }
6538 if (mCurAppTimeTracker != null) {
6539 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6540 }
6541 if (mAllowAppSwitchUids.size() > 0) {
6542 boolean printed = false;
6543 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6544 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6545 for (int j = 0; j < types.size(); j++) {
6546 if (dumpPackage == null ||
6547 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6548 if (needSep) {
6549 pw.println();
6550 needSep = false;
6551 }
6552 if (!printed) {
6553 pw.println(" mAllowAppSwitchUids:");
6554 printed = true;
6555 }
6556 pw.print(" User ");
6557 pw.print(mAllowAppSwitchUids.keyAt(i));
6558 pw.print(": Type ");
6559 pw.print(types.keyAt(j));
6560 pw.print(" = ");
6561 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6562 pw.println();
6563 }
6564 }
6565 }
6566 }
6567 if (dumpPackage == null) {
6568 if (mController != null) {
6569 pw.println(" mController=" + mController
6570 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6571 }
6572 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6573 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6574 }
6575
6576 return needSep;
6577 }
6578 }
6579
6580 @Override
6581 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6582 synchronized (mGlobalLock) {
6583 if (dumpPackage == null) {
6584 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6585 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6586 writeSleepStateToProto(proto);
6587 if (mController != null) {
6588 final long token = proto.start(CONTROLLER);
6589 proto.write(CONTROLLER, mController.toString());
6590 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6591 proto.end(token);
6592 }
6593 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6594 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6595 }
6596
6597 if (mHomeProcess != null && (dumpPackage == null
6598 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006599 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006600 }
6601
6602 if (mPreviousProcess != null && (dumpPackage == null
6603 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006604 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006605 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6606 }
6607
6608 if (mHeavyWeightProcess != null && (dumpPackage == null
6609 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006610 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006611 }
6612
6613 for (Map.Entry<String, Integer> entry
6614 : mCompatModePackages.getPackages().entrySet()) {
6615 String pkg = entry.getKey();
6616 int mode = entry.getValue();
6617 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6618 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6619 proto.write(PACKAGE, pkg);
6620 proto.write(MODE, mode);
6621 proto.end(compatToken);
6622 }
6623 }
6624
6625 if (mCurAppTimeTracker != null) {
6626 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6627 }
6628
6629 }
6630 }
6631
6632 @Override
6633 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6634 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6635 boolean dumpFocusedStackOnly) {
6636 synchronized (mGlobalLock) {
6637 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6638 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6639 }
6640 }
6641
6642 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006643 public void dumpForOom(PrintWriter pw) {
6644 synchronized (mGlobalLock) {
6645 pw.println(" mHomeProcess: " + mHomeProcess);
6646 pw.println(" mPreviousProcess: " + mPreviousProcess);
6647 if (mHeavyWeightProcess != null) {
6648 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6649 }
6650 }
6651 }
6652
6653 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654 public boolean canGcNow() {
6655 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006656 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006657 }
6658 }
6659
6660 @Override
6661 public WindowProcessController getTopApp() {
6662 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006663 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006664 return top != null ? top.app : null;
6665 }
6666 }
6667
6668 @Override
6669 public void rankTaskLayersIfNeeded() {
6670 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006671 if (mRootActivityContainer != null) {
6672 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006673 }
6674 }
6675 }
6676
6677 @Override
6678 public void scheduleDestroyAllActivities(String reason) {
6679 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006680 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006681 }
6682 }
6683
6684 @Override
6685 public void removeUser(int userId) {
6686 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006687 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006688 }
6689 }
6690
6691 @Override
6692 public boolean switchUser(int userId, UserState userState) {
6693 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006694 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006695 }
6696 }
6697
6698 @Override
6699 public void onHandleAppCrash(WindowProcessController wpc) {
6700 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006701 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006702 }
6703 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006704
6705 @Override
6706 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6707 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006708 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006709 }
6710 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006711
6712 @Override
6713 public void onUidActive(int uid, int procState) {
6714 synchronized (mGlobalLock) {
6715 mActiveUids.put(uid, procState);
6716 }
6717 }
6718
6719 @Override
6720 public void onUidInactive(int uid) {
6721 synchronized (mGlobalLock) {
6722 mActiveUids.remove(uid);
6723 }
6724 }
6725
6726 @Override
6727 public void onActiveUidsCleared() {
6728 synchronized (mGlobalLock) {
6729 mActiveUids.clear();
6730 }
6731 }
6732
6733 @Override
6734 public void onUidProcStateChanged(int uid, int procState) {
6735 synchronized (mGlobalLock) {
6736 if (mActiveUids.get(uid) != null) {
6737 mActiveUids.put(uid, procState);
6738 }
6739 }
6740 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006741
6742 @Override
6743 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6744 synchronized (mGlobalLock) {
6745 mPendingTempWhitelist.put(uid, tag);
6746 }
6747 }
6748
6749 @Override
6750 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6751 synchronized (mGlobalLock) {
6752 mPendingTempWhitelist.remove(uid);
6753 }
6754 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006755
6756 @Override
6757 public boolean handleAppCrashInActivityController(String processName, int pid,
6758 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6759 Runnable killCrashingAppCallback) {
6760 synchronized (mGlobalLock) {
6761 if (mController == null) {
6762 return false;
6763 }
6764
6765 try {
6766 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6767 stackTrace)) {
6768 killCrashingAppCallback.run();
6769 return true;
6770 }
6771 } catch (RemoteException e) {
6772 mController = null;
6773 Watchdog.getInstance().setActivityController(null);
6774 }
6775 return false;
6776 }
6777 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006778
6779 @Override
6780 public void removeRecentTasksByPackageName(String packageName, int userId) {
6781 synchronized (mGlobalLock) {
6782 mRecentTasks.removeTasksByPackageName(packageName, userId);
6783 }
6784 }
6785
6786 @Override
6787 public void cleanupRecentTasksForUser(int userId) {
6788 synchronized (mGlobalLock) {
6789 mRecentTasks.cleanupLocked(userId);
6790 }
6791 }
6792
6793 @Override
6794 public void loadRecentTasksForUser(int userId) {
6795 synchronized (mGlobalLock) {
6796 mRecentTasks.loadUserRecentsLocked(userId);
6797 }
6798 }
6799
6800 @Override
6801 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6802 synchronized (mGlobalLock) {
6803 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6804 }
6805 }
6806
6807 @Override
6808 public void flushRecentTasks() {
6809 mRecentTasks.flush();
6810 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006811
6812 @Override
6813 public WindowProcessController getHomeProcess() {
6814 synchronized (mGlobalLock) {
6815 return mHomeProcess;
6816 }
6817 }
6818
6819 @Override
6820 public WindowProcessController getPreviousProcess() {
6821 synchronized (mGlobalLock) {
6822 return mPreviousProcess;
6823 }
6824 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006825
6826 @Override
6827 public void clearLockedTasks(String reason) {
6828 synchronized (mGlobalLock) {
6829 getLockTaskController().clearLockedTasks(reason);
6830 }
6831 }
6832
6833 @Override
6834 public void updateUserConfiguration() {
6835 synchronized (mGlobalLock) {
6836 final Configuration configuration = new Configuration(getGlobalConfiguration());
6837 final int currentUserId = mAmInternal.getCurrentUserId();
6838 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6839 configuration, currentUserId, Settings.System.canWrite(mContext));
6840 updateConfigurationLocked(configuration, null /* starting */,
6841 false /* initLocale */, false /* persistent */, currentUserId,
6842 false /* deferResume */);
6843 }
6844 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006845
6846 @Override
6847 public boolean canShowErrorDialogs() {
6848 synchronized (mGlobalLock) {
6849 return mShowDialogs && !mSleeping && !mShuttingDown
6850 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6851 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6852 mAmInternal.getCurrentUserId())
6853 && !(UserManager.isDeviceInDemoMode(mContext)
6854 && mAmInternal.getCurrentUser().isDemo());
6855 }
6856 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006857
6858 @Override
6859 public void setProfileApp(String profileApp) {
6860 synchronized (mGlobalLock) {
6861 mProfileApp = profileApp;
6862 }
6863 }
6864
6865 @Override
6866 public void setProfileProc(WindowProcessController wpc) {
6867 synchronized (mGlobalLock) {
6868 mProfileProc = wpc;
6869 }
6870 }
6871
6872 @Override
6873 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6874 synchronized (mGlobalLock) {
6875 mProfilerInfo = profilerInfo;
6876 }
6877 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006878 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08006879}