blob: d747198bc3f15f1421f113697928eccbe528eb83 [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;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700196import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700197import android.os.SystemClock;
198import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.UserManager;
203import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700204import android.os.storage.IStorageManager;
205import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.provider.Settings;
207import android.service.voice.IVoiceInteractionSession;
208import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900209import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.telecom.TelecomManager;
211import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700212import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700213import android.util.ArrayMap;
214import android.util.EventLog;
215import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700216import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700218import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700220import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700221import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700222import android.view.IRecentsAnimationRunner;
223import android.view.RemoteAnimationAdapter;
224import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700225import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700226
Evan Rosky4505b352018-09-06 11:20:40 -0700227import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700228import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700229import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700232import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700235import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
236import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700237import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700238import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.policy.IKeyguardDismissCallback;
240import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.util.ArrayUtils;
242import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700243import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700244import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700245import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.server.LocalServices;
247import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700248import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800249import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700251import com.android.server.am.ActivityManagerService;
252import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
253import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
254import com.android.server.am.AppTimeTracker;
255import com.android.server.am.BaseErrorDialog;
256import com.android.server.am.EventLogTags;
257import com.android.server.am.PendingIntentController;
258import com.android.server.am.PendingIntentRecord;
259import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900260import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700261import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700262import com.android.server.pm.UserManagerService;
263import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700264import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700265
Wale Ogunwale31913b52018-10-13 08:29:31 -0700266import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700268import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700269import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700271import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700272import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700273import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800274import java.lang.annotation.ElementType;
275import java.lang.annotation.Retention;
276import java.lang.annotation.RetentionPolicy;
277import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700278import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700280import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700281import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400283import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700286import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Map;
288import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289
290/**
291 * System service for managing activities and their containers (task, stacks, displays,... ).
292 *
293 * {@hide}
294 */
295public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700296 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700298 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
299 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
300 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
301 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
302 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700303 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700304
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700306 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700308 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309
Wale Ogunwale98875612018-10-12 07:53:02 -0700310 /** Used to indicate that an app transition should be animated. */
311 static final boolean ANIMATE = true;
312
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700313 /** Hardware-reported OpenGLES version. */
314 final int GL_ES_VERSION;
315
Wale Ogunwale31913b52018-10-13 08:29:31 -0700316 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
317 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
318 public static final String DUMP_LASTANR_CMD = "lastanr" ;
319 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
320 public static final String DUMP_STARTER_CMD = "starter" ;
321 public static final String DUMP_CONTAINERS_CMD = "containers" ;
322 public static final String DUMP_RECENTS_CMD = "recents" ;
323 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
324
Wale Ogunwale64258362018-10-16 15:13:37 -0700325 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
326 public static final int RELAUNCH_REASON_NONE = 0;
327 /** This activity is being relaunched due to windowing mode change. */
328 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
329 /** This activity is being relaunched due to a free-resize operation. */
330 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
331
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700332 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700333
Wale Ogunwalef6733932018-06-27 05:14:34 -0700334 /**
335 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
336 * change at runtime. Use mContext for non-UI purposes.
337 */
338 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700339 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700340 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700342 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700343 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700344 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800345 @VisibleForTesting
346 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 PowerManagerInternal mPowerManagerInternal;
348 private UsageStatsManagerInternal mUsageStatsInternal;
349
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700350 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 IntentFirewall mIntentFirewall;
352
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700353 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800354 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800355 /**
356 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
357 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
358 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
359 *
360 * @see WindowManagerThreadPriorityBooster
361 */
362 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700363 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800364 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700365 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700366 private UserManagerService mUserManager;
367 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700368 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800369 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700370 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700371 /** All processes currently running that might have a window organized by name. */
372 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700373 /** All processes we currently have running mapped by pid */
374 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700375 /** This is the process holding what we currently consider to be the "home" activity. */
376 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700377 /** The currently running heavy-weight process, if any. */
378 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700379 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /**
381 * This is the process holding the activity the user last visited that is in a different process
382 * from the one they are currently in.
383 */
384 WindowProcessController mPreviousProcess;
385 /** The time at which the previous process was last visible. */
386 long mPreviousProcessVisibleTime;
387
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700388 /** List of intents that were used to start the most recent tasks. */
389 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700390 /** State of external calls telling us if the device is awake or asleep. */
391 private boolean mKeyguardShown = false;
392
393 // Wrapper around VoiceInteractionServiceManager
394 private AssistUtils mAssistUtils;
395
396 // VoiceInteraction session ID that changes for each new request except when
397 // being called for multi-window assist in a single session.
398 private int mViSessionId = 1000;
399
400 // How long to wait in getAssistContextExtras for the activity and foreground services
401 // to respond with the result.
402 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
403
404 // How long top wait when going through the modern assist (which doesn't need to block
405 // on getting this result before starting to launch its UI).
406 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
407
408 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
409 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
410
Alison Cichowlas3e340502018-08-07 17:15:01 -0400411 // Permission tokens are used to temporarily granted a trusted app the ability to call
412 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
413 // showing any appropriate error messages to the user.
414 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
415 10 * MINUTE_IN_MILLIS;
416
417 // How long before the service actually expires a token. This is slightly longer than
418 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
419 // expiration exception.
420 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
421 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
422
423 // How long the service will remember expired tokens, for the purpose of providing error
424 // messaging when a client uses an expired token.
425 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
426 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
427
428 // Activity tokens of system activities that are delegating their call to
429 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
430 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
431
432 // Permission tokens that have expired, but we remember for error reporting.
433 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
434
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700435 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
436
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700437 // Keeps track of the active voice interaction service component, notified from
438 // VoiceInteractionManagerService
439 ComponentName mActiveVoiceInteractionServiceComponent;
440
Wale Ogunwalee2172292018-10-25 10:11:10 -0700441 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700442 KeyguardController mKeyguardController;
443 private final ClientLifecycleManager mLifecycleManager;
444 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700445 /** The controller for all operations related to locktask. */
446 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700447 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 boolean mSuppressResizeConfigChanges;
450
451 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
452 new UpdateConfigurationResult();
453
454 static final class UpdateConfigurationResult {
455 // Configuration changes that were updated.
456 int changes;
457 // If the activity was relaunched to match the new configuration.
458 boolean activityRelaunched;
459
460 void reset() {
461 changes = 0;
462 activityRelaunched = false;
463 }
464 }
465
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700466 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700467 private int mConfigurationSeq;
468 // To cache the list of supported system locales
469 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700470
471 /**
472 * Temp object used when global and/or display override configuration is updated. It is also
473 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
474 * anyone...
475 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700476 private Configuration mTempConfig = new Configuration();
477
Wale Ogunwalef6733932018-06-27 05:14:34 -0700478 /** Temporary to avoid allocations. */
479 final StringBuilder mStringBuilder = new StringBuilder(256);
480
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 // Amount of time after a call to stopAppSwitches() during which we will
482 // prevent further untrusted switches from happening.
483 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
484
485 /**
486 * The time at which we will allow normal application switches again,
487 * after a call to {@link #stopAppSwitches()}.
488 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 /**
491 * This is set to true after the first switch after mAppSwitchesAllowedTime
492 * is set; any switches after that will clear the time.
493 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495
496 IActivityController mController = null;
497 boolean mControllerIsAMonkey = false;
498
Wale Ogunwale214f3482018-10-04 11:00:47 -0700499 final int mFactoryTest;
500
501 /** Used to control how we initialize the service. */
502 ComponentName mTopComponent;
503 String mTopAction = Intent.ACTION_MAIN;
504 String mTopData;
505
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800506 /** Profiling app information. */
507 String mProfileApp = null;
508 WindowProcessController mProfileProc = null;
509 ProfilerInfo mProfilerInfo = null;
510
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700512 * Dump of the activity state at the time of the last ANR. Cleared after
513 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
514 */
515 String mLastANRState;
516
517 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 * Used to retain an update lock when the foreground activity is in
519 * immersive mode.
520 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700521 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522
523 /**
524 * Packages that are being allowed to perform unrestricted app switches. Mapping is
525 * User -> Type -> uid.
526 */
527 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
528
529 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700530 private int mThumbnailWidth;
531 private int mThumbnailHeight;
532 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533
534 /**
535 * Flag that indicates if multi-window is enabled.
536 *
537 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
538 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
539 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
540 * At least one of the forms of multi-window must be enabled in order for this flag to be
541 * initialized to 'true'.
542 *
543 * @see #mSupportsSplitScreenMultiWindow
544 * @see #mSupportsFreeformWindowManagement
545 * @see #mSupportsPictureInPicture
546 * @see #mSupportsMultiDisplay
547 */
548 boolean mSupportsMultiWindow;
549 boolean mSupportsSplitScreenMultiWindow;
550 boolean mSupportsFreeformWindowManagement;
551 boolean mSupportsPictureInPicture;
552 boolean mSupportsMultiDisplay;
553 boolean mForceResizableActivities;
554
555 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
556
557 // VR Vr2d Display Id.
558 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700559
Wale Ogunwalef6733932018-06-27 05:14:34 -0700560 /**
561 * Set while we are wanting to sleep, to prevent any
562 * activities from being started/resumed.
563 *
564 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
565 *
566 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
567 * while in the sleep state until there is a pending transition out of sleep, in which case
568 * mSleeping is set to false, and remains false while awake.
569 *
570 * Whether mSleeping can quickly toggled between true/false without the device actually
571 * display changing states is undefined.
572 */
573 private boolean mSleeping = false;
574
575 /**
576 * The process state used for processes that are running the top activities.
577 * This changes between TOP and TOP_SLEEPING to following mSleeping.
578 */
579 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
580
581 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
582 // automatically. Important for devices without direct input devices.
583 private boolean mShowDialogs = true;
584
585 /** Set if we are shutting down the system, similar to sleeping. */
586 boolean mShuttingDown = false;
587
588 /**
589 * We want to hold a wake lock while running a voice interaction session, since
590 * this may happen with the screen off and we need to keep the CPU running to
591 * be able to continue to interact with the user.
592 */
593 PowerManager.WakeLock mVoiceWakeLock;
594
595 /**
596 * Set while we are running a voice interaction. This overrides sleeping while it is active.
597 */
598 IVoiceInteractionSession mRunningVoice;
599
600 /**
601 * The last resumed activity. This is identical to the current resumed activity most
602 * of the time but could be different when we're pausing one activity before we resume
603 * another activity.
604 */
605 ActivityRecord mLastResumedActivity;
606
607 /**
608 * The activity that is currently being traced as the active resumed activity.
609 *
610 * @see #updateResumedAppTrace
611 */
612 private @Nullable ActivityRecord mTracedResumedActivity;
613
614 /** If non-null, we are tracking the time the user spends in the currently focused app. */
615 AppTimeTracker mCurAppTimeTracker;
616
Wale Ogunwale008163e2018-07-23 23:11:08 -0700617 private AppWarnings mAppWarnings;
618
Wale Ogunwale53783742018-09-16 10:21:51 -0700619 /**
620 * Packages that the user has asked to have run in screen size
621 * compatibility mode instead of filling the screen.
622 */
623 CompatModePackages mCompatModePackages;
624
Wale Ogunwalef6733932018-06-27 05:14:34 -0700625 private FontScaleSettingObserver mFontScaleSettingObserver;
626
Michal Karpinski4026cae2019-02-12 11:51:47 +0000627 private String mDeviceOwnerPackageName;
628
Wale Ogunwalef6733932018-06-27 05:14:34 -0700629 private final class FontScaleSettingObserver extends ContentObserver {
630 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
631 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
632
633 public FontScaleSettingObserver() {
634 super(mH);
635 final ContentResolver resolver = mContext.getContentResolver();
636 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
637 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
638 UserHandle.USER_ALL);
639 }
640
641 @Override
642 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
643 if (mFontScaleUri.equals(uri)) {
644 updateFontScaleIfNeeded(userId);
645 } else if (mHideErrorDialogsUri.equals(uri)) {
646 synchronized (mGlobalLock) {
647 updateShouldShowDialogsLocked(getGlobalConfiguration());
648 }
649 }
650 }
651 }
652
Riddle Hsua0536432019-02-16 00:38:59 +0800653 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
654 @Target(ElementType.METHOD)
655 @Retention(RetentionPolicy.SOURCE)
656 @interface HotPath {
657 int NONE = 0;
658 int OOM_ADJUSTMENT = 1;
659 int LRU_UPDATE = 2;
660 int PROCESS_CHANGE = 3;
661 int caller() default NONE;
662 }
663
Charles Chen8d98dd22018-12-26 17:36:54 +0800664 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
665 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700666 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700667 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700668 mSystemThread = ActivityThread.currentActivityThread();
669 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700670 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800671 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700672 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700673 }
674
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700675 public void onSystemReady() {
676 synchronized (mGlobalLock) {
677 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
678 PackageManager.FEATURE_CANT_SAVE_STATE);
679 mAssistUtils = new AssistUtils(mContext);
680 mVrController.onSystemReady();
681 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700682 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700683 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700684 }
685
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700686 public void onInitPowerManagement() {
687 synchronized (mGlobalLock) {
688 mStackSupervisor.initPowerManagement();
689 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
690 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
691 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
692 mVoiceWakeLock.setReferenceCounted(false);
693 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700694 }
695
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700696 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700697 mFontScaleSettingObserver = new FontScaleSettingObserver();
698 }
699
Wale Ogunwale59507092018-10-29 09:00:30 -0700700 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700701 final boolean freeformWindowManagement =
702 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
703 || Settings.Global.getInt(
704 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
705
706 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
707 final boolean supportsPictureInPicture = supportsMultiWindow &&
708 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
709 final boolean supportsSplitScreenMultiWindow =
710 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
711 final boolean supportsMultiDisplay = mContext.getPackageManager()
712 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700713 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
714 final boolean forceResizable = Settings.Global.getInt(
715 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700716 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700717
718 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900719 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700720
721 final Configuration configuration = new Configuration();
722 Settings.System.getConfiguration(resolver, configuration);
723 if (forceRtl) {
724 // This will take care of setting the correct layout direction flags
725 configuration.setLayoutDirection(configuration.locale);
726 }
727
728 synchronized (mGlobalLock) {
729 mForceResizableActivities = forceResizable;
730 final boolean multiWindowFormEnabled = freeformWindowManagement
731 || supportsSplitScreenMultiWindow
732 || supportsPictureInPicture
733 || supportsMultiDisplay;
734 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
735 mSupportsMultiWindow = true;
736 mSupportsFreeformWindowManagement = freeformWindowManagement;
737 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
738 mSupportsPictureInPicture = supportsPictureInPicture;
739 mSupportsMultiDisplay = supportsMultiDisplay;
740 } else {
741 mSupportsMultiWindow = false;
742 mSupportsFreeformWindowManagement = false;
743 mSupportsSplitScreenMultiWindow = false;
744 mSupportsPictureInPicture = false;
745 mSupportsMultiDisplay = false;
746 }
747 mWindowManager.setForceResizableTasks(mForceResizableActivities);
748 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700749 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
750 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700751 // This happens before any activities are started, so we can change global configuration
752 // in-place.
753 updateConfigurationLocked(configuration, null, true);
754 final Configuration globalConfig = getGlobalConfiguration();
755 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
756
757 // Load resources only after the current configuration has been set.
758 final Resources res = mContext.getResources();
759 mThumbnailWidth = res.getDimensionPixelSize(
760 com.android.internal.R.dimen.thumbnail_width);
761 mThumbnailHeight = res.getDimensionPixelSize(
762 com.android.internal.R.dimen.thumbnail_height);
763
764 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
765 mFullscreenThumbnailScale = (float) res
766 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
767 (float) globalConfig.screenWidthDp;
768 } else {
769 mFullscreenThumbnailScale = res.getFraction(
770 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
771 }
772 }
773 }
774
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800775 public WindowManagerGlobalLock getGlobalLock() {
776 return mGlobalLock;
777 }
778
Riddle Hsud93a6c42018-11-29 21:50:06 +0800779 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
780 Looper looper) {
781 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700782 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700783 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700784 final File systemDir = SystemServiceManager.ensureSystemDir();
785 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
786 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700787 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700788
789 mTempConfig.setToDefaults();
790 mTempConfig.setLocales(LocaleList.getDefault());
791 mConfigurationSeq = mTempConfig.seq = 1;
792 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800793 mRootActivityContainer = new RootActivityContainer(this);
794 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700795
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700796 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700797 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700798 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700799 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700800 mRecentTasks = createRecentTasks();
801 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700802 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700803 mKeyguardController = mStackSupervisor.getKeyguardController();
804 }
805
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700806 public void onActivityManagerInternalAdded() {
807 synchronized (mGlobalLock) {
808 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
809 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
810 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700811 }
812
Yunfan Chen75157d72018-07-27 14:47:21 +0900813 int increaseConfigurationSeqLocked() {
814 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
815 return mConfigurationSeq;
816 }
817
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818 protected ActivityStackSupervisor createStackSupervisor() {
819 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
820 supervisor.initialize();
821 return supervisor;
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void setWindowManager(WindowManagerService wm) {
825 synchronized (mGlobalLock) {
826 mWindowManager = wm;
827 mLockTaskController.setWindowManager(wm);
828 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800829 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700830 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700831 }
832
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700833 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
834 synchronized (mGlobalLock) {
835 mUsageStatsInternal = usageStatsManager;
836 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700837 }
838
Wale Ogunwalef6733932018-06-27 05:14:34 -0700839 UserManagerService getUserManager() {
840 if (mUserManager == null) {
841 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
842 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
843 }
844 return mUserManager;
845 }
846
847 AppOpsService getAppOpsService() {
848 if (mAppOpsService == null) {
849 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
850 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
851 }
852 return mAppOpsService;
853 }
854
855 boolean hasUserRestriction(String restriction, int userId) {
856 return getUserManager().hasUserRestriction(restriction, userId);
857 }
858
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700859 protected RecentTasks createRecentTasks() {
860 return new RecentTasks(this, mStackSupervisor);
861 }
862
863 RecentTasks getRecentTasks() {
864 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700865 }
866
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700867 ClientLifecycleManager getLifecycleManager() {
868 return mLifecycleManager;
869 }
870
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700871 ActivityStartController getActivityStartController() {
872 return mActivityStartController;
873 }
874
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700875 TaskChangeNotificationController getTaskChangeNotificationController() {
876 return mTaskChangeNotificationController;
877 }
878
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700879 LockTaskController getLockTaskController() {
880 return mLockTaskController;
881 }
882
Yunfan Chen75157d72018-07-27 14:47:21 +0900883 /**
884 * Return the global configuration used by the process corresponding to the input pid. This is
885 * usually the global configuration with some overrides specific to that process.
886 */
887 Configuration getGlobalConfigurationForCallingPid() {
888 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800889 return getGlobalConfigurationForPid(pid);
890 }
891
892 /**
893 * Return the global configuration used by the process corresponding to the given pid.
894 */
895 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900896 if (pid == MY_PID || pid < 0) {
897 return getGlobalConfiguration();
898 }
899 synchronized (mGlobalLock) {
900 final WindowProcessController app = mPidMap.get(pid);
901 return app != null ? app.getConfiguration() : getGlobalConfiguration();
902 }
903 }
904
905 /**
906 * Return the device configuration info used by the process corresponding to the input pid.
907 * The value is consistent with the global configuration for the process.
908 */
909 @Override
910 public ConfigurationInfo getDeviceConfigurationInfo() {
911 ConfigurationInfo config = new ConfigurationInfo();
912 synchronized (mGlobalLock) {
913 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
914 config.reqTouchScreen = globalConfig.touchscreen;
915 config.reqKeyboardType = globalConfig.keyboard;
916 config.reqNavigation = globalConfig.navigation;
917 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
918 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
919 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
920 }
921 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
922 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
923 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
924 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700925 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900926 }
927 return config;
928 }
929
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700930 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700931 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700932 }
933
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700934 public static final class Lifecycle extends SystemService {
935 private final ActivityTaskManagerService mService;
936
937 public Lifecycle(Context context) {
938 super(context);
939 mService = new ActivityTaskManagerService(context);
940 }
941
942 @Override
943 public void onStart() {
944 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700945 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700946 }
947
Garfield Tan891146c2018-10-09 12:14:00 -0700948 @Override
949 public void onUnlockUser(int userId) {
950 synchronized (mService.getGlobalLock()) {
951 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
952 }
953 }
954
955 @Override
956 public void onCleanupUser(int userId) {
957 synchronized (mService.getGlobalLock()) {
958 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
959 }
960 }
961
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700962 public ActivityTaskManagerService getService() {
963 return mService;
964 }
965 }
966
967 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700968 public final int startActivity(IApplicationThread caller, String callingPackage,
969 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
970 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
971 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
972 resultWho, requestCode, startFlags, profilerInfo, bOptions,
973 UserHandle.getCallingUserId());
974 }
975
976 @Override
977 public final int startActivities(IApplicationThread caller, String callingPackage,
978 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
979 int userId) {
980 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700981 enforceNotIsolatedCaller(reason);
982 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700983 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000984 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
985 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
986 reason, null /* originatingPendingIntent */,
987 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700988 }
989
990 @Override
991 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
992 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
993 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
994 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
995 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
996 true /*validateIncomingUser*/);
997 }
998
999 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1000 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1001 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1002 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001003 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001005 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001006 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1007
1008 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001009 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001010 .setCaller(caller)
1011 .setCallingPackage(callingPackage)
1012 .setResolvedType(resolvedType)
1013 .setResultTo(resultTo)
1014 .setResultWho(resultWho)
1015 .setRequestCode(requestCode)
1016 .setStartFlags(startFlags)
1017 .setProfilerInfo(profilerInfo)
1018 .setActivityOptions(bOptions)
1019 .setMayWait(userId)
1020 .execute();
1021
1022 }
1023
1024 @Override
1025 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1026 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001027 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1028 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 // Refuse possible leaked file descriptors
1030 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1031 throw new IllegalArgumentException("File descriptors passed in Intent");
1032 }
1033
1034 if (!(target instanceof PendingIntentRecord)) {
1035 throw new IllegalArgumentException("Bad PendingIntent object");
1036 }
1037
1038 PendingIntentRecord pir = (PendingIntentRecord)target;
1039
1040 synchronized (mGlobalLock) {
1041 // If this is coming from the currently resumed activity, it is
1042 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001043 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 if (stack.mResumedActivity != null &&
1045 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001046 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 }
1048 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001049 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051 }
1052
1053 @Override
1054 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1055 Bundle bOptions) {
1056 // Refuse possible leaked file descriptors
1057 if (intent != null && intent.hasFileDescriptors()) {
1058 throw new IllegalArgumentException("File descriptors passed in Intent");
1059 }
1060 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1061
1062 synchronized (mGlobalLock) {
1063 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1064 if (r == null) {
1065 SafeActivityOptions.abort(options);
1066 return false;
1067 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001068 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 // The caller is not running... d'oh!
1070 SafeActivityOptions.abort(options);
1071 return false;
1072 }
1073 intent = new Intent(intent);
1074 // The caller is not allowed to change the data.
1075 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1076 // And we are resetting to find the next component...
1077 intent.setComponent(null);
1078
1079 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1080
1081 ActivityInfo aInfo = null;
1082 try {
1083 List<ResolveInfo> resolves =
1084 AppGlobals.getPackageManager().queryIntentActivities(
1085 intent, r.resolvedType,
1086 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1087 UserHandle.getCallingUserId()).getList();
1088
1089 // Look for the original activity in the list...
1090 final int N = resolves != null ? resolves.size() : 0;
1091 for (int i=0; i<N; i++) {
1092 ResolveInfo rInfo = resolves.get(i);
1093 if (rInfo.activityInfo.packageName.equals(r.packageName)
1094 && rInfo.activityInfo.name.equals(r.info.name)) {
1095 // We found the current one... the next matching is
1096 // after it.
1097 i++;
1098 if (i<N) {
1099 aInfo = resolves.get(i).activityInfo;
1100 }
1101 if (debug) {
1102 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1103 + "/" + r.info.name);
1104 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1105 ? "null" : aInfo.packageName + "/" + aInfo.name));
1106 }
1107 break;
1108 }
1109 }
1110 } catch (RemoteException e) {
1111 }
1112
1113 if (aInfo == null) {
1114 // Nobody who is next!
1115 SafeActivityOptions.abort(options);
1116 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1117 return false;
1118 }
1119
1120 intent.setComponent(new ComponentName(
1121 aInfo.applicationInfo.packageName, aInfo.name));
1122 intent.setFlags(intent.getFlags()&~(
1123 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1124 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1125 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1126 FLAG_ACTIVITY_NEW_TASK));
1127
1128 // Okay now we need to start the new activity, replacing the currently running activity.
1129 // This is a little tricky because we want to start the new one as if the current one is
1130 // finished, but not finish the current one first so that there is no flicker.
1131 // And thus...
1132 final boolean wasFinishing = r.finishing;
1133 r.finishing = true;
1134
1135 // Propagate reply information over to the new activity.
1136 final ActivityRecord resultTo = r.resultTo;
1137 final String resultWho = r.resultWho;
1138 final int requestCode = r.requestCode;
1139 r.resultTo = null;
1140 if (resultTo != null) {
1141 resultTo.removeResultsLocked(r, resultWho, requestCode);
1142 }
1143
1144 final long origId = Binder.clearCallingIdentity();
1145 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001146 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001147 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001148 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001149 .setResolvedType(r.resolvedType)
1150 .setActivityInfo(aInfo)
1151 .setResultTo(resultTo != null ? resultTo.appToken : null)
1152 .setResultWho(resultWho)
1153 .setRequestCode(requestCode)
1154 .setCallingPid(-1)
1155 .setCallingUid(r.launchedFromUid)
1156 .setCallingPackage(r.launchedFromPackage)
1157 .setRealCallingPid(-1)
1158 .setRealCallingUid(r.launchedFromUid)
1159 .setActivityOptions(options)
1160 .execute();
1161 Binder.restoreCallingIdentity(origId);
1162
1163 r.finishing = wasFinishing;
1164 if (res != ActivityManager.START_SUCCESS) {
1165 return false;
1166 }
1167 return true;
1168 }
1169 }
1170
1171 @Override
1172 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1173 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1174 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1175 final WaitResult res = new WaitResult();
1176 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001177 enforceNotIsolatedCaller("startActivityAndWait");
1178 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1179 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001180 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001181 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 .setCaller(caller)
1183 .setCallingPackage(callingPackage)
1184 .setResolvedType(resolvedType)
1185 .setResultTo(resultTo)
1186 .setResultWho(resultWho)
1187 .setRequestCode(requestCode)
1188 .setStartFlags(startFlags)
1189 .setActivityOptions(bOptions)
1190 .setMayWait(userId)
1191 .setProfilerInfo(profilerInfo)
1192 .setWaitResult(res)
1193 .execute();
1194 }
1195 return res;
1196 }
1197
1198 @Override
1199 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1200 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1201 int startFlags, Configuration config, Bundle bOptions, int userId) {
1202 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001203 enforceNotIsolatedCaller("startActivityWithConfig");
1204 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1205 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001206 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001207 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 .setCaller(caller)
1209 .setCallingPackage(callingPackage)
1210 .setResolvedType(resolvedType)
1211 .setResultTo(resultTo)
1212 .setResultWho(resultWho)
1213 .setRequestCode(requestCode)
1214 .setStartFlags(startFlags)
1215 .setGlobalConfiguration(config)
1216 .setActivityOptions(bOptions)
1217 .setMayWait(userId)
1218 .execute();
1219 }
1220 }
1221
Alison Cichowlas3e340502018-08-07 17:15:01 -04001222
1223 @Override
1224 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1225 int callingUid = Binder.getCallingUid();
1226 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1227 throw new SecurityException("Only the system process can request a permission token, "
1228 + "received request from uid: " + callingUid);
1229 }
1230 IBinder permissionToken = new Binder();
1231 synchronized (mGlobalLock) {
1232 mStartActivitySources.put(permissionToken, delegatorToken);
1233 }
1234
1235 Message expireMsg = PooledLambda.obtainMessage(
1236 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1237 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1238
1239 Message forgetMsg = PooledLambda.obtainMessage(
1240 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1241 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1242
1243 return permissionToken;
1244 }
1245
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001246 @Override
1247 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1248 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001249 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1250 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001251 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001252 // permission grants) as any app that may launch one of your own activities. So we only
1253 // allow this in two cases:
1254 // 1) The caller is an activity that is part of the core framework, and then only when it
1255 // is running as the system.
1256 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1257 // can only be requested by a system activity, which may then delegate this call to
1258 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001259 final ActivityRecord sourceRecord;
1260 final int targetUid;
1261 final String targetPackage;
1262 final boolean isResolver;
1263 synchronized (mGlobalLock) {
1264 if (resultTo == null) {
1265 throw new SecurityException("Must be called from an activity");
1266 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267 final IBinder sourceToken;
1268 if (permissionToken != null) {
1269 // To even attempt to use a permissionToken, an app must also have this signature
1270 // permission.
1271 mAmInternal.enforceCallingPermission(
1272 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1273 "startActivityAsCaller");
1274 // If called with a permissionToken, we want the sourceRecord from the delegator
1275 // activity that requested this token.
1276 sourceToken = mStartActivitySources.remove(permissionToken);
1277 if (sourceToken == null) {
1278 // Invalid permissionToken, check if it recently expired.
1279 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1280 throw new SecurityException("Called with expired permission token: "
1281 + permissionToken);
1282 } else {
1283 throw new SecurityException("Called with invalid permission token: "
1284 + permissionToken);
1285 }
1286 }
1287 } else {
1288 // This method was called directly by the source.
1289 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001290 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001291
Wale Ogunwaled32da472018-11-16 07:19:28 -08001292 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001293 if (sourceRecord == null) {
1294 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001295 }
1296 if (sourceRecord.app == null) {
1297 throw new SecurityException("Called without a process attached to activity");
1298 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299
1300 // Whether called directly or from a delegate, the source activity must be from the
1301 // android package.
1302 if (!sourceRecord.info.packageName.equals("android")) {
1303 throw new SecurityException("Must be called from an activity that is "
1304 + "declared in the android package");
1305 }
1306
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001307 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001308 // This is still okay, as long as this activity is running under the
1309 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001310 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001312 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001313 + " must be system uid or original calling uid "
1314 + sourceRecord.launchedFromUid);
1315 }
1316 }
1317 if (ignoreTargetSecurity) {
1318 if (intent.getComponent() == null) {
1319 throw new SecurityException(
1320 "Component must be specified with ignoreTargetSecurity");
1321 }
1322 if (intent.getSelector() != null) {
1323 throw new SecurityException(
1324 "Selector not allowed with ignoreTargetSecurity");
1325 }
1326 }
1327 targetUid = sourceRecord.launchedFromUid;
1328 targetPackage = sourceRecord.launchedFromPackage;
1329 isResolver = sourceRecord.isResolverOrChildActivity();
1330 }
1331
1332 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001333 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001334 }
1335
1336 // TODO: Switch to user app stacks here.
1337 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001338 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 .setCallingUid(targetUid)
1340 .setCallingPackage(targetPackage)
1341 .setResolvedType(resolvedType)
1342 .setResultTo(resultTo)
1343 .setResultWho(resultWho)
1344 .setRequestCode(requestCode)
1345 .setStartFlags(startFlags)
1346 .setActivityOptions(bOptions)
1347 .setMayWait(userId)
1348 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1349 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1350 .execute();
1351 } catch (SecurityException e) {
1352 // XXX need to figure out how to propagate to original app.
1353 // A SecurityException here is generally actually a fault of the original
1354 // calling activity (such as a fairly granting permissions), so propagate it
1355 // back to them.
1356 /*
1357 StringBuilder msg = new StringBuilder();
1358 msg.append("While launching");
1359 msg.append(intent.toString());
1360 msg.append(": ");
1361 msg.append(e.getMessage());
1362 */
1363 throw e;
1364 }
1365 }
1366
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001367 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1368 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1369 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1370 }
1371
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 @Override
1373 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1374 Intent intent, String resolvedType, IVoiceInteractionSession session,
1375 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1376 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001377 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 if (session == null || interactor == null) {
1379 throw new NullPointerException("null session or interactor");
1380 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001381 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001383 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 .setCallingUid(callingUid)
1385 .setCallingPackage(callingPackage)
1386 .setResolvedType(resolvedType)
1387 .setVoiceSession(session)
1388 .setVoiceInteractor(interactor)
1389 .setStartFlags(startFlags)
1390 .setProfilerInfo(profilerInfo)
1391 .setActivityOptions(bOptions)
1392 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001393 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 .execute();
1395 }
1396
1397 @Override
1398 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1399 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1401 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001403 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 .setCallingUid(callingUid)
1405 .setCallingPackage(callingPackage)
1406 .setResolvedType(resolvedType)
1407 .setActivityOptions(bOptions)
1408 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001409 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 .execute();
1411 }
1412
1413 @Override
1414 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1415 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 final int callingPid = Binder.getCallingPid();
1418 final long origId = Binder.clearCallingIdentity();
1419 try {
1420 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001421 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1422 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423
1424 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001425 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1426 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1428 recentsUid, assistDataReceiver);
1429 }
1430 } finally {
1431 Binder.restoreCallingIdentity(origId);
1432 }
1433 }
1434
1435 @Override
1436 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001437 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 "startActivityFromRecents()");
1439
1440 final int callingPid = Binder.getCallingPid();
1441 final int callingUid = Binder.getCallingUid();
1442 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1443 final long origId = Binder.clearCallingIdentity();
1444 try {
1445 synchronized (mGlobalLock) {
1446 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1447 safeOptions);
1448 }
1449 } finally {
1450 Binder.restoreCallingIdentity(origId);
1451 }
1452 }
1453
1454 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001455 * Public API to check if the client is allowed to start an activity on specified display.
1456 *
1457 * If the target display is private or virtual, some restrictions will apply.
1458 *
1459 * @param displayId Target display id.
1460 * @param intent Intent used to launch the activity.
1461 * @param resolvedType The MIME type of the intent.
1462 * @param userId The id of the user for whom the call is made.
1463 * @return {@code true} if a call to start an activity on the target display should succeed and
1464 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1465 */
1466 @Override
1467 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1468 String resolvedType, int userId) {
1469 final int callingUid = Binder.getCallingUid();
1470 final int callingPid = Binder.getCallingPid();
1471 final long origId = Binder.clearCallingIdentity();
1472
1473 try {
1474 // Collect information about the target of the Intent.
1475 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1476 0 /* startFlags */, null /* profilerInfo */, userId,
1477 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1478 UserHandle.USER_NULL));
1479 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1480
1481 synchronized (mGlobalLock) {
1482 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1483 aInfo);
1484 }
1485 } finally {
1486 Binder.restoreCallingIdentity(origId);
1487 }
1488 }
1489
1490 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001491 * This is the internal entry point for handling Activity.finish().
1492 *
1493 * @param token The Binder token referencing the Activity we want to finish.
1494 * @param resultCode Result code, if any, from this Activity.
1495 * @param resultData Result data (Intent), if any, from this Activity.
1496 * @param finishTask Whether to finish the task associated with this Activity.
1497 *
1498 * @return Returns true if the activity successfully finished, or false if it is still running.
1499 */
1500 @Override
1501 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1502 int finishTask) {
1503 // Refuse possible leaked file descriptors
1504 if (resultData != null && resultData.hasFileDescriptors()) {
1505 throw new IllegalArgumentException("File descriptors passed in Intent");
1506 }
1507
1508 synchronized (mGlobalLock) {
1509 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1510 if (r == null) {
1511 return true;
1512 }
1513 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001514 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001515 ActivityRecord rootR = tr.getRootActivity();
1516 if (rootR == null) {
1517 Slog.w(TAG, "Finishing task with all activities already finished");
1518 }
1519 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1520 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001521 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001522 return false;
1523 }
1524
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001525 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1526 // We should consolidate.
1527 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001529 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001530 if (next != null) {
1531 // ask watcher if this is allowed
1532 boolean resumeOK = true;
1533 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001534 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001536 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001537 Watchdog.getInstance().setActivityController(null);
1538 }
1539
1540 if (!resumeOK) {
1541 Slog.i(TAG, "Not finishing activity because controller resumed");
1542 return false;
1543 }
1544 }
1545 }
1546 final long origId = Binder.clearCallingIdentity();
1547 try {
1548 boolean res;
1549 final boolean finishWithRootActivity =
1550 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1551 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1552 || (finishWithRootActivity && r == rootR)) {
1553 // If requested, remove the task that is associated to this activity only if it
1554 // was the root activity in the task. The result code and data is ignored
1555 // because we don't support returning them across task boundaries. Also, to
1556 // keep backwards compatibility we remove the task from recents when finishing
1557 // task with root activity.
1558 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1559 finishWithRootActivity, "finish-activity");
1560 if (!res) {
1561 Slog.i(TAG, "Removing task failed to finish activity");
1562 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001563 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001564 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 } else {
1566 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1567 resultData, "app-request", true);
1568 if (!res) {
1569 Slog.i(TAG, "Failed to finish by app-request");
1570 }
1571 }
1572 return res;
1573 } finally {
1574 Binder.restoreCallingIdentity(origId);
1575 }
1576 }
1577 }
1578
1579 @Override
1580 public boolean finishActivityAffinity(IBinder token) {
1581 synchronized (mGlobalLock) {
1582 final long origId = Binder.clearCallingIdentity();
1583 try {
1584 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1585 if (r == null) {
1586 return false;
1587 }
1588
1589 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1590 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001591 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001592 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 return false;
1594 }
1595 return task.getStack().finishActivityAffinityLocked(r);
1596 } finally {
1597 Binder.restoreCallingIdentity(origId);
1598 }
1599 }
1600 }
1601
1602 @Override
1603 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1604 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001605 try {
1606 WindowProcessController proc = null;
1607 synchronized (mGlobalLock) {
1608 ActivityStack stack = ActivityRecord.getStackLocked(token);
1609 if (stack == null) {
1610 return;
1611 }
1612 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1613 false /* fromTimeout */, false /* processPausingActivities */, config);
1614 if (r != null) {
1615 proc = r.app;
1616 }
1617 if (stopProfiling && proc != null) {
1618 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 }
1620 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001621 } finally {
1622 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001624 }
1625
1626 @Override
1627 public final void activityResumed(IBinder token) {
1628 final long origId = Binder.clearCallingIdentity();
1629 synchronized (mGlobalLock) {
1630 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001631 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001632 }
1633 Binder.restoreCallingIdentity(origId);
1634 }
1635
1636 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001637 public final void activityTopResumedStateLost() {
1638 final long origId = Binder.clearCallingIdentity();
1639 synchronized (mGlobalLock) {
1640 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1641 }
1642 Binder.restoreCallingIdentity(origId);
1643 }
1644
1645 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001646 public final void activityPaused(IBinder token) {
1647 final long origId = Binder.clearCallingIdentity();
1648 synchronized (mGlobalLock) {
1649 ActivityStack stack = ActivityRecord.getStackLocked(token);
1650 if (stack != null) {
1651 stack.activityPausedLocked(token, false);
1652 }
1653 }
1654 Binder.restoreCallingIdentity(origId);
1655 }
1656
1657 @Override
1658 public final void activityStopped(IBinder token, Bundle icicle,
1659 PersistableBundle persistentState, CharSequence description) {
1660 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1661
1662 // Refuse possible leaked file descriptors
1663 if (icicle != null && icicle.hasFileDescriptors()) {
1664 throw new IllegalArgumentException("File descriptors passed in Bundle");
1665 }
1666
1667 final long origId = Binder.clearCallingIdentity();
1668
1669 synchronized (mGlobalLock) {
1670 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1671 if (r != null) {
1672 r.activityStoppedLocked(icicle, persistentState, description);
1673 }
1674 }
1675
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001676 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677
1678 Binder.restoreCallingIdentity(origId);
1679 }
1680
1681 @Override
1682 public final void activityDestroyed(IBinder token) {
1683 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1684 synchronized (mGlobalLock) {
1685 ActivityStack stack = ActivityRecord.getStackLocked(token);
1686 if (stack != null) {
1687 stack.activityDestroyedLocked(token, "activityDestroyed");
1688 }
1689 }
1690 }
1691
1692 @Override
1693 public final void activityRelaunched(IBinder token) {
1694 final long origId = Binder.clearCallingIdentity();
1695 synchronized (mGlobalLock) {
1696 mStackSupervisor.activityRelaunchedLocked(token);
1697 }
1698 Binder.restoreCallingIdentity(origId);
1699 }
1700
1701 public final void activitySlept(IBinder token) {
1702 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1703
1704 final long origId = Binder.clearCallingIdentity();
1705
1706 synchronized (mGlobalLock) {
1707 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1708 if (r != null) {
1709 mStackSupervisor.activitySleptLocked(r);
1710 }
1711 }
1712
1713 Binder.restoreCallingIdentity(origId);
1714 }
1715
1716 @Override
1717 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1718 synchronized (mGlobalLock) {
1719 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1720 if (r == null) {
1721 return;
1722 }
1723 final long origId = Binder.clearCallingIdentity();
1724 try {
1725 r.setRequestedOrientation(requestedOrientation);
1726 } finally {
1727 Binder.restoreCallingIdentity(origId);
1728 }
1729 }
1730 }
1731
1732 @Override
1733 public int getRequestedOrientation(IBinder token) {
1734 synchronized (mGlobalLock) {
1735 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1736 if (r == null) {
1737 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1738 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001739 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 }
1741 }
1742
1743 @Override
1744 public void setImmersive(IBinder token, boolean immersive) {
1745 synchronized (mGlobalLock) {
1746 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1747 if (r == null) {
1748 throw new IllegalArgumentException();
1749 }
1750 r.immersive = immersive;
1751
1752 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001753 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001754 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001755 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 }
1757 }
1758 }
1759
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001760 void applyUpdateLockStateLocked(ActivityRecord r) {
1761 // Modifications to the UpdateLock state are done on our handler, outside
1762 // the activity manager's locks. The new state is determined based on the
1763 // state *now* of the relevant activity record. The object is passed to
1764 // the handler solely for logging detail, not to be consulted/modified.
1765 final boolean nextState = r != null && r.immersive;
1766 mH.post(() -> {
1767 if (mUpdateLock.isHeld() != nextState) {
1768 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1769 "Applying new update lock state '" + nextState + "' for " + r);
1770 if (nextState) {
1771 mUpdateLock.acquire();
1772 } else {
1773 mUpdateLock.release();
1774 }
1775 }
1776 });
1777 }
1778
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 @Override
1780 public boolean isImmersive(IBinder token) {
1781 synchronized (mGlobalLock) {
1782 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1783 if (r == null) {
1784 throw new IllegalArgumentException();
1785 }
1786 return r.immersive;
1787 }
1788 }
1789
1790 @Override
1791 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001792 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001793 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001794 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001795 return (r != null) ? r.immersive : false;
1796 }
1797 }
1798
1799 @Override
1800 public void overridePendingTransition(IBinder token, String packageName,
1801 int enterAnim, int exitAnim) {
1802 synchronized (mGlobalLock) {
1803 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1804 if (self == null) {
1805 return;
1806 }
1807
1808 final long origId = Binder.clearCallingIdentity();
1809
1810 if (self.isState(
1811 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001812 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001813 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 }
1815
1816 Binder.restoreCallingIdentity(origId);
1817 }
1818 }
1819
1820 @Override
1821 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001822 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001823 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001824 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001825 if (r == null) {
1826 return ActivityManager.COMPAT_MODE_UNKNOWN;
1827 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001828 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001829 }
1830 }
1831
1832 @Override
1833 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001834 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001838 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001839 if (r == null) {
1840 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1841 return;
1842 }
1843 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001844 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001845 }
1846 }
1847
1848 @Override
1849 public int getLaunchedFromUid(IBinder activityToken) {
1850 ActivityRecord srec;
1851 synchronized (mGlobalLock) {
1852 srec = ActivityRecord.forTokenLocked(activityToken);
1853 }
1854 if (srec == null) {
1855 return -1;
1856 }
1857 return srec.launchedFromUid;
1858 }
1859
1860 @Override
1861 public String getLaunchedFromPackage(IBinder activityToken) {
1862 ActivityRecord srec;
1863 synchronized (mGlobalLock) {
1864 srec = ActivityRecord.forTokenLocked(activityToken);
1865 }
1866 if (srec == null) {
1867 return null;
1868 }
1869 return srec.launchedFromPackage;
1870 }
1871
1872 @Override
1873 public boolean convertFromTranslucent(IBinder token) {
1874 final long origId = Binder.clearCallingIdentity();
1875 try {
1876 synchronized (mGlobalLock) {
1877 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1878 if (r == null) {
1879 return false;
1880 }
1881 final boolean translucentChanged = r.changeWindowTranslucency(true);
1882 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001883 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 return translucentChanged;
1887 }
1888 } finally {
1889 Binder.restoreCallingIdentity(origId);
1890 }
1891 }
1892
1893 @Override
1894 public boolean convertToTranslucent(IBinder token, Bundle options) {
1895 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1896 final long origId = Binder.clearCallingIdentity();
1897 try {
1898 synchronized (mGlobalLock) {
1899 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1900 if (r == null) {
1901 return false;
1902 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001903 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 int index = task.mActivities.lastIndexOf(r);
1905 if (index > 0) {
1906 ActivityRecord under = task.mActivities.get(index - 1);
1907 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1908 }
1909 final boolean translucentChanged = r.changeWindowTranslucency(false);
1910 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001911 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001912 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001913 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001914 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 return translucentChanged;
1916 }
1917 } finally {
1918 Binder.restoreCallingIdentity(origId);
1919 }
1920 }
1921
1922 @Override
1923 public void notifyActivityDrawn(IBinder token) {
1924 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1925 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001926 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001928 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931 }
1932
1933 @Override
1934 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1935 synchronized (mGlobalLock) {
1936 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1937 if (r == null) {
1938 return;
1939 }
1940 r.reportFullyDrawnLocked(restoredFromBundle);
1941 }
1942 }
1943
1944 @Override
1945 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1946 synchronized (mGlobalLock) {
1947 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1948 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1949 return stack.mDisplayId;
1950 }
1951 return DEFAULT_DISPLAY;
1952 }
1953 }
1954
1955 @Override
1956 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001957 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 long ident = Binder.clearCallingIdentity();
1959 try {
1960 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001961 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 return null;
1966 }
1967 } finally {
1968 Binder.restoreCallingIdentity(ident);
1969 }
1970 }
1971
1972 @Override
1973 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001974 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1976 final long callingId = Binder.clearCallingIdentity();
1977 try {
1978 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001979 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 if (stack == null) {
1981 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1982 return;
1983 }
1984 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001985 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001986 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001987 }
1988 }
1989 } finally {
1990 Binder.restoreCallingIdentity(callingId);
1991 }
1992 }
1993
1994 @Override
1995 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001996 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1998 final long callingId = Binder.clearCallingIdentity();
1999 try {
2000 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002001 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002002 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 if (task == null) {
2004 return;
2005 }
2006 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002007 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002008 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 }
2010 }
2011 } finally {
2012 Binder.restoreCallingIdentity(callingId);
2013 }
2014 }
2015
2016 @Override
2017 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002018 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002019 synchronized (mGlobalLock) {
2020 final long ident = Binder.clearCallingIdentity();
2021 try {
2022 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2023 "remove-task");
2024 } finally {
2025 Binder.restoreCallingIdentity(ident);
2026 }
2027 }
2028 }
2029
2030 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002031 public void removeAllVisibleRecentTasks() {
2032 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2033 synchronized (mGlobalLock) {
2034 final long ident = Binder.clearCallingIdentity();
2035 try {
2036 getRecentTasks().removeAllVisibleTasks();
2037 } finally {
2038 Binder.restoreCallingIdentity(ident);
2039 }
2040 }
2041 }
2042
2043 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2045 synchronized (mGlobalLock) {
2046 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2047 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002048 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 }
2050 }
2051 return false;
2052 }
2053
2054 @Override
2055 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2056 Intent resultData) {
2057
2058 synchronized (mGlobalLock) {
2059 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2060 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002061 return r.getActivityStack().navigateUpToLocked(
2062 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 }
2064 return false;
2065 }
2066 }
2067
2068 /**
2069 * Attempts to move a task backwards in z-order (the order of activities within the task is
2070 * unchanged).
2071 *
2072 * There are several possible results of this call:
2073 * - if the task is locked, then we will show the lock toast
2074 * - if there is a task behind the provided task, then that task is made visible and resumed as
2075 * this task is moved to the back
2076 * - otherwise, if there are no other tasks in the stack:
2077 * - if this task is in the pinned stack, then we remove the stack completely, which will
2078 * have the effect of moving the task to the top or bottom of the fullscreen stack
2079 * (depending on whether it is visible)
2080 * - otherwise, we simply return home and hide this task
2081 *
2082 * @param token A reference to the activity we wish to move
2083 * @param nonRoot If false then this only works if the activity is the root
2084 * of a task; if true it will work for any activity in a task.
2085 * @return Returns true if the move completed, false if not.
2086 */
2087 @Override
2088 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002089 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 synchronized (mGlobalLock) {
2091 final long origId = Binder.clearCallingIdentity();
2092 try {
2093 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002094 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 if (task != null) {
2096 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2097 }
2098 } finally {
2099 Binder.restoreCallingIdentity(origId);
2100 }
2101 }
2102 return false;
2103 }
2104
2105 @Override
2106 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002107 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 long ident = Binder.clearCallingIdentity();
2109 Rect rect = new Rect();
2110 try {
2111 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002112 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2114 if (task == null) {
2115 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2116 return rect;
2117 }
2118 if (task.getStack() != null) {
2119 // Return the bounds from window manager since it will be adjusted for various
2120 // things like the presense of a docked stack for tasks that aren't resizeable.
2121 task.getWindowContainerBounds(rect);
2122 } else {
2123 // Task isn't in window manager yet since it isn't associated with a stack.
2124 // Return the persist value from activity manager
2125 if (!task.matchParentBounds()) {
2126 rect.set(task.getBounds());
2127 } else if (task.mLastNonFullscreenBounds != null) {
2128 rect.set(task.mLastNonFullscreenBounds);
2129 }
2130 }
2131 }
2132 } finally {
2133 Binder.restoreCallingIdentity(ident);
2134 }
2135 return rect;
2136 }
2137
2138 @Override
2139 public ActivityManager.TaskDescription getTaskDescription(int id) {
2140 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002141 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002143 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002144 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2145 if (tr != null) {
2146 return tr.lastTaskDescription;
2147 }
2148 }
2149 return null;
2150 }
2151
2152 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002153 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2154 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2155 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2156 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2157 return;
2158 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002159 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002160 synchronized (mGlobalLock) {
2161 final long ident = Binder.clearCallingIdentity();
2162 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002163 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002164 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002165 if (task == null) {
2166 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2167 return;
2168 }
2169
2170 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2171 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2172
2173 if (!task.isActivityTypeStandardOrUndefined()) {
2174 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2175 + " non-standard task " + taskId + " to windowing mode="
2176 + windowingMode);
2177 }
2178
2179 final ActivityStack stack = task.getStack();
2180 if (toTop) {
2181 stack.moveToFront("setTaskWindowingMode", task);
2182 }
2183 stack.setWindowingMode(windowingMode);
2184 } finally {
2185 Binder.restoreCallingIdentity(ident);
2186 }
2187 }
2188 }
2189
2190 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002192 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002193 ActivityRecord r = getCallingRecordLocked(token);
2194 return r != null ? r.info.packageName : null;
2195 }
2196 }
2197
2198 @Override
2199 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 ActivityRecord r = getCallingRecordLocked(token);
2202 return r != null ? r.intent.getComponent() : null;
2203 }
2204 }
2205
2206 private ActivityRecord getCallingRecordLocked(IBinder token) {
2207 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2208 if (r == null) {
2209 return null;
2210 }
2211 return r.resultTo;
2212 }
2213
2214 @Override
2215 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002216 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002217
2218 synchronized (mGlobalLock) {
2219 final long origId = Binder.clearCallingIdentity();
2220 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002221 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 } finally {
2223 Binder.restoreCallingIdentity(origId);
2224 }
2225 }
2226 }
2227
2228 /**
2229 * TODO: Add mController hook
2230 */
2231 @Override
2232 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002233 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002234
2235 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2236 synchronized (mGlobalLock) {
2237 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2238 false /* fromRecents */);
2239 }
2240 }
2241
2242 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2243 boolean fromRecents) {
2244
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002245 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 Binder.getCallingUid(), -1, -1, "Task to front")) {
2247 SafeActivityOptions.abort(options);
2248 return;
2249 }
2250 final long origId = Binder.clearCallingIdentity();
2251 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002252 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 if (task == null) {
2254 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002255 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002256 return;
2257 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002258 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002259 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002260 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002261 return;
2262 }
2263 ActivityOptions realOptions = options != null
2264 ? options.getOptions(mStackSupervisor)
2265 : null;
2266 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2267 false /* forceNonResizable */);
2268
2269 final ActivityRecord topActivity = task.getTopActivity();
2270 if (topActivity != null) {
2271
2272 // We are reshowing a task, use a starting window to hide the initial draw delay
2273 // so the transition can start earlier.
2274 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2275 true /* taskSwitch */, fromRecents);
2276 }
2277 } finally {
2278 Binder.restoreCallingIdentity(origId);
2279 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002280 }
2281
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002282 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2283 int callingPid, int callingUid, String name) {
2284 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2285 return true;
2286 }
2287
2288 if (getRecentTasks().isCallerRecents(sourceUid)) {
2289 return true;
2290 }
2291
2292 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2293 if (perm == PackageManager.PERMISSION_GRANTED) {
2294 return true;
2295 }
2296 if (checkAllowAppSwitchUid(sourceUid)) {
2297 return true;
2298 }
2299
2300 // If the actual IPC caller is different from the logical source, then
2301 // also see if they are allowed to control app switches.
2302 if (callingUid != -1 && callingUid != sourceUid) {
2303 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2304 if (perm == PackageManager.PERMISSION_GRANTED) {
2305 return true;
2306 }
2307 if (checkAllowAppSwitchUid(callingUid)) {
2308 return true;
2309 }
2310 }
2311
2312 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2313 return false;
2314 }
2315
2316 private boolean checkAllowAppSwitchUid(int uid) {
2317 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2318 if (types != null) {
2319 for (int i = types.size() - 1; i >= 0; i--) {
2320 if (types.valueAt(i).intValue() == uid) {
2321 return true;
2322 }
2323 }
2324 }
2325 return false;
2326 }
2327
2328 @Override
2329 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2330 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2331 "setActivityController()");
2332 synchronized (mGlobalLock) {
2333 mController = controller;
2334 mControllerIsAMonkey = imAMonkey;
2335 Watchdog.getInstance().setActivityController(controller);
2336 }
2337 }
2338
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002339 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002340 synchronized (mGlobalLock) {
2341 return mController != null && mControllerIsAMonkey;
2342 }
2343 }
2344
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345 @Override
2346 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2347 synchronized (mGlobalLock) {
2348 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2349 }
2350 }
2351
2352 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002353 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2354 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2355 }
2356
2357 @Override
2358 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2359 @WindowConfiguration.ActivityType int ignoreActivityType,
2360 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2361 final int callingUid = Binder.getCallingUid();
2362 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2363
2364 synchronized (mGlobalLock) {
2365 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2366
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002368 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002369 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002370 ignoreWindowingMode, callingUid, allowed);
2371 }
2372
2373 return list;
2374 }
2375
2376 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2378 synchronized (mGlobalLock) {
2379 final long origId = Binder.clearCallingIdentity();
2380 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2381 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002382 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 }
2384 Binder.restoreCallingIdentity(origId);
2385 }
2386 }
2387
2388 @Override
2389 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002390 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002391 ActivityStack stack = ActivityRecord.getStackLocked(token);
2392 if (stack != null) {
2393 return stack.willActivityBeVisibleLocked(token);
2394 }
2395 return false;
2396 }
2397 }
2398
2399 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002400 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002401 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002402 synchronized (mGlobalLock) {
2403 final long ident = Binder.clearCallingIdentity();
2404 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002405 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002406 if (task == null) {
2407 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2408 return;
2409 }
2410
2411 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2412 + " to stackId=" + stackId + " toTop=" + toTop);
2413
Wale Ogunwaled32da472018-11-16 07:19:28 -08002414 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002415 if (stack == null) {
2416 throw new IllegalStateException(
2417 "moveTaskToStack: No stack for stackId=" + stackId);
2418 }
2419 if (!stack.isActivityTypeStandardOrUndefined()) {
2420 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2421 + taskId + " to stack " + stackId);
2422 }
2423 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002424 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002425 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2426 }
2427 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2428 "moveTaskToStack");
2429 } finally {
2430 Binder.restoreCallingIdentity(ident);
2431 }
2432 }
2433 }
2434
2435 @Override
2436 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2437 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002438 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439
2440 final long ident = Binder.clearCallingIdentity();
2441 try {
2442 synchronized (mGlobalLock) {
2443 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002444 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002445 if (stack == null) {
2446 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2447 return;
2448 }
2449 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2450 throw new IllegalArgumentException("Stack: " + stackId
2451 + " doesn't support animated resize.");
2452 }
2453 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2454 animationDuration, false /* fromFullscreen */);
2455 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002456 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002457 if (stack == null) {
2458 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2459 return;
2460 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002461 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002462 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2463 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2464 }
2465 }
2466 } finally {
2467 Binder.restoreCallingIdentity(ident);
2468 }
2469 }
2470
wilsonshih5c4cf522019-01-25 09:03:47 +08002471 @Override
2472 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2473 int animationDuration) {
2474 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2475
2476 final long ident = Binder.clearCallingIdentity();
2477 try {
2478 synchronized (mGlobalLock) {
2479 if (xOffset == 0 && yOffset == 0) {
2480 return;
2481 }
2482 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2483 if (stack == null) {
2484 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2485 return;
2486 }
2487 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2488 throw new IllegalArgumentException("Stack: " + stackId
2489 + " doesn't support animated resize.");
2490 }
2491 final Rect destBounds = new Rect();
2492 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002493 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002494 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2495 return;
2496 }
2497 destBounds.offset(xOffset, yOffset);
2498 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2499 animationDuration, false /* fromFullscreen */);
2500 }
2501 } finally {
2502 Binder.restoreCallingIdentity(ident);
2503 }
2504 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002505 /**
2506 * Moves the specified task to the primary-split-screen stack.
2507 *
2508 * @param taskId Id of task to move.
2509 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2510 * exist already. See
2511 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2512 * and
2513 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2514 * @param toTop If the task and stack should be moved to the top.
2515 * @param animate Whether we should play an animation for the moving the task.
2516 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2517 * stack. Pass {@code null} to use default bounds.
2518 * @param showRecents If the recents activity should be shown on the other side of the task
2519 * going into split-screen mode.
2520 */
2521 @Override
2522 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2523 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002524 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002525 "setTaskWindowingModeSplitScreenPrimary()");
2526 synchronized (mGlobalLock) {
2527 final long ident = Binder.clearCallingIdentity();
2528 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002529 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002530 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002531 if (task == null) {
2532 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2533 return false;
2534 }
2535 if (DEBUG_STACK) Slog.d(TAG_STACK,
2536 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2537 + " to createMode=" + createMode + " toTop=" + toTop);
2538 if (!task.isActivityTypeStandardOrUndefined()) {
2539 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2540 + " non-standard task " + taskId + " to split-screen windowing mode");
2541 }
2542
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002543 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 final int windowingMode = task.getWindowingMode();
2545 final ActivityStack stack = task.getStack();
2546 if (toTop) {
2547 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2548 }
2549 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002550 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2551 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 return windowingMode != task.getWindowingMode();
2553 } finally {
2554 Binder.restoreCallingIdentity(ident);
2555 }
2556 }
2557 }
2558
2559 /**
2560 * Removes stacks in the input windowing modes from the system if they are of activity type
2561 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2562 */
2563 @Override
2564 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002565 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002566 "removeStacksInWindowingModes()");
2567
2568 synchronized (mGlobalLock) {
2569 final long ident = Binder.clearCallingIdentity();
2570 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002571 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572 } finally {
2573 Binder.restoreCallingIdentity(ident);
2574 }
2575 }
2576 }
2577
2578 @Override
2579 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002580 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002581 "removeStacksWithActivityTypes()");
2582
2583 synchronized (mGlobalLock) {
2584 final long ident = Binder.clearCallingIdentity();
2585 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002586 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002587 } finally {
2588 Binder.restoreCallingIdentity(ident);
2589 }
2590 }
2591 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002592
2593 @Override
2594 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2595 int userId) {
2596 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002597 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2598 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002600 final boolean detailed = checkGetTasksPermission(
2601 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2602 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002603 == PackageManager.PERMISSION_GRANTED;
2604
2605 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002606 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002607 callingUid);
2608 }
2609 }
2610
2611 @Override
2612 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002613 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002614 long ident = Binder.clearCallingIdentity();
2615 try {
2616 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002617 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002618 }
2619 } finally {
2620 Binder.restoreCallingIdentity(ident);
2621 }
2622 }
2623
2624 @Override
2625 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002626 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002627 long ident = Binder.clearCallingIdentity();
2628 try {
2629 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002630 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002631 }
2632 } finally {
2633 Binder.restoreCallingIdentity(ident);
2634 }
2635 }
2636
2637 @Override
2638 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002639 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002640 final long callingUid = Binder.getCallingUid();
2641 final long origId = Binder.clearCallingIdentity();
2642 try {
2643 synchronized (mGlobalLock) {
2644 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002645 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2647 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2648 }
2649 } finally {
2650 Binder.restoreCallingIdentity(origId);
2651 }
2652 }
2653
2654 @Override
2655 public void startLockTaskModeByToken(IBinder token) {
2656 synchronized (mGlobalLock) {
2657 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2658 if (r == null) {
2659 return;
2660 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002661 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002662 }
2663 }
2664
2665 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002666 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002667 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002668 // This makes inner call to look as if it was initiated by system.
2669 long ident = Binder.clearCallingIdentity();
2670 try {
2671 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002672 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002673 MATCH_TASK_IN_STACKS_ONLY);
2674 if (task == null) {
2675 return;
2676 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002677
2678 // When starting lock task mode the stack must be in front and focused
2679 task.getStack().moveToFront("startSystemLockTaskMode");
2680 startLockTaskModeLocked(task, true /* isSystemCaller */);
2681 }
2682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
2685 }
2686
2687 @Override
2688 public void stopLockTaskModeByToken(IBinder token) {
2689 synchronized (mGlobalLock) {
2690 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2691 if (r == null) {
2692 return;
2693 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002694 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002695 }
2696 }
2697
2698 /**
2699 * This API should be called by SystemUI only when user perform certain action to dismiss
2700 * lock task mode. We should only dismiss pinned lock task mode in this case.
2701 */
2702 @Override
2703 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002704 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002705 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2706 }
2707
2708 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2709 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2710 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2711 return;
2712 }
2713
Wale Ogunwaled32da472018-11-16 07:19:28 -08002714 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002715 if (stack == null || task != stack.topTask()) {
2716 throw new IllegalArgumentException("Invalid task, not in foreground");
2717 }
2718
2719 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2720 // system or a specific app.
2721 // * System-initiated requests will only start the pinned mode (screen pinning)
2722 // * App-initiated requests
2723 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2724 // - will start the pinned mode, otherwise
2725 final int callingUid = Binder.getCallingUid();
2726 long ident = Binder.clearCallingIdentity();
2727 try {
2728 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002729 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002730
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002731 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002732 } finally {
2733 Binder.restoreCallingIdentity(ident);
2734 }
2735 }
2736
2737 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2738 final int callingUid = Binder.getCallingUid();
2739 long ident = Binder.clearCallingIdentity();
2740 try {
2741 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002742 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 }
2744 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2745 // task and jumping straight into a call in the case of emergency call back.
2746 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2747 if (tm != null) {
2748 tm.showInCallScreen(false);
2749 }
2750 } finally {
2751 Binder.restoreCallingIdentity(ident);
2752 }
2753 }
2754
2755 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002756 public void updateLockTaskPackages(int userId, String[] packages) {
2757 final int callingUid = Binder.getCallingUid();
2758 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2759 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2760 "updateLockTaskPackages()");
2761 }
2762 synchronized (this) {
2763 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2764 + Arrays.toString(packages));
2765 getLockTaskController().updateLockTaskPackages(userId, packages);
2766 }
2767 }
2768
2769 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002770 public boolean isInLockTaskMode() {
2771 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2772 }
2773
2774 @Override
2775 public int getLockTaskModeState() {
2776 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002777 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 }
2779 }
2780
2781 @Override
2782 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2783 synchronized (mGlobalLock) {
2784 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2785 if (r != null) {
2786 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002787 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002788 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002789 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 }
2791 }
2792 }
2793
2794 @Override
2795 public Bundle getActivityOptions(IBinder token) {
2796 final long origId = Binder.clearCallingIdentity();
2797 try {
2798 synchronized (mGlobalLock) {
2799 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2800 if (r != null) {
2801 final ActivityOptions activityOptions = r.takeOptionsLocked();
2802 return activityOptions == null ? null : activityOptions.toBundle();
2803 }
2804 return null;
2805 }
2806 } finally {
2807 Binder.restoreCallingIdentity(origId);
2808 }
2809 }
2810
2811 @Override
2812 public List<IBinder> getAppTasks(String callingPackage) {
2813 int callingUid = Binder.getCallingUid();
2814 long ident = Binder.clearCallingIdentity();
2815 try {
2816 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002817 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 }
2819 } finally {
2820 Binder.restoreCallingIdentity(ident);
2821 }
2822 }
2823
2824 @Override
2825 public void finishVoiceTask(IVoiceInteractionSession session) {
2826 synchronized (mGlobalLock) {
2827 final long origId = Binder.clearCallingIdentity();
2828 try {
2829 // TODO: VI Consider treating local voice interactions and voice tasks
2830 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002831 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 } finally {
2833 Binder.restoreCallingIdentity(origId);
2834 }
2835 }
2836
2837 }
2838
2839 @Override
2840 public boolean isTopOfTask(IBinder token) {
2841 synchronized (mGlobalLock) {
2842 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002843 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002844 }
2845 }
2846
2847 @Override
2848 public void notifyLaunchTaskBehindComplete(IBinder token) {
2849 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2850 }
2851
2852 @Override
2853 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002854 mH.post(() -> {
2855 synchronized (mGlobalLock) {
2856 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002857 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002858 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002859 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002860 } catch (RemoteException e) {
2861 }
2862 }
2863 }
2864
2865 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 }
2867
2868 /** Called from an app when assist data is ready. */
2869 @Override
2870 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2871 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002872 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873 synchronized (pae) {
2874 pae.result = extras;
2875 pae.structure = structure;
2876 pae.content = content;
2877 if (referrer != null) {
2878 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2879 }
2880 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002881 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002882 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2883 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 structure.setHomeActivity(pae.isHome);
2885 }
2886 pae.haveResult = true;
2887 pae.notifyAll();
2888 if (pae.intent == null && pae.receiver == null) {
2889 // Caller is just waiting for the result.
2890 return;
2891 }
2892 }
2893 // We are now ready to launch the assist activity.
2894 IAssistDataReceiver sendReceiver = null;
2895 Bundle sendBundle = null;
2896 synchronized (mGlobalLock) {
2897 buildAssistBundleLocked(pae, extras);
2898 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002899 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 if (!exists) {
2901 // Timed out.
2902 return;
2903 }
2904
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002905 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002906 // Caller wants result sent back to them.
2907 sendBundle = new Bundle();
2908 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2909 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2910 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2911 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2912 }
2913 }
2914 if (sendReceiver != null) {
2915 try {
2916 sendReceiver.onHandleAssistData(sendBundle);
2917 } catch (RemoteException e) {
2918 }
2919 return;
2920 }
2921
2922 final long ident = Binder.clearCallingIdentity();
2923 try {
2924 if (TextUtils.equals(pae.intent.getAction(),
2925 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2926 pae.intent.putExtras(pae.extras);
2927 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2928 } else {
2929 pae.intent.replaceExtras(pae.extras);
2930 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2931 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2932 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002933 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002934
2935 try {
2936 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2937 } catch (ActivityNotFoundException e) {
2938 Slog.w(TAG, "No activity to handle assist action.", e);
2939 }
2940 }
2941 } finally {
2942 Binder.restoreCallingIdentity(ident);
2943 }
2944 }
2945
2946 @Override
2947 public int addAppTask(IBinder activityToken, Intent intent,
2948 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2949 final int callingUid = Binder.getCallingUid();
2950 final long callingIdent = Binder.clearCallingIdentity();
2951
2952 try {
2953 synchronized (mGlobalLock) {
2954 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2955 if (r == null) {
2956 throw new IllegalArgumentException("Activity does not exist; token="
2957 + activityToken);
2958 }
2959 ComponentName comp = intent.getComponent();
2960 if (comp == null) {
2961 throw new IllegalArgumentException("Intent " + intent
2962 + " must specify explicit component");
2963 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002964 if (thumbnail.getWidth() != mThumbnailWidth
2965 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 throw new IllegalArgumentException("Bad thumbnail size: got "
2967 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002968 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 }
2970 if (intent.getSelector() != null) {
2971 intent.setSelector(null);
2972 }
2973 if (intent.getSourceBounds() != null) {
2974 intent.setSourceBounds(null);
2975 }
2976 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2977 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2978 // The caller has added this as an auto-remove task... that makes no
2979 // sense, so turn off auto-remove.
2980 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2981 }
2982 }
2983 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2984 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2985 if (ainfo.applicationInfo.uid != callingUid) {
2986 throw new SecurityException(
2987 "Can't add task for another application: target uid="
2988 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2989 }
2990
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002991 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002993 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002995 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 // The app has too many tasks already and we can't add any more
2997 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2998 return INVALID_TASK_ID;
2999 }
3000 task.lastTaskDescription.copyFrom(description);
3001
3002 // TODO: Send the thumbnail to WM to store it.
3003
3004 return task.taskId;
3005 }
3006 } finally {
3007 Binder.restoreCallingIdentity(callingIdent);
3008 }
3009 }
3010
3011 @Override
3012 public Point getAppTaskThumbnailSize() {
3013 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003014 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003015 }
3016 }
3017
3018 @Override
3019 public void setTaskResizeable(int taskId, int resizeableMode) {
3020 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003021 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3023 if (task == null) {
3024 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3025 return;
3026 }
3027 task.setResizeMode(resizeableMode);
3028 }
3029 }
3030
3031 @Override
3032 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003033 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 long ident = Binder.clearCallingIdentity();
3035 try {
3036 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003037 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003038 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 if (task == null) {
3040 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3041 return;
3042 }
3043 // Place the task in the right stack if it isn't there already based on
3044 // the requested bounds.
3045 // The stack transition logic is:
3046 // - a null bounds on a freeform task moves that task to fullscreen
3047 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3048 // that task to freeform
3049 // - otherwise the task is not moved
3050 ActivityStack stack = task.getStack();
3051 if (!task.getWindowConfiguration().canResizeTask()) {
3052 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3053 }
3054 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3055 stack = stack.getDisplay().getOrCreateStack(
3056 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3057 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3058 stack = stack.getDisplay().getOrCreateStack(
3059 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3060 }
3061
3062 // Reparent the task to the right stack if necessary
3063 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3064 if (stack != task.getStack()) {
3065 // Defer resume until the task is resized below
3066 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3067 DEFER_RESUME, "resizeTask");
3068 preserveWindow = false;
3069 }
3070
3071 // After reparenting (which only resizes the task to the stack bounds), resize the
3072 // task to the actual bounds provided
3073 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3074 }
3075 } finally {
3076 Binder.restoreCallingIdentity(ident);
3077 }
3078 }
3079
3080 @Override
3081 public boolean releaseActivityInstance(IBinder token) {
3082 synchronized (mGlobalLock) {
3083 final long origId = Binder.clearCallingIdentity();
3084 try {
3085 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3086 if (r == null) {
3087 return false;
3088 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003089 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 } finally {
3091 Binder.restoreCallingIdentity(origId);
3092 }
3093 }
3094 }
3095
3096 @Override
3097 public void releaseSomeActivities(IApplicationThread appInt) {
3098 synchronized (mGlobalLock) {
3099 final long origId = Binder.clearCallingIdentity();
3100 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003101 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003102 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 } finally {
3104 Binder.restoreCallingIdentity(origId);
3105 }
3106 }
3107 }
3108
3109 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003110 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003111 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 != PackageManager.PERMISSION_GRANTED) {
3113 throw new SecurityException("Requires permission "
3114 + android.Manifest.permission.DEVICE_POWER);
3115 }
3116
3117 synchronized (mGlobalLock) {
3118 long ident = Binder.clearCallingIdentity();
3119 if (mKeyguardShown != keyguardShowing) {
3120 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003121 final Message msg = PooledLambda.obtainMessage(
3122 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3123 keyguardShowing);
3124 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 }
3126 try {
wilsonshih177261f2019-02-22 12:02:18 +08003127 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003128 } finally {
3129 Binder.restoreCallingIdentity(ident);
3130 }
3131 }
3132
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003133 mH.post(() -> {
3134 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3135 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3136 }
3137 });
3138 }
3139
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003140 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003141 mH.post(() -> {
3142 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3143 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3144 }
3145 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 }
3147
3148 @Override
3149 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003150 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3151 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152
3153 final File passedIconFile = new File(filePath);
3154 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3155 passedIconFile.getName());
3156 if (!legitIconFile.getPath().equals(filePath)
3157 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3158 throw new IllegalArgumentException("Bad file path: " + filePath
3159 + " passed for userId " + userId);
3160 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003161 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 }
3163
3164 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003165 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3167 final ActivityOptions activityOptions = safeOptions != null
3168 ? safeOptions.getOptions(mStackSupervisor)
3169 : null;
3170 if (activityOptions == null
3171 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3172 || activityOptions.getCustomInPlaceResId() == 0) {
3173 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3174 "with valid animation");
3175 }
lumark588a3e82018-07-20 18:53:54 +08003176 // Get top display of front most application.
3177 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3178 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003179 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3180 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3181 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003182 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003183 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003184 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 }
3186
3187 @Override
3188 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003189 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003190 synchronized (mGlobalLock) {
3191 final long ident = Binder.clearCallingIdentity();
3192 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003193 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 if (stack == null) {
3195 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3196 return;
3197 }
3198 if (!stack.isActivityTypeStandardOrUndefined()) {
3199 throw new IllegalArgumentException(
3200 "Removing non-standard stack is not allowed.");
3201 }
3202 mStackSupervisor.removeStack(stack);
3203 } finally {
3204 Binder.restoreCallingIdentity(ident);
3205 }
3206 }
3207 }
3208
3209 @Override
3210 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003211 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212
3213 synchronized (mGlobalLock) {
3214 final long ident = Binder.clearCallingIdentity();
3215 try {
3216 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3217 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003218 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 } finally {
3220 Binder.restoreCallingIdentity(ident);
3221 }
3222 }
3223 }
3224
3225 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003226 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 synchronized (mGlobalLock) {
3228 long ident = Binder.clearCallingIdentity();
3229 try {
3230 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3231 if (r == null) {
3232 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003233 "toggleFreeformWindowingMode: No activity record matching token="
3234 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003235 }
3236
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003237 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003238 if (stack == null) {
3239 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3240 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 }
3242
Yunfan Chend967af82019-01-17 18:30:18 +09003243 if (!stack.inFreeformWindowingMode()
3244 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3245 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3246 + "toggle between fullscreen and freeform.");
3247 }
3248
3249 if (stack.inFreeformWindowingMode()) {
3250 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3251 } else {
3252 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3253 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 } finally {
3255 Binder.restoreCallingIdentity(ident);
3256 }
3257 }
3258 }
3259
3260 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3261 @Override
3262 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003263 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003265 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003266 }
3267
3268 /** Unregister a task stack listener so that it stops receiving callbacks. */
3269 @Override
3270 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003271 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003272 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003273 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003274 }
3275
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 @Override
3277 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3278 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3279 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3280 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3281 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3282 }
3283
3284 @Override
3285 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3286 IBinder activityToken, int flags) {
3287 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3288 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3289 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3290 }
3291
3292 @Override
3293 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3294 Bundle args) {
3295 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3296 true /* focused */, true /* newSessionId */, userHandle, args,
3297 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3298 }
3299
3300 @Override
3301 public Bundle getAssistContextExtras(int requestType) {
3302 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3303 null, null, true /* focused */, true /* newSessionId */,
3304 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3305 if (pae == null) {
3306 return null;
3307 }
3308 synchronized (pae) {
3309 while (!pae.haveResult) {
3310 try {
3311 pae.wait();
3312 } catch (InterruptedException e) {
3313 }
3314 }
3315 }
3316 synchronized (mGlobalLock) {
3317 buildAssistBundleLocked(pae, pae.result);
3318 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003319 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 }
3321 return pae.extras;
3322 }
3323
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003324 /**
3325 * Binder IPC calls go through the public entry point.
3326 * This can be called with or without the global lock held.
3327 */
3328 private static int checkCallingPermission(String permission) {
3329 return checkPermission(
3330 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3331 }
3332
3333 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003334 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003335 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3336 mAmInternal.enforceCallingPermission(permission, func);
3337 }
3338 }
3339
3340 @VisibleForTesting
3341 int checkGetTasksPermission(String permission, int pid, int uid) {
3342 return checkPermission(permission, pid, uid);
3343 }
3344
3345 static int checkPermission(String permission, int pid, int uid) {
3346 if (permission == null) {
3347 return PackageManager.PERMISSION_DENIED;
3348 }
3349 return checkComponentPermission(permission, pid, uid, -1, true);
3350 }
3351
Wale Ogunwale214f3482018-10-04 11:00:47 -07003352 public static int checkComponentPermission(String permission, int pid, int uid,
3353 int owningUid, boolean exported) {
3354 return ActivityManagerService.checkComponentPermission(
3355 permission, pid, uid, owningUid, exported);
3356 }
3357
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003358 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3359 if (getRecentTasks().isCallerRecents(callingUid)) {
3360 // Always allow the recents component to get tasks
3361 return true;
3362 }
3363
3364 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3365 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3366 if (!allowed) {
3367 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3368 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3369 // Temporary compatibility: some existing apps on the system image may
3370 // still be requesting the old permission and not switched to the new
3371 // one; if so, we'll still allow them full access. This means we need
3372 // to see if they are holding the old permission and are a system app.
3373 try {
3374 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3375 allowed = true;
3376 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3377 + " is using old GET_TASKS but privileged; allowing");
3378 }
3379 } catch (RemoteException e) {
3380 }
3381 }
3382 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3383 + " does not hold REAL_GET_TASKS; limiting output");
3384 }
3385 return allowed;
3386 }
3387
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3389 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3390 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3391 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003392 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 "enqueueAssistContext()");
3394
3395 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003396 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 if (activity == null) {
3398 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3399 return null;
3400 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003401 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3403 return null;
3404 }
3405 if (focused) {
3406 if (activityToken != null) {
3407 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3408 if (activity != caller) {
3409 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3410 + " is not current top " + activity);
3411 return null;
3412 }
3413 }
3414 } else {
3415 activity = ActivityRecord.forTokenLocked(activityToken);
3416 if (activity == null) {
3417 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3418 + " couldn't be found");
3419 return null;
3420 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003421 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3423 return null;
3424 }
3425 }
3426
3427 PendingAssistExtras pae;
3428 Bundle extras = new Bundle();
3429 if (args != null) {
3430 extras.putAll(args);
3431 }
3432 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003433 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434
3435 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3436 userHandle);
3437 pae.isHome = activity.isActivityTypeHome();
3438
3439 // Increment the sessionId if necessary
3440 if (newSessionId) {
3441 mViSessionId++;
3442 }
3443 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003444 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3445 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003447 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003448 } catch (RemoteException e) {
3449 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3450 return null;
3451 }
3452 return pae;
3453 }
3454 }
3455
3456 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3457 if (result != null) {
3458 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3459 }
3460 if (pae.hint != null) {
3461 pae.extras.putBoolean(pae.hint, true);
3462 }
3463 }
3464
3465 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3466 IAssistDataReceiver receiver;
3467 synchronized (mGlobalLock) {
3468 mPendingAssistExtras.remove(pae);
3469 receiver = pae.receiver;
3470 }
3471 if (receiver != null) {
3472 // Caller wants result sent back to them.
3473 Bundle sendBundle = new Bundle();
3474 // At least return the receiver extras
3475 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3476 try {
3477 pae.receiver.onHandleAssistData(sendBundle);
3478 } catch (RemoteException e) {
3479 }
3480 }
3481 }
3482
3483 public class PendingAssistExtras extends Binder implements Runnable {
3484 public final ActivityRecord activity;
3485 public boolean isHome;
3486 public final Bundle extras;
3487 public final Intent intent;
3488 public final String hint;
3489 public final IAssistDataReceiver receiver;
3490 public final int userHandle;
3491 public boolean haveResult = false;
3492 public Bundle result = null;
3493 public AssistStructure structure = null;
3494 public AssistContent content = null;
3495 public Bundle receiverExtras;
3496
3497 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3498 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3499 int _userHandle) {
3500 activity = _activity;
3501 extras = _extras;
3502 intent = _intent;
3503 hint = _hint;
3504 receiver = _receiver;
3505 receiverExtras = _receiverExtras;
3506 userHandle = _userHandle;
3507 }
3508
3509 @Override
3510 public void run() {
3511 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3512 synchronized (this) {
3513 haveResult = true;
3514 notifyAll();
3515 }
3516 pendingAssistExtrasTimedOut(this);
3517 }
3518 }
3519
3520 @Override
3521 public boolean isAssistDataAllowedOnCurrentActivity() {
3522 int userId;
3523 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003524 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3526 return false;
3527 }
3528
3529 final ActivityRecord activity = focusedStack.getTopActivity();
3530 if (activity == null) {
3531 return false;
3532 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003533 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003534 }
3535 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3536 }
3537
3538 @Override
3539 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3540 long ident = Binder.clearCallingIdentity();
3541 try {
3542 synchronized (mGlobalLock) {
3543 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003544 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003545 if (top != caller) {
3546 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3547 + " is not current top " + top);
3548 return false;
3549 }
3550 if (!top.nowVisible) {
3551 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3552 + " is not visible");
3553 return false;
3554 }
3555 }
3556 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3557 token);
3558 } finally {
3559 Binder.restoreCallingIdentity(ident);
3560 }
3561 }
3562
3563 @Override
3564 public boolean isRootVoiceInteraction(IBinder token) {
3565 synchronized (mGlobalLock) {
3566 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3567 if (r == null) {
3568 return false;
3569 }
3570 return r.rootVoiceInteraction;
3571 }
3572 }
3573
Wale Ogunwalef6733932018-06-27 05:14:34 -07003574 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3575 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3576 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3577 if (activityToCallback == null) return;
3578 activityToCallback.setVoiceSessionLocked(voiceSession);
3579
3580 // Inform the activity
3581 try {
3582 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3583 voiceInteractor);
3584 long token = Binder.clearCallingIdentity();
3585 try {
3586 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3587 } finally {
3588 Binder.restoreCallingIdentity(token);
3589 }
3590 // TODO: VI Should we cache the activity so that it's easier to find later
3591 // rather than scan through all the stacks and activities?
3592 } catch (RemoteException re) {
3593 activityToCallback.clearVoiceSessionLocked();
3594 // TODO: VI Should this terminate the voice session?
3595 }
3596 }
3597
3598 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3599 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3600 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3601 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3602 boolean wasRunningVoice = mRunningVoice != null;
3603 mRunningVoice = session;
3604 if (!wasRunningVoice) {
3605 mVoiceWakeLock.acquire();
3606 updateSleepIfNeededLocked();
3607 }
3608 }
3609 }
3610
3611 void finishRunningVoiceLocked() {
3612 if (mRunningVoice != null) {
3613 mRunningVoice = null;
3614 mVoiceWakeLock.release();
3615 updateSleepIfNeededLocked();
3616 }
3617 }
3618
3619 @Override
3620 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3621 synchronized (mGlobalLock) {
3622 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3623 if (keepAwake) {
3624 mVoiceWakeLock.acquire();
3625 } else {
3626 mVoiceWakeLock.release();
3627 }
3628 }
3629 }
3630 }
3631
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 @Override
3633 public ComponentName getActivityClassForToken(IBinder token) {
3634 synchronized (mGlobalLock) {
3635 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3636 if (r == null) {
3637 return null;
3638 }
3639 return r.intent.getComponent();
3640 }
3641 }
3642
3643 @Override
3644 public String getPackageForToken(IBinder token) {
3645 synchronized (mGlobalLock) {
3646 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3647 if (r == null) {
3648 return null;
3649 }
3650 return r.packageName;
3651 }
3652 }
3653
3654 @Override
3655 public void showLockTaskEscapeMessage(IBinder token) {
3656 synchronized (mGlobalLock) {
3657 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3658 if (r == null) {
3659 return;
3660 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003661 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003662 }
3663 }
3664
3665 @Override
3666 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003667 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 final long token = Binder.clearCallingIdentity();
3669 try {
3670 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003671 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003672 }
3673 } finally {
3674 Binder.restoreCallingIdentity(token);
3675 }
3676 }
3677
3678 /**
3679 * Try to place task to provided position. The final position might be different depending on
3680 * current user and stacks state. The task will be moved to target stack if it's currently in
3681 * different stack.
3682 */
3683 @Override
3684 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003685 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003686 synchronized (mGlobalLock) {
3687 long ident = Binder.clearCallingIdentity();
3688 try {
3689 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3690 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003691 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003692 if (task == null) {
3693 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3694 + taskId);
3695 }
3696
Wale Ogunwaled32da472018-11-16 07:19:28 -08003697 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003698
3699 if (stack == null) {
3700 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3701 + stackId);
3702 }
3703 if (!stack.isActivityTypeStandardOrUndefined()) {
3704 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3705 + " the position of task " + taskId + " in/to non-standard stack");
3706 }
3707
3708 // TODO: Have the callers of this API call a separate reparent method if that is
3709 // what they intended to do vs. having this method also do reparenting.
3710 if (task.getStack() == stack) {
3711 // Change position in current stack.
3712 stack.positionChildAt(task, position);
3713 } else {
3714 // Reparent to new stack.
3715 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3716 !DEFER_RESUME, "positionTaskInStack");
3717 }
3718 } finally {
3719 Binder.restoreCallingIdentity(ident);
3720 }
3721 }
3722 }
3723
3724 @Override
3725 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3726 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3727 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3728 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3729 synchronized (mGlobalLock) {
3730 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3731 if (record == null) {
3732 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3733 + "found for: " + token);
3734 }
3735 record.setSizeConfigurations(horizontalSizeConfiguration,
3736 verticalSizeConfigurations, smallestSizeConfigurations);
3737 }
3738 }
3739
3740 /**
3741 * Dismisses split-screen multi-window mode.
3742 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3743 */
3744 @Override
3745 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003746 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003747 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3748 final long ident = Binder.clearCallingIdentity();
3749 try {
3750 synchronized (mGlobalLock) {
3751 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003752 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 if (stack == null) {
3754 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3755 return;
3756 }
3757
3758 if (toTop) {
3759 // Caller wants the current split-screen primary stack to be the top stack after
3760 // it goes fullscreen, so move it to the front.
3761 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003762 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003763 // In this case the current split-screen primary stack shouldn't be the top
3764 // stack after it goes fullscreen, but it current has focus, so we move the
3765 // focus to the top-most split-screen secondary stack next to it.
3766 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3767 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3768 if (otherStack != null) {
3769 otherStack.moveToFront("dismissSplitScreenMode_other");
3770 }
3771 }
3772
Evan Rosky10475742018-09-05 19:02:48 -07003773 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003774 }
3775 } finally {
3776 Binder.restoreCallingIdentity(ident);
3777 }
3778 }
3779
3780 /**
3781 * Dismisses Pip
3782 * @param animate True if the dismissal should be animated.
3783 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3784 * default animation duration should be used.
3785 */
3786 @Override
3787 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003788 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003789 final long ident = Binder.clearCallingIdentity();
3790 try {
3791 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003792 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003793 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 if (stack == null) {
3795 Slog.w(TAG, "dismissPip: pinned stack not found.");
3796 return;
3797 }
3798 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3799 throw new IllegalArgumentException("Stack: " + stack
3800 + " doesn't support animated resize.");
3801 }
3802 if (animate) {
3803 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3804 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3805 } else {
3806 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3807 }
3808 }
3809 } finally {
3810 Binder.restoreCallingIdentity(ident);
3811 }
3812 }
3813
3814 @Override
3815 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003816 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003817 synchronized (mGlobalLock) {
3818 mSuppressResizeConfigChanges = suppress;
3819 }
3820 }
3821
3822 /**
3823 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3824 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3825 * activity and clearing the task at the same time.
3826 */
3827 @Override
3828 // TODO: API should just be about changing windowing modes...
3829 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003830 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 "moveTasksToFullscreenStack()");
3832 synchronized (mGlobalLock) {
3833 final long origId = Binder.clearCallingIdentity();
3834 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003835 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 if (stack != null){
3837 if (!stack.isActivityTypeStandardOrUndefined()) {
3838 throw new IllegalArgumentException(
3839 "You can't move tasks from non-standard stacks.");
3840 }
3841 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3842 }
3843 } finally {
3844 Binder.restoreCallingIdentity(origId);
3845 }
3846 }
3847 }
3848
3849 /**
3850 * Moves the top activity in the input stackId to the pinned stack.
3851 *
3852 * @param stackId Id of stack to move the top activity to pinned stack.
3853 * @param bounds Bounds to use for pinned stack.
3854 *
3855 * @return True if the top activity of the input stack was successfully moved to the pinned
3856 * stack.
3857 */
3858 @Override
3859 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003860 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003861 "moveTopActivityToPinnedStack()");
3862 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003863 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3865 + "Device doesn't support picture-in-picture mode");
3866 }
3867
3868 long ident = Binder.clearCallingIdentity();
3869 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003870 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003871 } finally {
3872 Binder.restoreCallingIdentity(ident);
3873 }
3874 }
3875 }
3876
3877 @Override
3878 public boolean isInMultiWindowMode(IBinder token) {
3879 final long origId = Binder.clearCallingIdentity();
3880 try {
3881 synchronized (mGlobalLock) {
3882 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3883 if (r == null) {
3884 return false;
3885 }
3886 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3887 return r.inMultiWindowMode();
3888 }
3889 } finally {
3890 Binder.restoreCallingIdentity(origId);
3891 }
3892 }
3893
3894 @Override
3895 public boolean isInPictureInPictureMode(IBinder token) {
3896 final long origId = Binder.clearCallingIdentity();
3897 try {
3898 synchronized (mGlobalLock) {
3899 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3900 }
3901 } finally {
3902 Binder.restoreCallingIdentity(origId);
3903 }
3904 }
3905
3906 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003907 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3908 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 return false;
3910 }
3911
3912 // If we are animating to fullscreen then we have already dispatched the PIP mode
3913 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003914 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3915 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 }
3917
3918 @Override
3919 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3920 final long origId = Binder.clearCallingIdentity();
3921 try {
3922 synchronized (mGlobalLock) {
3923 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3924 "enterPictureInPictureMode", token, params);
3925
3926 // If the activity is already in picture in picture mode, then just return early
3927 if (isInPictureInPictureMode(r)) {
3928 return true;
3929 }
3930
3931 // Activity supports picture-in-picture, now check that we can enter PiP at this
3932 // point, if it is
3933 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3934 false /* beforeStopping */)) {
3935 return false;
3936 }
3937
3938 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003939 synchronized (mGlobalLock) {
3940 // Only update the saved args from the args that are set
3941 r.pictureInPictureArgs.copyOnlySet(params);
3942 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3943 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3944 // Adjust the source bounds by the insets for the transition down
3945 final Rect sourceBounds = new Rect(
3946 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003947 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003948 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003949 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003950 stack.setPictureInPictureAspectRatio(aspectRatio);
3951 stack.setPictureInPictureActions(actions);
3952 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3953 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3954 logPictureInPictureArgs(params);
3955 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 };
3957
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003958 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 // If the keyguard is showing or occluded, then try and dismiss it before
3960 // entering picture-in-picture (this will prompt the user to authenticate if the
3961 // device is currently locked).
3962 dismissKeyguard(token, new KeyguardDismissCallback() {
3963 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003964 public void onDismissSucceeded() {
3965 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 }
3967 }, null /* message */);
3968 } else {
3969 // Enter picture in picture immediately otherwise
3970 enterPipRunnable.run();
3971 }
3972 return true;
3973 }
3974 } finally {
3975 Binder.restoreCallingIdentity(origId);
3976 }
3977 }
3978
3979 @Override
3980 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3981 final long origId = Binder.clearCallingIdentity();
3982 try {
3983 synchronized (mGlobalLock) {
3984 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3985 "setPictureInPictureParams", token, params);
3986
3987 // Only update the saved args from the args that are set
3988 r.pictureInPictureArgs.copyOnlySet(params);
3989 if (r.inPinnedWindowingMode()) {
3990 // If the activity is already in picture-in-picture, update the pinned stack now
3991 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3992 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003993 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003994 if (!stack.isAnimatingBoundsToFullscreen()) {
3995 stack.setPictureInPictureAspectRatio(
3996 r.pictureInPictureArgs.getAspectRatio());
3997 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3998 }
3999 }
4000 logPictureInPictureArgs(params);
4001 }
4002 } finally {
4003 Binder.restoreCallingIdentity(origId);
4004 }
4005 }
4006
4007 @Override
4008 public int getMaxNumPictureInPictureActions(IBinder token) {
4009 // Currently, this is a static constant, but later, we may change this to be dependent on
4010 // the context of the activity
4011 return 3;
4012 }
4013
4014 private void logPictureInPictureArgs(PictureInPictureParams params) {
4015 if (params.hasSetActions()) {
4016 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4017 params.getActions().size());
4018 }
4019 if (params.hasSetAspectRatio()) {
4020 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4021 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4022 MetricsLogger.action(lm);
4023 }
4024 }
4025
4026 /**
4027 * Checks the state of the system and the activity associated with the given {@param token} to
4028 * verify that picture-in-picture is supported for that activity.
4029 *
4030 * @return the activity record for the given {@param token} if all the checks pass.
4031 */
4032 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4033 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 throw new IllegalStateException(caller
4036 + ": Device doesn't support picture-in-picture mode.");
4037 }
4038
4039 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4040 if (r == null) {
4041 throw new IllegalStateException(caller
4042 + ": Can't find activity for token=" + token);
4043 }
4044
4045 if (!r.supportsPictureInPicture()) {
4046 throw new IllegalStateException(caller
4047 + ": Current activity does not support picture-in-picture.");
4048 }
4049
4050 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004051 && !mWindowManager.isValidPictureInPictureAspectRatio(
4052 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 final float minAspectRatio = mContext.getResources().getFloat(
4054 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4055 final float maxAspectRatio = mContext.getResources().getFloat(
4056 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4057 throw new IllegalArgumentException(String.format(caller
4058 + ": Aspect ratio is too extreme (must be between %f and %f).",
4059 minAspectRatio, maxAspectRatio));
4060 }
4061
4062 // Truncate the number of actions if necessary
4063 params.truncateActions(getMaxNumPictureInPictureActions(token));
4064
4065 return r;
4066 }
4067
4068 @Override
4069 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004070 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 synchronized (mGlobalLock) {
4072 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4073 if (r == null) {
4074 throw new IllegalArgumentException("Activity does not exist; token="
4075 + activityToken);
4076 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004077 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 }
4079 }
4080
4081 @Override
4082 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4083 Rect tempDockedTaskInsetBounds,
4084 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004085 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 long ident = Binder.clearCallingIdentity();
4087 try {
4088 synchronized (mGlobalLock) {
4089 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4090 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4091 PRESERVE_WINDOWS);
4092 }
4093 } finally {
4094 Binder.restoreCallingIdentity(ident);
4095 }
4096 }
4097
4098 @Override
4099 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004100 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004101 final long ident = Binder.clearCallingIdentity();
4102 try {
4103 synchronized (mGlobalLock) {
4104 mStackSupervisor.setSplitScreenResizing(resizing);
4105 }
4106 } finally {
4107 Binder.restoreCallingIdentity(ident);
4108 }
4109 }
4110
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004111 /**
4112 * Check that we have the features required for VR-related API calls, and throw an exception if
4113 * not.
4114 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004115 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004116 if (!mContext.getPackageManager().hasSystemFeature(
4117 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4118 throw new UnsupportedOperationException("VR mode not supported on this device!");
4119 }
4120 }
4121
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 @Override
4123 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004124 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125
4126 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4127
4128 ActivityRecord r;
4129 synchronized (mGlobalLock) {
4130 r = ActivityRecord.isInStackLocked(token);
4131 }
4132
4133 if (r == null) {
4134 throw new IllegalArgumentException();
4135 }
4136
4137 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004138 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004139 VrManagerInternal.NO_ERROR) {
4140 return err;
4141 }
4142
4143 // Clear the binder calling uid since this path may call moveToTask().
4144 final long callingId = Binder.clearCallingIdentity();
4145 try {
4146 synchronized (mGlobalLock) {
4147 r.requestedVrComponent = (enabled) ? packageName : null;
4148
4149 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004150 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004151 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 }
4153 return 0;
4154 }
4155 } finally {
4156 Binder.restoreCallingIdentity(callingId);
4157 }
4158 }
4159
4160 @Override
4161 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4162 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4163 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004164 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4166 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4167 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004168 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004169 || activity.voiceSession != null) {
4170 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4171 return;
4172 }
4173 if (activity.pendingVoiceInteractionStart) {
4174 Slog.w(TAG, "Pending start of voice interaction already.");
4175 return;
4176 }
4177 activity.pendingVoiceInteractionStart = true;
4178 }
4179 LocalServices.getService(VoiceInteractionManagerInternal.class)
4180 .startLocalVoiceInteraction(callingActivity, options);
4181 }
4182
4183 @Override
4184 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4185 LocalServices.getService(VoiceInteractionManagerInternal.class)
4186 .stopLocalVoiceInteraction(callingActivity);
4187 }
4188
4189 @Override
4190 public boolean supportsLocalVoiceInteraction() {
4191 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4192 .supportsLocalVoiceInteraction();
4193 }
4194
4195 /** Notifies all listeners when the pinned stack animation starts. */
4196 @Override
4197 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004198 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004199 }
4200
4201 /** Notifies all listeners when the pinned stack animation ends. */
4202 @Override
4203 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004204 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 }
4206
4207 @Override
4208 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004209 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 final long ident = Binder.clearCallingIdentity();
4211 try {
4212 synchronized (mGlobalLock) {
4213 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4214 }
4215 } finally {
4216 Binder.restoreCallingIdentity(ident);
4217 }
4218 }
4219
4220 @Override
4221 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004222 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004223
4224 synchronized (mGlobalLock) {
4225 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004226 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 // Call might come when display is not yet added or has already been removed.
4228 if (DEBUG_CONFIGURATION) {
4229 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4230 + displayId);
4231 }
4232 return false;
4233 }
4234
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004237 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004238 }
4239
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004240 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004241 final Message msg = PooledLambda.obtainMessage(
4242 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4243 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 }
4245
4246 final long origId = Binder.clearCallingIdentity();
4247 try {
4248 if (values != null) {
4249 Settings.System.clearConfiguration(values);
4250 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004251 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4253 return mTmpUpdateConfigurationResult.changes != 0;
4254 } finally {
4255 Binder.restoreCallingIdentity(origId);
4256 }
4257 }
4258 }
4259
4260 @Override
4261 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004262 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263
4264 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004265 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004267 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 }
4269
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004270 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004271 final Message msg = PooledLambda.obtainMessage(
4272 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4273 DEFAULT_DISPLAY);
4274 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 }
4276
4277 final long origId = Binder.clearCallingIdentity();
4278 try {
4279 if (values != null) {
4280 Settings.System.clearConfiguration(values);
4281 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004283 UserHandle.USER_NULL, false /* deferResume */,
4284 mTmpUpdateConfigurationResult);
4285 return mTmpUpdateConfigurationResult.changes != 0;
4286 } finally {
4287 Binder.restoreCallingIdentity(origId);
4288 }
4289 }
4290 }
4291
4292 @Override
4293 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4294 CharSequence message) {
4295 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004296 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004297 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4298 }
4299 final long callingId = Binder.clearCallingIdentity();
4300 try {
4301 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004302 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 }
4304 } finally {
4305 Binder.restoreCallingIdentity(callingId);
4306 }
4307 }
4308
4309 @Override
4310 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004311 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 "cancelTaskWindowTransition()");
4313 final long ident = Binder.clearCallingIdentity();
4314 try {
4315 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004316 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 MATCH_TASK_IN_STACKS_ONLY);
4318 if (task == null) {
4319 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4320 return;
4321 }
4322 task.cancelWindowTransition();
4323 }
4324 } finally {
4325 Binder.restoreCallingIdentity(ident);
4326 }
4327 }
4328
4329 @Override
4330 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004331 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 final long ident = Binder.clearCallingIdentity();
4333 try {
4334 final TaskRecord task;
4335 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004336 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004337 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4338 if (task == null) {
4339 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4340 return null;
4341 }
4342 }
4343 // Don't call this while holding the lock as this operation might hit the disk.
4344 return task.getSnapshot(reducedResolution);
4345 } finally {
4346 Binder.restoreCallingIdentity(ident);
4347 }
4348 }
4349
4350 @Override
4351 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4352 synchronized (mGlobalLock) {
4353 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4354 if (r == null) {
4355 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4356 + token);
4357 return;
4358 }
4359 final long origId = Binder.clearCallingIdentity();
4360 try {
4361 r.setDisablePreviewScreenshots(disable);
4362 } finally {
4363 Binder.restoreCallingIdentity(origId);
4364 }
4365 }
4366 }
4367
4368 /** Return the user id of the last resumed activity. */
4369 @Override
4370 public @UserIdInt
4371 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004372 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4374 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004375 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004376 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004378 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380 }
4381
4382 @Override
4383 public void updateLockTaskFeatures(int userId, int flags) {
4384 final int callingUid = Binder.getCallingUid();
4385 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 "updateLockTaskFeatures()");
4388 }
4389 synchronized (mGlobalLock) {
4390 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4391 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004392 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 }
4394 }
4395
4396 @Override
4397 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4398 synchronized (mGlobalLock) {
4399 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4400 if (r == null) {
4401 return;
4402 }
4403 final long origId = Binder.clearCallingIdentity();
4404 try {
4405 r.setShowWhenLocked(showWhenLocked);
4406 } finally {
4407 Binder.restoreCallingIdentity(origId);
4408 }
4409 }
4410 }
4411
4412 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004413 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4414 synchronized (mGlobalLock) {
4415 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4416 if (r == null) {
4417 return;
4418 }
4419 final long origId = Binder.clearCallingIdentity();
4420 try {
4421 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4422 } finally {
4423 Binder.restoreCallingIdentity(origId);
4424 }
4425 }
4426 }
4427
4428 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4430 synchronized (mGlobalLock) {
4431 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4432 if (r == null) {
4433 return;
4434 }
4435 final long origId = Binder.clearCallingIdentity();
4436 try {
4437 r.setTurnScreenOn(turnScreenOn);
4438 } finally {
4439 Binder.restoreCallingIdentity(origId);
4440 }
4441 }
4442 }
4443
4444 @Override
4445 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 "registerRemoteAnimations");
4448 definition.setCallingPid(Binder.getCallingPid());
4449 synchronized (mGlobalLock) {
4450 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4451 if (r == null) {
4452 return;
4453 }
4454 final long origId = Binder.clearCallingIdentity();
4455 try {
4456 r.registerRemoteAnimations(definition);
4457 } finally {
4458 Binder.restoreCallingIdentity(origId);
4459 }
4460 }
4461 }
4462
4463 @Override
4464 public void registerRemoteAnimationForNextActivityStart(String packageName,
4465 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004466 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 "registerRemoteAnimationForNextActivityStart");
4468 adapter.setCallingPid(Binder.getCallingPid());
4469 synchronized (mGlobalLock) {
4470 final long origId = Binder.clearCallingIdentity();
4471 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004472 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 packageName, adapter);
4474 } finally {
4475 Binder.restoreCallingIdentity(origId);
4476 }
4477 }
4478 }
4479
Evan Rosky966759f2019-01-15 10:33:58 -08004480 @Override
4481 public void registerRemoteAnimationsForDisplay(int displayId,
4482 RemoteAnimationDefinition definition) {
4483 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4484 "registerRemoteAnimations");
4485 definition.setCallingPid(Binder.getCallingPid());
4486 synchronized (mGlobalLock) {
4487 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4488 if (display == null) {
4489 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4490 return;
4491 }
4492 final long origId = Binder.clearCallingIdentity();
4493 try {
4494 display.mDisplayContent.registerRemoteAnimations(definition);
4495 } finally {
4496 Binder.restoreCallingIdentity(origId);
4497 }
4498 }
4499 }
4500
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4502 @Override
4503 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4504 synchronized (mGlobalLock) {
4505 final long origId = Binder.clearCallingIdentity();
4506 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004507 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 } finally {
4509 Binder.restoreCallingIdentity(origId);
4510 }
4511 }
4512 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004513
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004514 @Override
4515 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004516 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004517 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004518 final int pid = Binder.getCallingPid();
4519 final WindowProcessController wpc = mPidMap.get(pid);
4520 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004521 }
4522 }
4523
4524 @Override
4525 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004526 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004527 != PERMISSION_GRANTED) {
4528 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4529 + Binder.getCallingPid()
4530 + ", uid=" + Binder.getCallingUid()
4531 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4532 Slog.w(TAG, msg);
4533 throw new SecurityException(msg);
4534 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004535 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004536 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004537 final int pid = Binder.getCallingPid();
4538 final WindowProcessController proc = mPidMap.get(pid);
4539 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004540 }
4541 }
4542
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004543 @Override
4544 public void stopAppSwitches() {
4545 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4546 synchronized (mGlobalLock) {
4547 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4548 mDidAppSwitch = false;
4549 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4550 }
4551 }
4552
4553 @Override
4554 public void resumeAppSwitches() {
4555 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4556 synchronized (mGlobalLock) {
4557 // Note that we don't execute any pending app switches... we will
4558 // let those wait until either the timeout, or the next start
4559 // activity request.
4560 mAppSwitchesAllowedTime = 0;
4561 }
4562 }
4563
4564 void onStartActivitySetDidAppSwitch() {
4565 if (mDidAppSwitch) {
4566 // This is the second allowed switch since we stopped switches, so now just generally
4567 // allow switches. Use case:
4568 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4569 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4570 // anyone to switch again).
4571 mAppSwitchesAllowedTime = 0;
4572 } else {
4573 mDidAppSwitch = true;
4574 }
4575 }
4576
4577 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004578 boolean shouldDisableNonVrUiLocked() {
4579 return mVrController.shouldDisableNonVrUiLocked();
4580 }
4581
Wale Ogunwale53783742018-09-16 10:21:51 -07004582 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004583 // VR apps are expected to run in a main display. If an app is turning on VR for
4584 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4585 // fullscreen stack before enabling VR Mode.
4586 // TODO: The goal of this code is to keep the VR app on the main display. When the
4587 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4588 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4589 // option would be a better choice here.
4590 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4591 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4592 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004593 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004594 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004595 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004596 }
4597 mH.post(() -> {
4598 if (!mVrController.onVrModeChanged(r)) {
4599 return;
4600 }
4601 synchronized (mGlobalLock) {
4602 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4603 mWindowManager.disableNonVrUi(disableNonVrUi);
4604 if (disableNonVrUi) {
4605 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4606 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004607 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004608 }
4609 }
4610 });
4611 }
4612
Wale Ogunwale53783742018-09-16 10:21:51 -07004613 @Override
4614 public int getPackageScreenCompatMode(String packageName) {
4615 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4616 synchronized (mGlobalLock) {
4617 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4618 }
4619 }
4620
4621 @Override
4622 public void setPackageScreenCompatMode(String packageName, int mode) {
4623 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4624 "setPackageScreenCompatMode");
4625 synchronized (mGlobalLock) {
4626 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4627 }
4628 }
4629
4630 @Override
4631 public boolean getPackageAskScreenCompat(String packageName) {
4632 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4633 synchronized (mGlobalLock) {
4634 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4635 }
4636 }
4637
4638 @Override
4639 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4640 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4641 "setPackageAskScreenCompat");
4642 synchronized (mGlobalLock) {
4643 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4644 }
4645 }
4646
Wale Ogunwale64258362018-10-16 15:13:37 -07004647 public static String relaunchReasonToString(int relaunchReason) {
4648 switch (relaunchReason) {
4649 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4650 return "window_resize";
4651 case RELAUNCH_REASON_FREE_RESIZE:
4652 return "free_resize";
4653 default:
4654 return null;
4655 }
4656 }
4657
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004658 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004659 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004660 }
4661
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004662 /** Pokes the task persister. */
4663 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4664 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4665 }
4666
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004667 boolean isKeyguardLocked() {
4668 return mKeyguardController.isKeyguardLocked();
4669 }
4670
Garfield Tan01548632018-11-27 10:15:48 -08004671 /**
4672 * Clears launch params for the given package.
4673 * @param packageNames the names of the packages of which the launch params are to be cleared
4674 */
4675 @Override
4676 public void clearLaunchParamsForPackages(List<String> packageNames) {
4677 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4678 "clearLaunchParamsForPackages");
4679 synchronized (mGlobalLock) {
4680 for (int i = 0; i < packageNames.size(); ++i) {
4681 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4682 }
4683 }
4684 }
4685
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004686 /**
4687 * Makes the display with the given id a single task instance display. I.e the display can only
4688 * contain one task.
4689 */
4690 @Override
4691 public void setDisplayToSingleTaskInstance(int displayId) {
4692 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4693 "setDisplayToSingleTaskInstance");
4694 final long origId = Binder.clearCallingIdentity();
4695 try {
4696 final ActivityDisplay display =
4697 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4698 if (display != null) {
4699 display.setDisplayToSingleTaskInstance();
4700 }
4701 } finally {
4702 Binder.restoreCallingIdentity(origId);
4703 }
4704 }
4705
Wale Ogunwale31913b52018-10-13 08:29:31 -07004706 void dumpLastANRLocked(PrintWriter pw) {
4707 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4708 if (mLastANRState == null) {
4709 pw.println(" <no ANR has occurred since boot>");
4710 } else {
4711 pw.println(mLastANRState);
4712 }
4713 }
4714
4715 void dumpLastANRTracesLocked(PrintWriter pw) {
4716 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4717
4718 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4719 if (ArrayUtils.isEmpty(files)) {
4720 pw.println(" <no ANR has occurred since boot>");
4721 return;
4722 }
4723 // Find the latest file.
4724 File latest = null;
4725 for (File f : files) {
4726 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4727 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004728 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004729 }
4730 pw.print("File: ");
4731 pw.print(latest.getName());
4732 pw.println();
4733 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4734 String line;
4735 while ((line = in.readLine()) != null) {
4736 pw.println(line);
4737 }
4738 } catch (IOException e) {
4739 pw.print("Unable to read: ");
4740 pw.print(e);
4741 pw.println();
4742 }
4743 }
4744
4745 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4746 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4747 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4748 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4749 }
4750
4751 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4752 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4753 pw.println(header);
4754
Wale Ogunwaled32da472018-11-16 07:19:28 -08004755 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004756 dumpPackage);
4757 boolean needSep = printedAnything;
4758
4759 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004760 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004761 " ResumedActivity: ");
4762 if (printed) {
4763 printedAnything = true;
4764 needSep = false;
4765 }
4766
4767 if (dumpPackage == null) {
4768 if (needSep) {
4769 pw.println();
4770 }
4771 printedAnything = true;
4772 mStackSupervisor.dump(pw, " ");
4773 }
4774
4775 if (!printedAnything) {
4776 pw.println(" (nothing)");
4777 }
4778 }
4779
4780 void dumpActivityContainersLocked(PrintWriter pw) {
4781 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004782 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004783 pw.println(" ");
4784 }
4785
4786 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4787 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4788 getActivityStartController().dump(pw, "", dumpPackage);
4789 }
4790
4791 /**
4792 * There are three things that cmd can be:
4793 * - a flattened component name that matches an existing activity
4794 * - the cmd arg isn't the flattened component name of an existing activity:
4795 * dump all activity whose component contains the cmd as a substring
4796 * - A hex number of the ActivityRecord object instance.
4797 *
4798 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4799 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4800 */
4801 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4802 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4803 ArrayList<ActivityRecord> activities;
4804
4805 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004806 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004807 dumpFocusedStackOnly);
4808 }
4809
4810 if (activities.size() <= 0) {
4811 return false;
4812 }
4813
4814 String[] newArgs = new String[args.length - opti];
4815 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4816
4817 TaskRecord lastTask = null;
4818 boolean needSep = false;
4819 for (int i = activities.size() - 1; i >= 0; i--) {
4820 ActivityRecord r = activities.get(i);
4821 if (needSep) {
4822 pw.println();
4823 }
4824 needSep = true;
4825 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004826 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004827 if (lastTask != task) {
4828 lastTask = task;
4829 pw.print("TASK "); pw.print(lastTask.affinity);
4830 pw.print(" id="); pw.print(lastTask.taskId);
4831 pw.print(" userId="); pw.println(lastTask.userId);
4832 if (dumpAll) {
4833 lastTask.dump(pw, " ");
4834 }
4835 }
4836 }
4837 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4838 }
4839 return true;
4840 }
4841
4842 /**
4843 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4844 * there is a thread associated with the activity.
4845 */
4846 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4847 final ActivityRecord r, String[] args, boolean dumpAll) {
4848 String innerPrefix = prefix + " ";
4849 synchronized (mGlobalLock) {
4850 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4851 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4852 pw.print(" pid=");
4853 if (r.hasProcess()) pw.println(r.app.getPid());
4854 else pw.println("(not running)");
4855 if (dumpAll) {
4856 r.dump(pw, innerPrefix);
4857 }
4858 }
4859 if (r.attachedToProcess()) {
4860 // flush anything that is already in the PrintWriter since the thread is going
4861 // to write to the file descriptor directly
4862 pw.flush();
4863 try {
4864 TransferPipe tp = new TransferPipe();
4865 try {
4866 r.app.getThread().dumpActivity(tp.getWriteFd(),
4867 r.appToken, innerPrefix, args);
4868 tp.go(fd);
4869 } finally {
4870 tp.kill();
4871 }
4872 } catch (IOException e) {
4873 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4874 } catch (RemoteException e) {
4875 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4876 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004877 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004878 }
4879
sanryhuang498e77e2018-12-06 14:57:01 +08004880 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4881 boolean testPssMode) {
4882 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4883 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4884 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004885 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004886 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4887 st.toString());
4888 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004889 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4890 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4891 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004892 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4893 testPssMode);
4894 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004895 }
4896
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897 int getCurrentUserId() {
4898 return mAmInternal.getCurrentUserId();
4899 }
4900
4901 private void enforceNotIsolatedCaller(String caller) {
4902 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4903 throw new SecurityException("Isolated process not allowed to call " + caller);
4904 }
4905 }
4906
Wale Ogunwalef6733932018-06-27 05:14:34 -07004907 public Configuration getConfiguration() {
4908 Configuration ci;
4909 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004910 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004911 ci.userSetLocale = false;
4912 }
4913 return ci;
4914 }
4915
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004916 /**
4917 * Current global configuration information. Contains general settings for the entire system,
4918 * also corresponds to the merged configuration of the default display.
4919 */
4920 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004921 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004922 }
4923
4924 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4925 boolean initLocale) {
4926 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4927 }
4928
4929 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4930 boolean initLocale, boolean deferResume) {
4931 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4932 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4933 UserHandle.USER_NULL, deferResume);
4934 }
4935
Wale Ogunwale59507092018-10-29 09:00:30 -07004936 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004937 final long origId = Binder.clearCallingIdentity();
4938 try {
4939 synchronized (mGlobalLock) {
4940 updateConfigurationLocked(values, null, false, true, userId,
4941 false /* deferResume */);
4942 }
4943 } finally {
4944 Binder.restoreCallingIdentity(origId);
4945 }
4946 }
4947
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004948 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4949 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4950 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4951 deferResume, null /* result */);
4952 }
4953
4954 /**
4955 * Do either or both things: (1) change the current configuration, and (2)
4956 * make sure the given activity is running with the (now) current
4957 * configuration. Returns true if the activity has been left running, or
4958 * false if <var>starting</var> is being destroyed to match the new
4959 * configuration.
4960 *
4961 * @param userId is only used when persistent parameter is set to true to persist configuration
4962 * for that particular user
4963 */
4964 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4965 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4966 ActivityTaskManagerService.UpdateConfigurationResult result) {
4967 int changes = 0;
4968 boolean kept = true;
4969
4970 if (mWindowManager != null) {
4971 mWindowManager.deferSurfaceLayout();
4972 }
4973 try {
4974 if (values != null) {
4975 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4976 deferResume);
4977 }
4978
4979 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4980 } finally {
4981 if (mWindowManager != null) {
4982 mWindowManager.continueSurfaceLayout();
4983 }
4984 }
4985
4986 if (result != null) {
4987 result.changes = changes;
4988 result.activityRelaunched = !kept;
4989 }
4990 return kept;
4991 }
4992
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004993 /** Update default (global) configuration and notify listeners about changes. */
4994 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4995 boolean persistent, int userId, boolean deferResume) {
4996 mTempConfig.setTo(getGlobalConfiguration());
4997 final int changes = mTempConfig.updateFrom(values);
4998 if (changes == 0) {
4999 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5000 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5001 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5002 // (even if there are no actual changes) to unfreeze the window.
5003 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5004 return 0;
5005 }
5006
5007 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5008 "Updating global configuration to: " + values);
5009
5010 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5011 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5012 values.colorMode,
5013 values.densityDpi,
5014 values.fontScale,
5015 values.hardKeyboardHidden,
5016 values.keyboard,
5017 values.keyboardHidden,
5018 values.mcc,
5019 values.mnc,
5020 values.navigation,
5021 values.navigationHidden,
5022 values.orientation,
5023 values.screenHeightDp,
5024 values.screenLayout,
5025 values.screenWidthDp,
5026 values.smallestScreenWidthDp,
5027 values.touchscreen,
5028 values.uiMode);
5029
5030
5031 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5032 final LocaleList locales = values.getLocales();
5033 int bestLocaleIndex = 0;
5034 if (locales.size() > 1) {
5035 if (mSupportedSystemLocales == null) {
5036 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5037 }
5038 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5039 }
5040 SystemProperties.set("persist.sys.locale",
5041 locales.get(bestLocaleIndex).toLanguageTag());
5042 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005043
5044 final Message m = PooledLambda.obtainMessage(
5045 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5046 locales.get(bestLocaleIndex));
5047 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005048 }
5049
Yunfan Chen75157d72018-07-27 14:47:21 +09005050 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005051
5052 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005053 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005054
5055 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5056 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005057 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005058
5059 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005060 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005061
5062 AttributeCache ac = AttributeCache.instance();
5063 if (ac != null) {
5064 ac.updateConfiguration(mTempConfig);
5065 }
5066
5067 // Make sure all resources in our process are updated right now, so that anyone who is going
5068 // to retrieve resource values after we return will be sure to get the new ones. This is
5069 // especially important during boot, where the first config change needs to guarantee all
5070 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005071 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072
5073 // We need another copy of global config because we're scheduling some calls instead of
5074 // running them in place. We need to be sure that object we send will be handled unchanged.
5075 final Configuration configCopy = new Configuration(mTempConfig);
5076 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005077 final Message msg = PooledLambda.obtainMessage(
5078 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5079 this, userId, configCopy);
5080 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005081 }
5082
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005083 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005084 final int pid = mPidMap.keyAt(i);
5085 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005086 if (DEBUG_CONFIGURATION) {
5087 Slog.v(TAG_CONFIGURATION, "Update process config of "
5088 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005089 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005090 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005091 }
5092
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005093 final Message msg = PooledLambda.obtainMessage(
5094 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5095 mAmInternal, changes, initLocale);
5096 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005097
5098 // Override configuration of the default display duplicates global config, so we need to
5099 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005100 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005101 DEFAULT_DISPLAY);
5102
5103 return changes;
5104 }
5105
5106 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5107 boolean deferResume, int displayId) {
5108 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5109 displayId, null /* result */);
5110 }
5111
5112 /**
5113 * Updates override configuration specific for the selected display. If no config is provided,
5114 * new one will be computed in WM based on current display info.
5115 */
5116 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5117 ActivityRecord starting, boolean deferResume, int displayId,
5118 ActivityTaskManagerService.UpdateConfigurationResult result) {
5119 int changes = 0;
5120 boolean kept = true;
5121
5122 if (mWindowManager != null) {
5123 mWindowManager.deferSurfaceLayout();
5124 }
5125 try {
5126 if (values != null) {
5127 if (displayId == DEFAULT_DISPLAY) {
5128 // Override configuration of the default display duplicates global config, so
5129 // we're calling global config update instead for default display. It will also
5130 // apply the correct override config.
5131 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5132 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5133 } else {
5134 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5135 }
5136 }
5137
5138 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5139 } finally {
5140 if (mWindowManager != null) {
5141 mWindowManager.continueSurfaceLayout();
5142 }
5143 }
5144
5145 if (result != null) {
5146 result.changes = changes;
5147 result.activityRelaunched = !kept;
5148 }
5149 return kept;
5150 }
5151
5152 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5153 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005154 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005155 final int changes = mTempConfig.updateFrom(values);
5156 if (changes != 0) {
5157 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5158 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005159 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005160
5161 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5162 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005163 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164
Wale Ogunwale5c918702018-10-18 11:06:33 -07005165 // Post message to start process to avoid possible deadlock of calling into AMS with
5166 // the ATMS lock held.
5167 final Message msg = PooledLambda.obtainMessage(
5168 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5169 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5170 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171 }
5172 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005173 return changes;
5174 }
5175
Wale Ogunwalef6733932018-06-27 05:14:34 -07005176 private void updateEventDispatchingLocked(boolean booted) {
5177 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5178 }
5179
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005180 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5181 final ContentResolver resolver = mContext.getContentResolver();
5182 Settings.System.putConfigurationForUser(resolver, config, userId);
5183 }
5184
5185 private void sendLocaleToMountDaemonMsg(Locale l) {
5186 try {
5187 IBinder service = ServiceManager.getService("mount");
5188 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5189 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5190 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5191 } catch (RemoteException e) {
5192 Log.e(TAG, "Error storing locale for decryption UI", e);
5193 }
5194 }
5195
Alison Cichowlas3e340502018-08-07 17:15:01 -04005196 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5197 mStartActivitySources.remove(permissionToken);
5198 mExpiredStartAsCallerTokens.add(permissionToken);
5199 }
5200
5201 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5202 mExpiredStartAsCallerTokens.remove(permissionToken);
5203 }
5204
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005205 boolean isActivityStartsLoggingEnabled() {
5206 return mAmInternal.isActivityStartsLoggingEnabled();
5207 }
5208
Michal Karpinski8596ded2018-11-14 14:43:48 +00005209 boolean isBackgroundActivityStartsEnabled() {
5210 return mAmInternal.isBackgroundActivityStartsEnabled();
5211 }
5212
Wale Ogunwalef6733932018-06-27 05:14:34 -07005213 void enableScreenAfterBoot(boolean booted) {
5214 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5215 SystemClock.uptimeMillis());
5216 mWindowManager.enableScreenAfterBoot();
5217
5218 synchronized (mGlobalLock) {
5219 updateEventDispatchingLocked(booted);
5220 }
5221 }
5222
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005223 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5224 if (r == null || !r.hasProcess()) {
5225 return KEY_DISPATCHING_TIMEOUT_MS;
5226 }
5227 return getInputDispatchingTimeoutLocked(r.app);
5228 }
5229
5230 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005231 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005232 }
5233
Wale Ogunwalef6733932018-06-27 05:14:34 -07005234 /**
5235 * Decide based on the configuration whether we should show the ANR,
5236 * crash, etc dialogs. The idea is that if there is no affordance to
5237 * press the on-screen buttons, or the user experience would be more
5238 * greatly impacted than the crash itself, we shouldn't show the dialog.
5239 *
5240 * A thought: SystemUI might also want to get told about this, the Power
5241 * dialog / global actions also might want different behaviors.
5242 */
5243 private void updateShouldShowDialogsLocked(Configuration config) {
5244 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5245 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5246 && config.navigation == Configuration.NAVIGATION_NONAV);
5247 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5248 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5249 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5250 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5251 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5252 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5253 HIDE_ERROR_DIALOGS, 0) != 0;
5254 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5255 }
5256
5257 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5258 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5259 FONT_SCALE, 1.0f, userId);
5260
5261 synchronized (this) {
5262 if (getGlobalConfiguration().fontScale == scaleFactor) {
5263 return;
5264 }
5265
5266 final Configuration configuration
5267 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5268 configuration.fontScale = scaleFactor;
5269 updatePersistentConfiguration(configuration, userId);
5270 }
5271 }
5272
5273 // Actually is sleeping or shutting down or whatever else in the future
5274 // is an inactive state.
5275 boolean isSleepingOrShuttingDownLocked() {
5276 return isSleepingLocked() || mShuttingDown;
5277 }
5278
5279 boolean isSleepingLocked() {
5280 return mSleeping;
5281 }
5282
Riddle Hsu16567132018-08-16 21:37:47 +08005283 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005284 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005285 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005286 if (task.isActivityTypeStandard()) {
5287 if (mCurAppTimeTracker != r.appTimeTracker) {
5288 // We are switching app tracking. Complete the current one.
5289 if (mCurAppTimeTracker != null) {
5290 mCurAppTimeTracker.stop();
5291 mH.obtainMessage(
5292 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005293 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005294 mCurAppTimeTracker = null;
5295 }
5296 if (r.appTimeTracker != null) {
5297 mCurAppTimeTracker = r.appTimeTracker;
5298 startTimeTrackingFocusedActivityLocked();
5299 }
5300 } else {
5301 startTimeTrackingFocusedActivityLocked();
5302 }
5303 } else {
5304 r.appTimeTracker = null;
5305 }
5306 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5307 // TODO: Probably not, because we don't want to resume voice on switching
5308 // back to this activity
5309 if (task.voiceInteractor != null) {
5310 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5311 } else {
5312 finishRunningVoiceLocked();
5313
5314 if (mLastResumedActivity != null) {
5315 final IVoiceInteractionSession session;
5316
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005317 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005318 if (lastResumedActivityTask != null
5319 && lastResumedActivityTask.voiceSession != null) {
5320 session = lastResumedActivityTask.voiceSession;
5321 } else {
5322 session = mLastResumedActivity.voiceSession;
5323 }
5324
5325 if (session != null) {
5326 // We had been in a voice interaction session, but now focused has
5327 // move to something different. Just finish the session, we can't
5328 // return to it and retain the proper state and synchronization with
5329 // the voice interaction service.
5330 finishVoiceTask(session);
5331 }
5332 }
5333 }
5334
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005335 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5336 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005337 }
5338 updateResumedAppTrace(r);
5339 mLastResumedActivity = r;
5340
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005341 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005342
5343 applyUpdateLockStateLocked(r);
5344 applyUpdateVrModeLocked(r);
5345
5346 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005347 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005348 r == null ? "NULL" : r.shortComponentName,
5349 reason);
5350 }
5351
5352 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5353 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005354 final ActivityTaskManagerInternal.SleepToken token =
5355 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005356 updateSleepIfNeededLocked();
5357 return token;
5358 }
5359 }
5360
5361 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005362 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005363 final boolean wasSleeping = mSleeping;
5364 boolean updateOomAdj = false;
5365
5366 if (!shouldSleep) {
5367 // If wasSleeping is true, we need to wake up activity manager state from when
5368 // we started sleeping. In either case, we need to apply the sleep tokens, which
5369 // will wake up stacks or put them to sleep as appropriate.
5370 if (wasSleeping) {
5371 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005372 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5373 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005374 startTimeTrackingFocusedActivityLocked();
5375 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5376 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5377 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005378 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005379 if (wasSleeping) {
5380 updateOomAdj = true;
5381 }
5382 } else if (!mSleeping && shouldSleep) {
5383 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005384 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5385 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005386 if (mCurAppTimeTracker != null) {
5387 mCurAppTimeTracker.stop();
5388 }
5389 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5390 mStackSupervisor.goingToSleepLocked();
5391 updateResumedAppTrace(null /* resumed */);
5392 updateOomAdj = true;
5393 }
5394 if (updateOomAdj) {
5395 mH.post(mAmInternal::updateOomAdj);
5396 }
5397 }
5398
5399 void updateOomAdj() {
5400 mH.post(mAmInternal::updateOomAdj);
5401 }
5402
Wale Ogunwale53783742018-09-16 10:21:51 -07005403 void updateCpuStats() {
5404 mH.post(mAmInternal::updateCpuStats);
5405 }
5406
Hui Yu03d12402018-12-06 18:00:37 -08005407 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5408 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005409 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5410 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005411 mH.sendMessage(m);
5412 }
5413
Hui Yu03d12402018-12-06 18:00:37 -08005414 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005415 ComponentName taskRoot = null;
5416 final TaskRecord task = activity.getTaskRecord();
5417 if (task != null) {
5418 final ActivityRecord rootActivity = task.getRootActivity();
5419 if (rootActivity != null) {
5420 taskRoot = rootActivity.mActivityComponent;
5421 }
5422 }
5423
Hui Yu03d12402018-12-06 18:00:37 -08005424 final Message m = PooledLambda.obtainMessage(
5425 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005426 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005427 mH.sendMessage(m);
5428 }
5429
Wale Ogunwale53783742018-09-16 10:21:51 -07005430 void setBooting(boolean booting) {
5431 mAmInternal.setBooting(booting);
5432 }
5433
5434 boolean isBooting() {
5435 return mAmInternal.isBooting();
5436 }
5437
5438 void setBooted(boolean booted) {
5439 mAmInternal.setBooted(booted);
5440 }
5441
5442 boolean isBooted() {
5443 return mAmInternal.isBooted();
5444 }
5445
5446 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5447 mH.post(() -> {
5448 if (finishBooting) {
5449 mAmInternal.finishBooting();
5450 }
5451 if (enableScreen) {
5452 mInternal.enableScreenAfterBoot(isBooted());
5453 }
5454 });
5455 }
5456
5457 void setHeavyWeightProcess(ActivityRecord root) {
5458 mHeavyWeightProcess = root.app;
5459 final Message m = PooledLambda.obtainMessage(
5460 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005461 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005462 mH.sendMessage(m);
5463 }
5464
5465 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5466 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5467 return;
5468 }
5469
5470 mHeavyWeightProcess = null;
5471 final Message m = PooledLambda.obtainMessage(
5472 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5473 proc.mUserId);
5474 mH.sendMessage(m);
5475 }
5476
5477 private void cancelHeavyWeightProcessNotification(int userId) {
5478 final INotificationManager inm = NotificationManager.getService();
5479 if (inm == null) {
5480 return;
5481 }
5482 try {
5483 inm.cancelNotificationWithTag("android", null,
5484 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5485 } catch (RuntimeException e) {
5486 Slog.w(TAG, "Error canceling notification for service", e);
5487 } catch (RemoteException e) {
5488 }
5489
5490 }
5491
5492 private void postHeavyWeightProcessNotification(
5493 WindowProcessController proc, Intent intent, int userId) {
5494 if (proc == null) {
5495 return;
5496 }
5497
5498 final INotificationManager inm = NotificationManager.getService();
5499 if (inm == null) {
5500 return;
5501 }
5502
5503 try {
5504 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5505 String text = mContext.getString(R.string.heavy_weight_notification,
5506 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5507 Notification notification =
5508 new Notification.Builder(context,
5509 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5510 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5511 .setWhen(0)
5512 .setOngoing(true)
5513 .setTicker(text)
5514 .setColor(mContext.getColor(
5515 com.android.internal.R.color.system_notification_accent_color))
5516 .setContentTitle(text)
5517 .setContentText(
5518 mContext.getText(R.string.heavy_weight_notification_detail))
5519 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5520 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5521 new UserHandle(userId)))
5522 .build();
5523 try {
5524 inm.enqueueNotificationWithTag("android", "android", null,
5525 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5526 } catch (RuntimeException e) {
5527 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5528 } catch (RemoteException e) {
5529 }
5530 } catch (PackageManager.NameNotFoundException e) {
5531 Slog.w(TAG, "Unable to create context for heavy notification", e);
5532 }
5533
5534 }
5535
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005536 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5537 IBinder token, String resultWho, int requestCode, Intent[] intents,
5538 String[] resolvedTypes, int flags, Bundle bOptions) {
5539
5540 ActivityRecord activity = null;
5541 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5542 activity = ActivityRecord.isInStackLocked(token);
5543 if (activity == null) {
5544 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5545 return null;
5546 }
5547 if (activity.finishing) {
5548 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5549 return null;
5550 }
5551 }
5552
5553 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5554 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5555 bOptions);
5556 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5557 if (noCreate) {
5558 return rec;
5559 }
5560 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5561 if (activity.pendingResults == null) {
5562 activity.pendingResults = new HashSet<>();
5563 }
5564 activity.pendingResults.add(rec.ref);
5565 }
5566 return rec;
5567 }
5568
Andrii Kulian52d255c2018-07-13 11:32:19 -07005569 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005571 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5573 mCurAppTimeTracker.start(resumedActivity.packageName);
5574 }
5575 }
5576
5577 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5578 if (mTracedResumedActivity != null) {
5579 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5580 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5581 }
5582 if (resumed != null) {
5583 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5584 constructResumedTraceName(resumed.packageName), 0);
5585 }
5586 mTracedResumedActivity = resumed;
5587 }
5588
5589 private String constructResumedTraceName(String packageName) {
5590 return "focused app: " + packageName;
5591 }
5592
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005593 /** Applies latest configuration and/or visibility updates if needed. */
5594 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5595 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005596 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005597 // mainStack is null during startup.
5598 if (mainStack != null) {
5599 if (changes != 0 && starting == null) {
5600 // If the configuration changed, and the caller is not already
5601 // in the process of starting an activity, then find the top
5602 // activity to check if its configuration needs to change.
5603 starting = mainStack.topRunningActivityLocked();
5604 }
5605
5606 if (starting != null) {
5607 kept = starting.ensureActivityConfiguration(changes,
5608 false /* preserveWindow */);
5609 // And we need to make sure at this point that all other activities
5610 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005611 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005612 !PRESERVE_WINDOWS);
5613 }
5614 }
5615
5616 return kept;
5617 }
5618
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005619 void scheduleAppGcsLocked() {
5620 mH.post(() -> mAmInternal.scheduleAppGcs());
5621 }
5622
Wale Ogunwale53783742018-09-16 10:21:51 -07005623 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5624 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5625 }
5626
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005627 /**
5628 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5629 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5630 * on demand.
5631 */
5632 IPackageManager getPackageManager() {
5633 return AppGlobals.getPackageManager();
5634 }
5635
5636 PackageManagerInternal getPackageManagerInternalLocked() {
5637 if (mPmInternal == null) {
5638 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5639 }
5640 return mPmInternal;
5641 }
5642
Wale Ogunwale008163e2018-07-23 23:11:08 -07005643 AppWarnings getAppWarningsLocked() {
5644 return mAppWarnings;
5645 }
5646
Wale Ogunwale214f3482018-10-04 11:00:47 -07005647 Intent getHomeIntent() {
5648 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5649 intent.setComponent(mTopComponent);
5650 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5651 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5652 intent.addCategory(Intent.CATEGORY_HOME);
5653 }
5654 return intent;
5655 }
5656
Chilun2ef71f72018-11-16 17:57:15 +08005657 /**
5658 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5659 * activities.
5660 *
5661 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5662 * component defined in config_secondaryHomeComponent.
5663 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5664 */
5665 Intent getSecondaryHomeIntent(String preferredPackage) {
5666 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5667 if (preferredPackage == null) {
5668 // Using the component stored in config if no package name.
5669 final String secondaryHomeComponent = mContext.getResources().getString(
5670 com.android.internal.R.string.config_secondaryHomeComponent);
5671 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5672 } else {
5673 intent.setPackage(preferredPackage);
5674 }
5675 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5676 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5677 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5678 }
5679 return intent;
5680 }
5681
Wale Ogunwale214f3482018-10-04 11:00:47 -07005682 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5683 if (info == null) return null;
5684 ApplicationInfo newInfo = new ApplicationInfo(info);
5685 newInfo.initForUser(userId);
5686 return newInfo;
5687 }
5688
Wale Ogunwale9c103022018-10-18 07:44:54 -07005689 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005690 if (uid == SYSTEM_UID) {
5691 // The system gets to run in any process. If there are multiple processes with the same
5692 // uid, just pick the first (this should never happen).
5693 final SparseArray<WindowProcessController> procs =
5694 mProcessNames.getMap().get(processName);
5695 if (procs == null) return null;
5696 final int procCount = procs.size();
5697 for (int i = 0; i < procCount; i++) {
5698 final int procUid = procs.keyAt(i);
5699 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5700 // Don't use an app process or different user process for system component.
5701 continue;
5702 }
5703 return procs.valueAt(i);
5704 }
5705 }
5706
5707 return mProcessNames.get(processName, uid);
5708 }
5709
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005710 WindowProcessController getProcessController(IApplicationThread thread) {
5711 if (thread == null) {
5712 return null;
5713 }
5714
5715 final IBinder threadBinder = thread.asBinder();
5716 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5717 for (int i = pmap.size()-1; i >= 0; i--) {
5718 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5719 for (int j = procs.size() - 1; j >= 0; j--) {
5720 final WindowProcessController proc = procs.valueAt(j);
5721 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5722 return proc;
5723 }
5724 }
5725 }
5726
5727 return null;
5728 }
5729
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005730 WindowProcessController getProcessController(int pid, int uid) {
5731 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5732 for (int i = pmap.size()-1; i >= 0; i--) {
5733 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5734 for (int j = procs.size() - 1; j >= 0; j--) {
5735 final WindowProcessController proc = procs.valueAt(j);
5736 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5737 return proc;
5738 }
5739 }
5740 }
5741 return null;
5742 }
5743
Riddle Hsua0536432019-02-16 00:38:59 +08005744 int getUidState(int uid) {
5745 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005746 }
5747
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005748 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005749 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005750 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5751 }
5752
Michal Karpinski4026cae2019-02-12 11:51:47 +00005753 boolean isDeviceOwner(String packageName) {
5754 if (packageName == null) {
5755 return false;
5756 }
5757 return packageName.equals(mDeviceOwnerPackageName);
5758 }
5759
5760 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5761 mDeviceOwnerPackageName = deviceOwnerPkg;
5762 }
5763
Wale Ogunwale9de19442018-10-18 19:05:03 -07005764 /**
5765 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5766 * the whitelist
5767 */
5768 String getPendingTempWhitelistTagForUidLocked(int uid) {
5769 return mPendingTempWhitelist.get(uid);
5770 }
5771
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005772 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5773 if (true || Build.IS_USER) {
5774 return;
5775 }
5776
5777 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5778 StrictMode.allowThreadDiskWrites();
5779 try {
5780 File tracesDir = new File("/data/anr");
5781 File tracesFile = null;
5782 try {
5783 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5784
5785 StringBuilder sb = new StringBuilder();
5786 Time tobj = new Time();
5787 tobj.set(System.currentTimeMillis());
5788 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5789 sb.append(": ");
5790 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5791 sb.append(" since ");
5792 sb.append(msg);
5793 FileOutputStream fos = new FileOutputStream(tracesFile);
5794 fos.write(sb.toString().getBytes());
5795 if (app == null) {
5796 fos.write("\n*** No application process!".getBytes());
5797 }
5798 fos.close();
5799 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5800 } catch (IOException e) {
5801 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5802 return;
5803 }
5804
5805 if (app != null && app.getPid() > 0) {
5806 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5807 firstPids.add(app.getPid());
5808 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5809 }
5810
5811 File lastTracesFile = null;
5812 File curTracesFile = null;
5813 for (int i=9; i>=0; i--) {
5814 String name = String.format(Locale.US, "slow%02d.txt", i);
5815 curTracesFile = new File(tracesDir, name);
5816 if (curTracesFile.exists()) {
5817 if (lastTracesFile != null) {
5818 curTracesFile.renameTo(lastTracesFile);
5819 } else {
5820 curTracesFile.delete();
5821 }
5822 }
5823 lastTracesFile = curTracesFile;
5824 }
5825 tracesFile.renameTo(curTracesFile);
5826 } finally {
5827 StrictMode.setThreadPolicy(oldPolicy);
5828 }
5829 }
5830
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005831 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005832 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005833
5834
Wale Ogunwale98875612018-10-12 07:53:02 -07005835 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5836 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005837
Riddle Hsud93a6c42018-11-29 21:50:06 +08005838 H(Looper looper) {
5839 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005840 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005841
5842 @Override
5843 public void handleMessage(Message msg) {
5844 switch (msg.what) {
5845 case REPORT_TIME_TRACKER_MSG: {
5846 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5847 tracker.deliverResult(mContext);
5848 } break;
5849 }
5850 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005851 }
5852
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005853 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005854 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005855
5856 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005857 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005858 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005859
5860 @Override
5861 public void handleMessage(Message msg) {
5862 switch (msg.what) {
5863 case DISMISS_DIALOG_UI_MSG: {
5864 final Dialog d = (Dialog) msg.obj;
5865 d.dismiss();
5866 break;
5867 }
5868 }
5869 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005870 }
5871
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005872 final class LocalService extends ActivityTaskManagerInternal {
5873 @Override
5874 public SleepToken acquireSleepToken(String tag, int displayId) {
5875 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005876 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005877 }
5878
5879 @Override
5880 public ComponentName getHomeActivityForUser(int userId) {
5881 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005882 final ActivityRecord homeActivity =
5883 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005884 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005885 }
5886 }
5887
5888 @Override
5889 public void onLocalVoiceInteractionStarted(IBinder activity,
5890 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5891 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005892 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005893 }
5894 }
5895
5896 @Override
5897 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5898 synchronized (mGlobalLock) {
5899 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5900 reasons, timestamp);
5901 }
5902 }
5903
5904 @Override
5905 public void notifyAppTransitionFinished() {
5906 synchronized (mGlobalLock) {
5907 mStackSupervisor.notifyAppTransitionDone();
5908 }
5909 }
5910
5911 @Override
5912 public void notifyAppTransitionCancelled() {
5913 synchronized (mGlobalLock) {
5914 mStackSupervisor.notifyAppTransitionDone();
5915 }
5916 }
5917
5918 @Override
5919 public List<IBinder> getTopVisibleActivities() {
5920 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005921 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005922 }
5923 }
5924
5925 @Override
5926 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5927 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005928 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005929 }
5930 }
5931
5932 @Override
5933 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5934 Bundle bOptions) {
5935 Preconditions.checkNotNull(intents, "intents");
5936 final String[] resolvedTypes = new String[intents.length];
5937
5938 // UID of the package on user userId.
5939 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5940 // packageUid may not be initialized.
5941 int packageUid = 0;
5942 final long ident = Binder.clearCallingIdentity();
5943
5944 try {
5945 for (int i = 0; i < intents.length; i++) {
5946 resolvedTypes[i] =
5947 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5948 }
5949
5950 packageUid = AppGlobals.getPackageManager().getPackageUid(
5951 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5952 } catch (RemoteException e) {
5953 // Shouldn't happen.
5954 } finally {
5955 Binder.restoreCallingIdentity(ident);
5956 }
5957
Riddle Hsu591bf612019-02-14 17:55:31 +08005958 return getActivityStartController().startActivitiesInPackage(
5959 packageUid, packageName,
5960 intents, resolvedTypes, null /* resultTo */,
5961 SafeActivityOptions.fromBundle(bOptions), userId,
5962 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5963 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005964 }
5965
5966 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005967 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5968 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5969 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5970 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005971 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005972 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005973 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5974 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5975 userId, validateIncomingUser, originatingPendingIntent,
5976 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005977 }
5978 }
5979
5980 @Override
5981 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5982 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5983 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5984 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005985 PendingIntentRecord originatingPendingIntent,
5986 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005987 synchronized (mGlobalLock) {
5988 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5989 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5990 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005991 validateIncomingUser, originatingPendingIntent,
5992 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005993 }
5994 }
5995
5996 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005997 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5998 Intent intent, Bundle options, int userId) {
5999 return ActivityTaskManagerService.this.startActivityAsUser(
6000 caller, callerPacakge, intent,
6001 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6002 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6003 false /*validateIncomingUser*/);
6004 }
6005
6006 @Override
lumark588a3e82018-07-20 18:53:54 +08006007 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006008 synchronized (mGlobalLock) {
6009
6010 // We might change the visibilities here, so prepare an empty app transition which
6011 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006012 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006013 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006014 if (activityDisplay == null) {
6015 return;
6016 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006017 final DisplayContent dc = activityDisplay.mDisplayContent;
6018 final boolean wasTransitionSet =
6019 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006020 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006021 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006022 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006023 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006024
6025 // If there was a transition set already we don't want to interfere with it as we
6026 // might be starting it too early.
6027 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006028 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006029 }
6030 }
6031 if (callback != null) {
6032 callback.run();
6033 }
6034 }
6035
6036 @Override
6037 public void notifyKeyguardTrustedChanged() {
6038 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006039 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006040 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006041 }
6042 }
6043 }
6044
6045 /**
6046 * Called after virtual display Id is updated by
6047 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6048 * {@param vrVr2dDisplayId}.
6049 */
6050 @Override
6051 public void setVr2dDisplayId(int vr2dDisplayId) {
6052 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6053 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006054 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006055 }
6056 }
6057
6058 @Override
6059 public void setFocusedActivity(IBinder token) {
6060 synchronized (mGlobalLock) {
6061 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6062 if (r == null) {
6063 throw new IllegalArgumentException(
6064 "setFocusedActivity: No activity record matching token=" + token);
6065 }
Louis Chang19443452018-10-09 12:10:21 +08006066 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006067 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006068 }
6069 }
6070 }
6071
6072 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006073 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006074 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006075 }
6076
6077 @Override
6078 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006079 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006080 }
6081
6082 @Override
6083 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006084 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006085 }
6086
6087 @Override
6088 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6089 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6090 }
6091
6092 @Override
6093 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006094 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006095 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006096
6097 @Override
6098 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6099 synchronized (mGlobalLock) {
6100 mActiveVoiceInteractionServiceComponent = component;
6101 }
6102 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006103
6104 @Override
6105 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6106 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6107 return;
6108 }
6109 synchronized (mGlobalLock) {
6110 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6111 if (types == null) {
6112 if (uid < 0) {
6113 return;
6114 }
6115 types = new ArrayMap<>();
6116 mAllowAppSwitchUids.put(userId, types);
6117 }
6118 if (uid < 0) {
6119 types.remove(type);
6120 } else {
6121 types.put(type, uid);
6122 }
6123 }
6124 }
6125
6126 @Override
6127 public void onUserStopped(int userId) {
6128 synchronized (mGlobalLock) {
6129 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6130 mAllowAppSwitchUids.remove(userId);
6131 }
6132 }
6133
6134 @Override
6135 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6136 synchronized (mGlobalLock) {
6137 return ActivityTaskManagerService.this.isGetTasksAllowed(
6138 caller, callingPid, callingUid);
6139 }
6140 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006141
Riddle Hsua0536432019-02-16 00:38:59 +08006142 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006143 @Override
6144 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006145 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006146 mProcessNames.put(proc.mName, proc.mUid, proc);
6147 }
6148 }
6149
Riddle Hsua0536432019-02-16 00:38:59 +08006150 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006151 @Override
6152 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006153 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006154 mProcessNames.remove(name, uid);
6155 }
6156 }
6157
Riddle Hsua0536432019-02-16 00:38:59 +08006158 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006159 @Override
6160 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006161 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006162 if (proc == mHomeProcess) {
6163 mHomeProcess = null;
6164 }
6165 if (proc == mPreviousProcess) {
6166 mPreviousProcess = null;
6167 }
6168 }
6169 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006170
Riddle Hsua0536432019-02-16 00:38:59 +08006171 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006172 @Override
6173 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006174 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006175 return mTopProcessState;
6176 }
6177 }
6178
Riddle Hsua0536432019-02-16 00:38:59 +08006179 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006180 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006181 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006182 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006183 return proc == mHeavyWeightProcess;
6184 }
6185 }
6186
Riddle Hsua0536432019-02-16 00:38:59 +08006187 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006188 @Override
6189 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006190 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006191 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6192 }
6193 }
6194
6195 @Override
6196 public void finishHeavyWeightApp() {
6197 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006198 if (mHeavyWeightProcess != null) {
6199 mHeavyWeightProcess.finishActivities();
6200 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006201 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6202 mHeavyWeightProcess);
6203 }
6204 }
6205
Riddle Hsua0536432019-02-16 00:38:59 +08006206 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006207 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006208 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006209 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006210 return isSleepingLocked();
6211 }
6212 }
6213
6214 @Override
6215 public boolean isShuttingDown() {
6216 synchronized (mGlobalLock) {
6217 return mShuttingDown;
6218 }
6219 }
6220
6221 @Override
6222 public boolean shuttingDown(boolean booted, int timeout) {
6223 synchronized (mGlobalLock) {
6224 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006225 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006226 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006227 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006228 return mStackSupervisor.shutdownLocked(timeout);
6229 }
6230 }
6231
6232 @Override
6233 public void enableScreenAfterBoot(boolean booted) {
6234 synchronized (mGlobalLock) {
6235 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6236 SystemClock.uptimeMillis());
6237 mWindowManager.enableScreenAfterBoot();
6238 updateEventDispatchingLocked(booted);
6239 }
6240 }
6241
6242 @Override
6243 public boolean showStrictModeViolationDialog() {
6244 synchronized (mGlobalLock) {
6245 return mShowDialogs && !mSleeping && !mShuttingDown;
6246 }
6247 }
6248
6249 @Override
6250 public void showSystemReadyErrorDialogsIfNeeded() {
6251 synchronized (mGlobalLock) {
6252 try {
6253 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6254 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6255 + " data partition or your device will be unstable.");
6256 mUiHandler.post(() -> {
6257 if (mShowDialogs) {
6258 AlertDialog d = new BaseErrorDialog(mUiContext);
6259 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6260 d.setCancelable(false);
6261 d.setTitle(mUiContext.getText(R.string.android_system_label));
6262 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6263 d.setButton(DialogInterface.BUTTON_POSITIVE,
6264 mUiContext.getText(R.string.ok),
6265 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6266 d.show();
6267 }
6268 });
6269 }
6270 } catch (RemoteException e) {
6271 }
6272
6273 if (!Build.isBuildConsistent()) {
6274 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6275 mUiHandler.post(() -> {
6276 if (mShowDialogs) {
6277 AlertDialog d = new BaseErrorDialog(mUiContext);
6278 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6279 d.setCancelable(false);
6280 d.setTitle(mUiContext.getText(R.string.android_system_label));
6281 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6282 d.setButton(DialogInterface.BUTTON_POSITIVE,
6283 mUiContext.getText(R.string.ok),
6284 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6285 d.show();
6286 }
6287 });
6288 }
6289 }
6290 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006291
6292 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006293 public void onProcessMapped(int pid, WindowProcessController proc) {
6294 synchronized (mGlobalLock) {
6295 mPidMap.put(pid, proc);
6296 }
6297 }
6298
6299 @Override
6300 public void onProcessUnMapped(int pid) {
6301 synchronized (mGlobalLock) {
6302 mPidMap.remove(pid);
6303 }
6304 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006305
6306 @Override
6307 public void onPackageDataCleared(String name) {
6308 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006309 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006310 mAppWarnings.onPackageDataCleared(name);
6311 }
6312 }
6313
6314 @Override
6315 public void onPackageUninstalled(String name) {
6316 synchronized (mGlobalLock) {
6317 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006318 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006319 }
6320 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006321
6322 @Override
6323 public void onPackageAdded(String name, boolean replacing) {
6324 synchronized (mGlobalLock) {
6325 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6326 }
6327 }
6328
6329 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006330 public void onPackageReplaced(ApplicationInfo aInfo) {
6331 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006332 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006333 }
6334 }
6335
6336 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006337 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6338 synchronized (mGlobalLock) {
6339 return compatibilityInfoForPackageLocked(ai);
6340 }
6341 }
6342
Yunfan Chen75157d72018-07-27 14:47:21 +09006343 /**
6344 * Set the corresponding display information for the process global configuration. To be
6345 * called when we need to show IME on a different display.
6346 *
6347 * @param pid The process id associated with the IME window.
6348 * @param displayId The ID of the display showing the IME.
6349 */
6350 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006351 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006352 if (pid == MY_PID || pid < 0) {
6353 if (DEBUG_CONFIGURATION) {
6354 Slog.w(TAG,
6355 "Trying to update display configuration for system/invalid process.");
6356 }
6357 return;
6358 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006359 synchronized (mGlobalLock) {
6360 final ActivityDisplay activityDisplay =
6361 mRootActivityContainer.getActivityDisplay(displayId);
6362 if (activityDisplay == null) {
6363 // Call might come when display is not yet added or has been removed.
6364 if (DEBUG_CONFIGURATION) {
6365 Slog.w(TAG, "Trying to update display configuration for non-existing "
6366 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006367 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006368 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006369 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006370 final WindowProcessController process = mPidMap.get(pid);
6371 if (process == null) {
6372 if (DEBUG_CONFIGURATION) {
6373 Slog.w(TAG, "Trying to update display configuration for invalid "
6374 + "process, pid=" + pid);
6375 }
6376 return;
6377 }
6378 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6379 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006380 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006381
6382 @Override
6383 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6384 int requestCode, int resultCode, Intent data) {
6385 synchronized (mGlobalLock) {
6386 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006387 if (r != null && r.getActivityStack() != null) {
6388 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6389 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006390 }
6391 }
6392 }
6393
6394 @Override
6395 public void clearPendingResultForActivity(IBinder activityToken,
6396 WeakReference<PendingIntentRecord> pir) {
6397 synchronized (mGlobalLock) {
6398 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6399 if (r != null && r.pendingResults != null) {
6400 r.pendingResults.remove(pir);
6401 }
6402 }
6403 }
6404
6405 @Override
6406 public IIntentSender getIntentSender(int type, String packageName,
6407 int callingUid, int userId, IBinder token, String resultWho,
6408 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6409 Bundle bOptions) {
6410 synchronized (mGlobalLock) {
6411 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6412 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6413 }
6414 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006415
6416 @Override
6417 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6418 synchronized (mGlobalLock) {
6419 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6420 if (r == null) {
6421 return null;
6422 }
6423 if (r.mServiceConnectionsHolder == null) {
6424 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6425 ActivityTaskManagerService.this, r);
6426 }
6427
6428 return r.mServiceConnectionsHolder;
6429 }
6430 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006431
6432 @Override
6433 public Intent getHomeIntent() {
6434 synchronized (mGlobalLock) {
6435 return ActivityTaskManagerService.this.getHomeIntent();
6436 }
6437 }
6438
6439 @Override
6440 public boolean startHomeActivity(int userId, String reason) {
6441 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006442 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006443 }
6444 }
6445
6446 @Override
6447 public boolean startHomeOnAllDisplays(int userId, String reason) {
6448 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006449 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006450 }
6451 }
6452
Riddle Hsua0536432019-02-16 00:38:59 +08006453 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006454 @Override
6455 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006456 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006457 if (mFactoryTest == FACTORY_TEST_OFF) {
6458 return false;
6459 }
6460 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6461 && wpc.mName.equals(mTopComponent.getPackageName())) {
6462 return true;
6463 }
6464 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6465 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6466 }
6467 }
6468
6469 @Override
6470 public void updateTopComponentForFactoryTest() {
6471 synchronized (mGlobalLock) {
6472 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6473 return;
6474 }
6475 final ResolveInfo ri = mContext.getPackageManager()
6476 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6477 final CharSequence errorMsg;
6478 if (ri != null) {
6479 final ActivityInfo ai = ri.activityInfo;
6480 final ApplicationInfo app = ai.applicationInfo;
6481 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6482 mTopAction = Intent.ACTION_FACTORY_TEST;
6483 mTopData = null;
6484 mTopComponent = new ComponentName(app.packageName, ai.name);
6485 errorMsg = null;
6486 } else {
6487 errorMsg = mContext.getResources().getText(
6488 com.android.internal.R.string.factorytest_not_system);
6489 }
6490 } else {
6491 errorMsg = mContext.getResources().getText(
6492 com.android.internal.R.string.factorytest_no_action);
6493 }
6494 if (errorMsg == null) {
6495 return;
6496 }
6497
6498 mTopAction = null;
6499 mTopData = null;
6500 mTopComponent = null;
6501 mUiHandler.post(() -> {
6502 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6503 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006504 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006505 });
6506 }
6507 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006508
Riddle Hsua0536432019-02-16 00:38:59 +08006509 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006510 @Override
6511 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6512 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006513 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006514 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006515 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006516
6517 wpc.clearRecentTasks();
6518 wpc.clearActivities();
6519
6520 if (wpc.isInstrumenting()) {
6521 finishInstrumentationCallback.run();
6522 }
6523
Jorim Jaggid0752812018-10-16 16:07:20 +02006524 if (!restarting && hasVisibleActivities) {
6525 mWindowManager.deferSurfaceLayout();
6526 try {
6527 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6528 // If there was nothing to resume, and we are not already restarting
6529 // this process, but there is a visible activity that is hosted by the
6530 // process...then make sure all visible activities are running, taking
6531 // care of restarting this process.
6532 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6533 !PRESERVE_WINDOWS);
6534 }
6535 } finally {
6536 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006537 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006538 }
6539 }
6540 }
6541
6542 @Override
6543 public void closeSystemDialogs(String reason) {
6544 enforceNotIsolatedCaller("closeSystemDialogs");
6545
6546 final int pid = Binder.getCallingPid();
6547 final int uid = Binder.getCallingUid();
6548 final long origId = Binder.clearCallingIdentity();
6549 try {
6550 synchronized (mGlobalLock) {
6551 // Only allow this from foreground processes, so that background
6552 // applications can't abuse it to prevent system UI from being shown.
6553 if (uid >= FIRST_APPLICATION_UID) {
6554 final WindowProcessController proc = mPidMap.get(pid);
6555 if (!proc.isPerceptible()) {
6556 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6557 + " from background process " + proc);
6558 return;
6559 }
6560 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006561 mWindowManager.closeSystemDialogs(reason);
6562
Wale Ogunwaled32da472018-11-16 07:19:28 -08006563 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006564 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006565 // Call into AM outside the synchronized block.
6566 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006567 } finally {
6568 Binder.restoreCallingIdentity(origId);
6569 }
6570 }
6571
6572 @Override
6573 public void cleanupDisabledPackageComponents(
6574 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6575 synchronized (mGlobalLock) {
6576 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006577 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006578 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006579 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006580 mStackSupervisor.scheduleIdleLocked();
6581 }
6582
6583 // Clean-up disabled tasks
6584 getRecentTasks().cleanupDisabledPackageTasksLocked(
6585 packageName, disabledClasses, userId);
6586 }
6587 }
6588
6589 @Override
6590 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6591 int userId) {
6592 synchronized (mGlobalLock) {
6593
6594 boolean didSomething =
6595 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006596 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006597 null, doit, evenPersistent, userId);
6598 return didSomething;
6599 }
6600 }
6601
6602 @Override
6603 public void resumeTopActivities(boolean scheduleIdle) {
6604 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006605 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006606 if (scheduleIdle) {
6607 mStackSupervisor.scheduleIdleLocked();
6608 }
6609 }
6610 }
6611
Riddle Hsua0536432019-02-16 00:38:59 +08006612 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006613 @Override
6614 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006615 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006616 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6617 }
6618 }
6619
Riddle Hsua0536432019-02-16 00:38:59 +08006620 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006621 @Override
6622 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006623 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006624 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006625 }
6626 }
6627
6628 @Override
6629 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6630 try {
6631 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6632 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6633 }
6634 } catch (RemoteException ex) {
6635 throw new SecurityException("Fail to check is caller a privileged app", ex);
6636 }
6637
6638 synchronized (mGlobalLock) {
6639 final long ident = Binder.clearCallingIdentity();
6640 try {
6641 if (mAmInternal.shouldConfirmCredentials(userId)) {
6642 if (mKeyguardController.isKeyguardLocked()) {
6643 // Showing launcher to avoid user entering credential twice.
6644 startHomeActivity(currentUserId, "notifyLockedProfile");
6645 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006646 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006647 }
6648 } finally {
6649 Binder.restoreCallingIdentity(ident);
6650 }
6651 }
6652 }
6653
6654 @Override
6655 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6656 mAmInternal.enforceCallingPermission(
6657 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6658
6659 synchronized (mGlobalLock) {
6660 final long ident = Binder.clearCallingIdentity();
6661 try {
6662 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6663 FLAG_ACTIVITY_TASK_ON_HOME);
6664 ActivityOptions activityOptions = options != null
6665 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006666 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006667 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006668 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006669 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006670 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006671 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6672 UserHandle.CURRENT);
6673 } finally {
6674 Binder.restoreCallingIdentity(ident);
6675 }
6676 }
6677 }
6678
6679 @Override
6680 public void writeActivitiesToProto(ProtoOutputStream proto) {
6681 synchronized (mGlobalLock) {
6682 // The output proto of "activity --proto activities"
6683 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006684 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006685 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6686 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006687 }
6688 }
6689
6690 @Override
6691 public void saveANRState(String reason) {
6692 synchronized (mGlobalLock) {
6693 final StringWriter sw = new StringWriter();
6694 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6695 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6696 if (reason != null) {
6697 pw.println(" Reason: " + reason);
6698 }
6699 pw.println();
6700 getActivityStartController().dump(pw, " ", null);
6701 pw.println();
6702 pw.println("-------------------------------------------------------------------------------");
6703 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6704 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6705 "" /* header */);
6706 pw.println();
6707 pw.close();
6708
6709 mLastANRState = sw.toString();
6710 }
6711 }
6712
6713 @Override
6714 public void clearSavedANRState() {
6715 synchronized (mGlobalLock) {
6716 mLastANRState = null;
6717 }
6718 }
6719
6720 @Override
6721 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6722 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6723 synchronized (mGlobalLock) {
6724 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6725 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6726 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6727 dumpLastANRLocked(pw);
6728 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6729 dumpLastANRTracesLocked(pw);
6730 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6731 dumpActivityStarterLocked(pw, dumpPackage);
6732 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6733 dumpActivityContainersLocked(pw);
6734 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6735 if (getRecentTasks() != null) {
6736 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6737 }
6738 }
6739 }
6740 }
6741
6742 @Override
6743 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6744 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6745 int wakefulness) {
6746 synchronized (mGlobalLock) {
6747 if (mHomeProcess != null && (dumpPackage == null
6748 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6749 if (needSep) {
6750 pw.println();
6751 needSep = false;
6752 }
6753 pw.println(" mHomeProcess: " + mHomeProcess);
6754 }
6755 if (mPreviousProcess != null && (dumpPackage == null
6756 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6757 if (needSep) {
6758 pw.println();
6759 needSep = false;
6760 }
6761 pw.println(" mPreviousProcess: " + mPreviousProcess);
6762 }
6763 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6764 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6765 StringBuilder sb = new StringBuilder(128);
6766 sb.append(" mPreviousProcessVisibleTime: ");
6767 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6768 pw.println(sb);
6769 }
6770 if (mHeavyWeightProcess != null && (dumpPackage == null
6771 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6772 if (needSep) {
6773 pw.println();
6774 needSep = false;
6775 }
6776 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6777 }
6778 if (dumpPackage == null) {
6779 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006780 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781 }
6782 if (dumpAll) {
6783 if (dumpPackage == null) {
6784 pw.println(" mConfigWillChange: "
6785 + getTopDisplayFocusedStack().mConfigWillChange);
6786 }
6787 if (mCompatModePackages.getPackages().size() > 0) {
6788 boolean printed = false;
6789 for (Map.Entry<String, Integer> entry
6790 : mCompatModePackages.getPackages().entrySet()) {
6791 String pkg = entry.getKey();
6792 int mode = entry.getValue();
6793 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6794 continue;
6795 }
6796 if (!printed) {
6797 pw.println(" mScreenCompatPackages:");
6798 printed = true;
6799 }
6800 pw.println(" " + pkg + ": " + mode);
6801 }
6802 }
6803 }
6804
6805 if (dumpPackage == null) {
6806 pw.println(" mWakefulness="
6807 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006808 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 if (mRunningVoice != null) {
6810 pw.println(" mRunningVoice=" + mRunningVoice);
6811 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6812 }
6813 pw.println(" mSleeping=" + mSleeping);
6814 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6815 pw.println(" mVrController=" + mVrController);
6816 }
6817 if (mCurAppTimeTracker != null) {
6818 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6819 }
6820 if (mAllowAppSwitchUids.size() > 0) {
6821 boolean printed = false;
6822 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6823 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6824 for (int j = 0; j < types.size(); j++) {
6825 if (dumpPackage == null ||
6826 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6827 if (needSep) {
6828 pw.println();
6829 needSep = false;
6830 }
6831 if (!printed) {
6832 pw.println(" mAllowAppSwitchUids:");
6833 printed = true;
6834 }
6835 pw.print(" User ");
6836 pw.print(mAllowAppSwitchUids.keyAt(i));
6837 pw.print(": Type ");
6838 pw.print(types.keyAt(j));
6839 pw.print(" = ");
6840 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6841 pw.println();
6842 }
6843 }
6844 }
6845 }
6846 if (dumpPackage == null) {
6847 if (mController != null) {
6848 pw.println(" mController=" + mController
6849 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6850 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006851 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6852 pw.println(" mLaunchingActivityWakeLock="
6853 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 }
6855
6856 return needSep;
6857 }
6858 }
6859
6860 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006861 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6862 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 synchronized (mGlobalLock) {
6864 if (dumpPackage == null) {
6865 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6866 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006867 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6868 if (mRunningVoice != null) {
6869 final long vrToken = proto.start(
6870 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6871 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6872 mRunningVoice.toString());
6873 mVoiceWakeLock.writeToProto(
6874 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6875 proto.end(vrToken);
6876 }
6877 mVrController.writeToProto(proto,
6878 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 if (mController != null) {
6880 final long token = proto.start(CONTROLLER);
6881 proto.write(CONTROLLER, mController.toString());
6882 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6883 proto.end(token);
6884 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006885 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6886 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6887 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 }
6889
6890 if (mHomeProcess != null && (dumpPackage == null
6891 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006892 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006893 }
6894
6895 if (mPreviousProcess != null && (dumpPackage == null
6896 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006897 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6899 }
6900
6901 if (mHeavyWeightProcess != null && (dumpPackage == null
6902 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006903 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 }
6905
6906 for (Map.Entry<String, Integer> entry
6907 : mCompatModePackages.getPackages().entrySet()) {
6908 String pkg = entry.getKey();
6909 int mode = entry.getValue();
6910 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6911 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6912 proto.write(PACKAGE, pkg);
6913 proto.write(MODE, mode);
6914 proto.end(compatToken);
6915 }
6916 }
6917
6918 if (mCurAppTimeTracker != null) {
6919 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6920 }
6921
6922 }
6923 }
6924
6925 @Override
6926 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6927 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6928 boolean dumpFocusedStackOnly) {
6929 synchronized (mGlobalLock) {
6930 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6931 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6932 }
6933 }
6934
6935 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006936 public void dumpForOom(PrintWriter pw) {
6937 synchronized (mGlobalLock) {
6938 pw.println(" mHomeProcess: " + mHomeProcess);
6939 pw.println(" mPreviousProcess: " + mPreviousProcess);
6940 if (mHeavyWeightProcess != null) {
6941 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6942 }
6943 }
6944 }
6945
6946 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 public boolean canGcNow() {
6948 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006949 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006950 }
6951 }
6952
Riddle Hsua0536432019-02-16 00:38:59 +08006953 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 @Override
6955 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006956 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006957 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006958 return top != null ? top.app : null;
6959 }
6960 }
6961
Riddle Hsua0536432019-02-16 00:38:59 +08006962 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006963 @Override
6964 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006965 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006966 if (mRootActivityContainer != null) {
6967 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006968 }
6969 }
6970 }
6971
6972 @Override
6973 public void scheduleDestroyAllActivities(String reason) {
6974 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006975 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006976 }
6977 }
6978
6979 @Override
6980 public void removeUser(int userId) {
6981 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006982 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006983 }
6984 }
6985
6986 @Override
6987 public boolean switchUser(int userId, UserState userState) {
6988 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006989 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006990 }
6991 }
6992
6993 @Override
6994 public void onHandleAppCrash(WindowProcessController wpc) {
6995 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006996 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006997 }
6998 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006999
7000 @Override
7001 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7002 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007003 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007004 }
7005 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007006
Riddle Hsua0536432019-02-16 00:38:59 +08007007 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007008 @Override
7009 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007010 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007011 }
7012
Riddle Hsua0536432019-02-16 00:38:59 +08007013 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007014 @Override
7015 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007016 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007017 }
7018
Riddle Hsua0536432019-02-16 00:38:59 +08007019 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007020 @Override
7021 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007022 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007023 }
7024
Riddle Hsua0536432019-02-16 00:38:59 +08007025 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007026 @Override
7027 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007028 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007029 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007030
7031 @Override
7032 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007033 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007034 mPendingTempWhitelist.put(uid, tag);
7035 }
7036 }
7037
7038 @Override
7039 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007040 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007041 mPendingTempWhitelist.remove(uid);
7042 }
7043 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007044
7045 @Override
7046 public boolean handleAppCrashInActivityController(String processName, int pid,
7047 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7048 Runnable killCrashingAppCallback) {
7049 synchronized (mGlobalLock) {
7050 if (mController == null) {
7051 return false;
7052 }
7053
7054 try {
7055 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7056 stackTrace)) {
7057 killCrashingAppCallback.run();
7058 return true;
7059 }
7060 } catch (RemoteException e) {
7061 mController = null;
7062 Watchdog.getInstance().setActivityController(null);
7063 }
7064 return false;
7065 }
7066 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007067
7068 @Override
7069 public void removeRecentTasksByPackageName(String packageName, int userId) {
7070 synchronized (mGlobalLock) {
7071 mRecentTasks.removeTasksByPackageName(packageName, userId);
7072 }
7073 }
7074
7075 @Override
7076 public void cleanupRecentTasksForUser(int userId) {
7077 synchronized (mGlobalLock) {
7078 mRecentTasks.cleanupLocked(userId);
7079 }
7080 }
7081
7082 @Override
7083 public void loadRecentTasksForUser(int userId) {
7084 synchronized (mGlobalLock) {
7085 mRecentTasks.loadUserRecentsLocked(userId);
7086 }
7087 }
7088
7089 @Override
7090 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7091 synchronized (mGlobalLock) {
7092 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7093 }
7094 }
7095
7096 @Override
7097 public void flushRecentTasks() {
7098 mRecentTasks.flush();
7099 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007100
7101 @Override
7102 public WindowProcessController getHomeProcess() {
7103 synchronized (mGlobalLock) {
7104 return mHomeProcess;
7105 }
7106 }
7107
7108 @Override
7109 public WindowProcessController getPreviousProcess() {
7110 synchronized (mGlobalLock) {
7111 return mPreviousProcess;
7112 }
7113 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007114
7115 @Override
7116 public void clearLockedTasks(String reason) {
7117 synchronized (mGlobalLock) {
7118 getLockTaskController().clearLockedTasks(reason);
7119 }
7120 }
7121
7122 @Override
7123 public void updateUserConfiguration() {
7124 synchronized (mGlobalLock) {
7125 final Configuration configuration = new Configuration(getGlobalConfiguration());
7126 final int currentUserId = mAmInternal.getCurrentUserId();
7127 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7128 configuration, currentUserId, Settings.System.canWrite(mContext));
7129 updateConfigurationLocked(configuration, null /* starting */,
7130 false /* initLocale */, false /* persistent */, currentUserId,
7131 false /* deferResume */);
7132 }
7133 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007134
7135 @Override
7136 public boolean canShowErrorDialogs() {
7137 synchronized (mGlobalLock) {
7138 return mShowDialogs && !mSleeping && !mShuttingDown
7139 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7140 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7141 mAmInternal.getCurrentUserId())
7142 && !(UserManager.isDeviceInDemoMode(mContext)
7143 && mAmInternal.getCurrentUser().isDemo());
7144 }
7145 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007146
7147 @Override
7148 public void setProfileApp(String profileApp) {
7149 synchronized (mGlobalLock) {
7150 mProfileApp = profileApp;
7151 }
7152 }
7153
7154 @Override
7155 public void setProfileProc(WindowProcessController wpc) {
7156 synchronized (mGlobalLock) {
7157 mProfileProc = wpc;
7158 }
7159 }
7160
7161 @Override
7162 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7163 synchronized (mGlobalLock) {
7164 mProfilerInfo = profilerInfo;
7165 }
7166 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007167
7168 @Override
7169 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7170 synchronized (mGlobalLock) {
7171 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7172 }
7173 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007174
7175 @Override
7176 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7177 synchronized (mGlobalLock) {
7178 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7179 }
7180 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007181
7182 @Override
7183 public boolean isUidForeground(int uid) {
7184 synchronized (mGlobalLock) {
7185 return ActivityTaskManagerService.this.isUidForeground(uid);
7186 }
7187 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007188
7189 @Override
7190 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7191 synchronized (mGlobalLock) {
7192 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7193 }
7194 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007195 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007196}