blob: 3255bc6f43b9d4aa0d900a1b5c414d204d5ed0ae [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
Michal Karpinski666631b2019-02-26 16:59:11 +00005213 boolean isPackageNameWhitelistedForBgActivityStarts(String packageName) {
5214 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5215 }
5216
Wale Ogunwalef6733932018-06-27 05:14:34 -07005217 void enableScreenAfterBoot(boolean booted) {
5218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5219 SystemClock.uptimeMillis());
5220 mWindowManager.enableScreenAfterBoot();
5221
5222 synchronized (mGlobalLock) {
5223 updateEventDispatchingLocked(booted);
5224 }
5225 }
5226
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005227 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5228 if (r == null || !r.hasProcess()) {
5229 return KEY_DISPATCHING_TIMEOUT_MS;
5230 }
5231 return getInputDispatchingTimeoutLocked(r.app);
5232 }
5233
5234 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005235 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005236 }
5237
Wale Ogunwalef6733932018-06-27 05:14:34 -07005238 /**
5239 * Decide based on the configuration whether we should show the ANR,
5240 * crash, etc dialogs. The idea is that if there is no affordance to
5241 * press the on-screen buttons, or the user experience would be more
5242 * greatly impacted than the crash itself, we shouldn't show the dialog.
5243 *
5244 * A thought: SystemUI might also want to get told about this, the Power
5245 * dialog / global actions also might want different behaviors.
5246 */
5247 private void updateShouldShowDialogsLocked(Configuration config) {
5248 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5249 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5250 && config.navigation == Configuration.NAVIGATION_NONAV);
5251 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5252 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5253 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5254 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5255 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5256 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5257 HIDE_ERROR_DIALOGS, 0) != 0;
5258 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5259 }
5260
5261 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5262 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5263 FONT_SCALE, 1.0f, userId);
5264
5265 synchronized (this) {
5266 if (getGlobalConfiguration().fontScale == scaleFactor) {
5267 return;
5268 }
5269
5270 final Configuration configuration
5271 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5272 configuration.fontScale = scaleFactor;
5273 updatePersistentConfiguration(configuration, userId);
5274 }
5275 }
5276
5277 // Actually is sleeping or shutting down or whatever else in the future
5278 // is an inactive state.
5279 boolean isSleepingOrShuttingDownLocked() {
5280 return isSleepingLocked() || mShuttingDown;
5281 }
5282
5283 boolean isSleepingLocked() {
5284 return mSleeping;
5285 }
5286
Riddle Hsu16567132018-08-16 21:37:47 +08005287 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005288 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005289 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005290 if (task.isActivityTypeStandard()) {
5291 if (mCurAppTimeTracker != r.appTimeTracker) {
5292 // We are switching app tracking. Complete the current one.
5293 if (mCurAppTimeTracker != null) {
5294 mCurAppTimeTracker.stop();
5295 mH.obtainMessage(
5296 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005297 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005298 mCurAppTimeTracker = null;
5299 }
5300 if (r.appTimeTracker != null) {
5301 mCurAppTimeTracker = r.appTimeTracker;
5302 startTimeTrackingFocusedActivityLocked();
5303 }
5304 } else {
5305 startTimeTrackingFocusedActivityLocked();
5306 }
5307 } else {
5308 r.appTimeTracker = null;
5309 }
5310 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5311 // TODO: Probably not, because we don't want to resume voice on switching
5312 // back to this activity
5313 if (task.voiceInteractor != null) {
5314 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5315 } else {
5316 finishRunningVoiceLocked();
5317
5318 if (mLastResumedActivity != null) {
5319 final IVoiceInteractionSession session;
5320
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005321 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005322 if (lastResumedActivityTask != null
5323 && lastResumedActivityTask.voiceSession != null) {
5324 session = lastResumedActivityTask.voiceSession;
5325 } else {
5326 session = mLastResumedActivity.voiceSession;
5327 }
5328
5329 if (session != null) {
5330 // We had been in a voice interaction session, but now focused has
5331 // move to something different. Just finish the session, we can't
5332 // return to it and retain the proper state and synchronization with
5333 // the voice interaction service.
5334 finishVoiceTask(session);
5335 }
5336 }
5337 }
5338
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005339 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5340 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005341 }
5342 updateResumedAppTrace(r);
5343 mLastResumedActivity = r;
5344
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005345 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005346
5347 applyUpdateLockStateLocked(r);
5348 applyUpdateVrModeLocked(r);
5349
5350 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005351 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005352 r == null ? "NULL" : r.shortComponentName,
5353 reason);
5354 }
5355
5356 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5357 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005358 final ActivityTaskManagerInternal.SleepToken token =
5359 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 updateSleepIfNeededLocked();
5361 return token;
5362 }
5363 }
5364
5365 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005366 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005367 final boolean wasSleeping = mSleeping;
5368 boolean updateOomAdj = false;
5369
5370 if (!shouldSleep) {
5371 // If wasSleeping is true, we need to wake up activity manager state from when
5372 // we started sleeping. In either case, we need to apply the sleep tokens, which
5373 // will wake up stacks or put them to sleep as appropriate.
5374 if (wasSleeping) {
5375 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005376 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5377 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378 startTimeTrackingFocusedActivityLocked();
5379 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5380 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5381 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005382 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005383 if (wasSleeping) {
5384 updateOomAdj = true;
5385 }
5386 } else if (!mSleeping && shouldSleep) {
5387 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005388 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5389 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005390 if (mCurAppTimeTracker != null) {
5391 mCurAppTimeTracker.stop();
5392 }
5393 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5394 mStackSupervisor.goingToSleepLocked();
5395 updateResumedAppTrace(null /* resumed */);
5396 updateOomAdj = true;
5397 }
5398 if (updateOomAdj) {
5399 mH.post(mAmInternal::updateOomAdj);
5400 }
5401 }
5402
5403 void updateOomAdj() {
5404 mH.post(mAmInternal::updateOomAdj);
5405 }
5406
Wale Ogunwale53783742018-09-16 10:21:51 -07005407 void updateCpuStats() {
5408 mH.post(mAmInternal::updateCpuStats);
5409 }
5410
Hui Yu03d12402018-12-06 18:00:37 -08005411 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5412 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005413 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5414 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005415 mH.sendMessage(m);
5416 }
5417
Hui Yu03d12402018-12-06 18:00:37 -08005418 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005419 ComponentName taskRoot = null;
5420 final TaskRecord task = activity.getTaskRecord();
5421 if (task != null) {
5422 final ActivityRecord rootActivity = task.getRootActivity();
5423 if (rootActivity != null) {
5424 taskRoot = rootActivity.mActivityComponent;
5425 }
5426 }
5427
Hui Yu03d12402018-12-06 18:00:37 -08005428 final Message m = PooledLambda.obtainMessage(
5429 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005430 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005431 mH.sendMessage(m);
5432 }
5433
Wale Ogunwale53783742018-09-16 10:21:51 -07005434 void setBooting(boolean booting) {
5435 mAmInternal.setBooting(booting);
5436 }
5437
5438 boolean isBooting() {
5439 return mAmInternal.isBooting();
5440 }
5441
5442 void setBooted(boolean booted) {
5443 mAmInternal.setBooted(booted);
5444 }
5445
5446 boolean isBooted() {
5447 return mAmInternal.isBooted();
5448 }
5449
5450 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5451 mH.post(() -> {
5452 if (finishBooting) {
5453 mAmInternal.finishBooting();
5454 }
5455 if (enableScreen) {
5456 mInternal.enableScreenAfterBoot(isBooted());
5457 }
5458 });
5459 }
5460
5461 void setHeavyWeightProcess(ActivityRecord root) {
5462 mHeavyWeightProcess = root.app;
5463 final Message m = PooledLambda.obtainMessage(
5464 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005465 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005466 mH.sendMessage(m);
5467 }
5468
5469 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5470 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5471 return;
5472 }
5473
5474 mHeavyWeightProcess = null;
5475 final Message m = PooledLambda.obtainMessage(
5476 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5477 proc.mUserId);
5478 mH.sendMessage(m);
5479 }
5480
5481 private void cancelHeavyWeightProcessNotification(int userId) {
5482 final INotificationManager inm = NotificationManager.getService();
5483 if (inm == null) {
5484 return;
5485 }
5486 try {
5487 inm.cancelNotificationWithTag("android", null,
5488 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5489 } catch (RuntimeException e) {
5490 Slog.w(TAG, "Error canceling notification for service", e);
5491 } catch (RemoteException e) {
5492 }
5493
5494 }
5495
5496 private void postHeavyWeightProcessNotification(
5497 WindowProcessController proc, Intent intent, int userId) {
5498 if (proc == null) {
5499 return;
5500 }
5501
5502 final INotificationManager inm = NotificationManager.getService();
5503 if (inm == null) {
5504 return;
5505 }
5506
5507 try {
5508 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5509 String text = mContext.getString(R.string.heavy_weight_notification,
5510 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5511 Notification notification =
5512 new Notification.Builder(context,
5513 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5514 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5515 .setWhen(0)
5516 .setOngoing(true)
5517 .setTicker(text)
5518 .setColor(mContext.getColor(
5519 com.android.internal.R.color.system_notification_accent_color))
5520 .setContentTitle(text)
5521 .setContentText(
5522 mContext.getText(R.string.heavy_weight_notification_detail))
5523 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5524 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5525 new UserHandle(userId)))
5526 .build();
5527 try {
5528 inm.enqueueNotificationWithTag("android", "android", null,
5529 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5530 } catch (RuntimeException e) {
5531 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5532 } catch (RemoteException e) {
5533 }
5534 } catch (PackageManager.NameNotFoundException e) {
5535 Slog.w(TAG, "Unable to create context for heavy notification", e);
5536 }
5537
5538 }
5539
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005540 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5541 IBinder token, String resultWho, int requestCode, Intent[] intents,
5542 String[] resolvedTypes, int flags, Bundle bOptions) {
5543
5544 ActivityRecord activity = null;
5545 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5546 activity = ActivityRecord.isInStackLocked(token);
5547 if (activity == null) {
5548 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5549 return null;
5550 }
5551 if (activity.finishing) {
5552 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5553 return null;
5554 }
5555 }
5556
5557 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5558 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5559 bOptions);
5560 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5561 if (noCreate) {
5562 return rec;
5563 }
5564 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5565 if (activity.pendingResults == null) {
5566 activity.pendingResults = new HashSet<>();
5567 }
5568 activity.pendingResults.add(rec.ref);
5569 }
5570 return rec;
5571 }
5572
Andrii Kulian52d255c2018-07-13 11:32:19 -07005573 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005575 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005576 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5577 mCurAppTimeTracker.start(resumedActivity.packageName);
5578 }
5579 }
5580
5581 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5582 if (mTracedResumedActivity != null) {
5583 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5584 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5585 }
5586 if (resumed != null) {
5587 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5588 constructResumedTraceName(resumed.packageName), 0);
5589 }
5590 mTracedResumedActivity = resumed;
5591 }
5592
5593 private String constructResumedTraceName(String packageName) {
5594 return "focused app: " + packageName;
5595 }
5596
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005597 /** Applies latest configuration and/or visibility updates if needed. */
5598 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5599 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005600 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005601 // mainStack is null during startup.
5602 if (mainStack != null) {
5603 if (changes != 0 && starting == null) {
5604 // If the configuration changed, and the caller is not already
5605 // in the process of starting an activity, then find the top
5606 // activity to check if its configuration needs to change.
5607 starting = mainStack.topRunningActivityLocked();
5608 }
5609
5610 if (starting != null) {
5611 kept = starting.ensureActivityConfiguration(changes,
5612 false /* preserveWindow */);
5613 // And we need to make sure at this point that all other activities
5614 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005615 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005616 !PRESERVE_WINDOWS);
5617 }
5618 }
5619
5620 return kept;
5621 }
5622
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005623 void scheduleAppGcsLocked() {
5624 mH.post(() -> mAmInternal.scheduleAppGcs());
5625 }
5626
Wale Ogunwale53783742018-09-16 10:21:51 -07005627 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5628 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5629 }
5630
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005631 /**
5632 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5633 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5634 * on demand.
5635 */
5636 IPackageManager getPackageManager() {
5637 return AppGlobals.getPackageManager();
5638 }
5639
5640 PackageManagerInternal getPackageManagerInternalLocked() {
5641 if (mPmInternal == null) {
5642 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5643 }
5644 return mPmInternal;
5645 }
5646
Wale Ogunwale008163e2018-07-23 23:11:08 -07005647 AppWarnings getAppWarningsLocked() {
5648 return mAppWarnings;
5649 }
5650
Wale Ogunwale214f3482018-10-04 11:00:47 -07005651 Intent getHomeIntent() {
5652 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5653 intent.setComponent(mTopComponent);
5654 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5655 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5656 intent.addCategory(Intent.CATEGORY_HOME);
5657 }
5658 return intent;
5659 }
5660
Chilun2ef71f72018-11-16 17:57:15 +08005661 /**
5662 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5663 * activities.
5664 *
5665 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5666 * component defined in config_secondaryHomeComponent.
5667 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5668 */
5669 Intent getSecondaryHomeIntent(String preferredPackage) {
5670 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5671 if (preferredPackage == null) {
5672 // Using the component stored in config if no package name.
5673 final String secondaryHomeComponent = mContext.getResources().getString(
5674 com.android.internal.R.string.config_secondaryHomeComponent);
5675 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5676 } else {
5677 intent.setPackage(preferredPackage);
5678 }
5679 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5680 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5681 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5682 }
5683 return intent;
5684 }
5685
Wale Ogunwale214f3482018-10-04 11:00:47 -07005686 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5687 if (info == null) return null;
5688 ApplicationInfo newInfo = new ApplicationInfo(info);
5689 newInfo.initForUser(userId);
5690 return newInfo;
5691 }
5692
Wale Ogunwale9c103022018-10-18 07:44:54 -07005693 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005694 if (uid == SYSTEM_UID) {
5695 // The system gets to run in any process. If there are multiple processes with the same
5696 // uid, just pick the first (this should never happen).
5697 final SparseArray<WindowProcessController> procs =
5698 mProcessNames.getMap().get(processName);
5699 if (procs == null) return null;
5700 final int procCount = procs.size();
5701 for (int i = 0; i < procCount; i++) {
5702 final int procUid = procs.keyAt(i);
5703 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5704 // Don't use an app process or different user process for system component.
5705 continue;
5706 }
5707 return procs.valueAt(i);
5708 }
5709 }
5710
5711 return mProcessNames.get(processName, uid);
5712 }
5713
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005714 WindowProcessController getProcessController(IApplicationThread thread) {
5715 if (thread == null) {
5716 return null;
5717 }
5718
5719 final IBinder threadBinder = thread.asBinder();
5720 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5721 for (int i = pmap.size()-1; i >= 0; i--) {
5722 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5723 for (int j = procs.size() - 1; j >= 0; j--) {
5724 final WindowProcessController proc = procs.valueAt(j);
5725 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5726 return proc;
5727 }
5728 }
5729 }
5730
5731 return null;
5732 }
5733
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005734 WindowProcessController getProcessController(int pid, int uid) {
5735 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5736 for (int i = pmap.size()-1; i >= 0; i--) {
5737 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5738 for (int j = procs.size() - 1; j >= 0; j--) {
5739 final WindowProcessController proc = procs.valueAt(j);
5740 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5741 return proc;
5742 }
5743 }
5744 }
5745 return null;
5746 }
5747
Riddle Hsua0536432019-02-16 00:38:59 +08005748 int getUidState(int uid) {
5749 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005750 }
5751
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005752 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005753 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005754 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5755 }
5756
Michal Karpinski4026cae2019-02-12 11:51:47 +00005757 boolean isDeviceOwner(String packageName) {
5758 if (packageName == null) {
5759 return false;
5760 }
5761 return packageName.equals(mDeviceOwnerPackageName);
5762 }
5763
5764 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5765 mDeviceOwnerPackageName = deviceOwnerPkg;
5766 }
5767
Wale Ogunwale9de19442018-10-18 19:05:03 -07005768 /**
5769 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5770 * the whitelist
5771 */
5772 String getPendingTempWhitelistTagForUidLocked(int uid) {
5773 return mPendingTempWhitelist.get(uid);
5774 }
5775
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005776 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5777 if (true || Build.IS_USER) {
5778 return;
5779 }
5780
5781 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5782 StrictMode.allowThreadDiskWrites();
5783 try {
5784 File tracesDir = new File("/data/anr");
5785 File tracesFile = null;
5786 try {
5787 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5788
5789 StringBuilder sb = new StringBuilder();
5790 Time tobj = new Time();
5791 tobj.set(System.currentTimeMillis());
5792 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5793 sb.append(": ");
5794 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5795 sb.append(" since ");
5796 sb.append(msg);
5797 FileOutputStream fos = new FileOutputStream(tracesFile);
5798 fos.write(sb.toString().getBytes());
5799 if (app == null) {
5800 fos.write("\n*** No application process!".getBytes());
5801 }
5802 fos.close();
5803 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5804 } catch (IOException e) {
5805 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5806 return;
5807 }
5808
5809 if (app != null && app.getPid() > 0) {
5810 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5811 firstPids.add(app.getPid());
5812 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5813 }
5814
5815 File lastTracesFile = null;
5816 File curTracesFile = null;
5817 for (int i=9; i>=0; i--) {
5818 String name = String.format(Locale.US, "slow%02d.txt", i);
5819 curTracesFile = new File(tracesDir, name);
5820 if (curTracesFile.exists()) {
5821 if (lastTracesFile != null) {
5822 curTracesFile.renameTo(lastTracesFile);
5823 } else {
5824 curTracesFile.delete();
5825 }
5826 }
5827 lastTracesFile = curTracesFile;
5828 }
5829 tracesFile.renameTo(curTracesFile);
5830 } finally {
5831 StrictMode.setThreadPolicy(oldPolicy);
5832 }
5833 }
5834
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005835 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005836 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005837
5838
Wale Ogunwale98875612018-10-12 07:53:02 -07005839 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5840 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005841
Riddle Hsud93a6c42018-11-29 21:50:06 +08005842 H(Looper looper) {
5843 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005844 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005845
5846 @Override
5847 public void handleMessage(Message msg) {
5848 switch (msg.what) {
5849 case REPORT_TIME_TRACKER_MSG: {
5850 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5851 tracker.deliverResult(mContext);
5852 } break;
5853 }
5854 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005855 }
5856
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005857 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005858 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005859
5860 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005861 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005862 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005863
5864 @Override
5865 public void handleMessage(Message msg) {
5866 switch (msg.what) {
5867 case DISMISS_DIALOG_UI_MSG: {
5868 final Dialog d = (Dialog) msg.obj;
5869 d.dismiss();
5870 break;
5871 }
5872 }
5873 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005874 }
5875
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005876 final class LocalService extends ActivityTaskManagerInternal {
5877 @Override
5878 public SleepToken acquireSleepToken(String tag, int displayId) {
5879 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005880 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005881 }
5882
5883 @Override
5884 public ComponentName getHomeActivityForUser(int userId) {
5885 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005886 final ActivityRecord homeActivity =
5887 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005888 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005889 }
5890 }
5891
5892 @Override
5893 public void onLocalVoiceInteractionStarted(IBinder activity,
5894 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5895 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005896 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005897 }
5898 }
5899
5900 @Override
5901 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5902 synchronized (mGlobalLock) {
5903 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5904 reasons, timestamp);
5905 }
5906 }
5907
5908 @Override
5909 public void notifyAppTransitionFinished() {
5910 synchronized (mGlobalLock) {
5911 mStackSupervisor.notifyAppTransitionDone();
5912 }
5913 }
5914
5915 @Override
5916 public void notifyAppTransitionCancelled() {
5917 synchronized (mGlobalLock) {
5918 mStackSupervisor.notifyAppTransitionDone();
5919 }
5920 }
5921
5922 @Override
5923 public List<IBinder> getTopVisibleActivities() {
5924 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005925 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005926 }
5927 }
5928
5929 @Override
5930 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5931 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005932 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005933 }
5934 }
5935
5936 @Override
5937 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5938 Bundle bOptions) {
5939 Preconditions.checkNotNull(intents, "intents");
5940 final String[] resolvedTypes = new String[intents.length];
5941
5942 // UID of the package on user userId.
5943 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5944 // packageUid may not be initialized.
5945 int packageUid = 0;
5946 final long ident = Binder.clearCallingIdentity();
5947
5948 try {
5949 for (int i = 0; i < intents.length; i++) {
5950 resolvedTypes[i] =
5951 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5952 }
5953
5954 packageUid = AppGlobals.getPackageManager().getPackageUid(
5955 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5956 } catch (RemoteException e) {
5957 // Shouldn't happen.
5958 } finally {
5959 Binder.restoreCallingIdentity(ident);
5960 }
5961
Riddle Hsu591bf612019-02-14 17:55:31 +08005962 return getActivityStartController().startActivitiesInPackage(
5963 packageUid, packageName,
5964 intents, resolvedTypes, null /* resultTo */,
5965 SafeActivityOptions.fromBundle(bOptions), userId,
5966 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5967 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005968 }
5969
5970 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005971 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5972 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5973 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5974 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005975 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005976 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005977 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5978 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5979 userId, validateIncomingUser, originatingPendingIntent,
5980 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005981 }
5982 }
5983
5984 @Override
5985 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5986 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5987 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5988 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005989 PendingIntentRecord originatingPendingIntent,
5990 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005991 synchronized (mGlobalLock) {
5992 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5993 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5994 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005995 validateIncomingUser, originatingPendingIntent,
5996 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005997 }
5998 }
5999
6000 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006001 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6002 Intent intent, Bundle options, int userId) {
6003 return ActivityTaskManagerService.this.startActivityAsUser(
6004 caller, callerPacakge, intent,
6005 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6006 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6007 false /*validateIncomingUser*/);
6008 }
6009
6010 @Override
lumark588a3e82018-07-20 18:53:54 +08006011 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006012 synchronized (mGlobalLock) {
6013
6014 // We might change the visibilities here, so prepare an empty app transition which
6015 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006016 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006017 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006018 if (activityDisplay == null) {
6019 return;
6020 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006021 final DisplayContent dc = activityDisplay.mDisplayContent;
6022 final boolean wasTransitionSet =
6023 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006024 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006025 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006026 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006027 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006028
6029 // If there was a transition set already we don't want to interfere with it as we
6030 // might be starting it too early.
6031 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006032 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006033 }
6034 }
6035 if (callback != null) {
6036 callback.run();
6037 }
6038 }
6039
6040 @Override
6041 public void notifyKeyguardTrustedChanged() {
6042 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006043 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006044 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006045 }
6046 }
6047 }
6048
6049 /**
6050 * Called after virtual display Id is updated by
6051 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6052 * {@param vrVr2dDisplayId}.
6053 */
6054 @Override
6055 public void setVr2dDisplayId(int vr2dDisplayId) {
6056 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6057 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006058 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006059 }
6060 }
6061
6062 @Override
6063 public void setFocusedActivity(IBinder token) {
6064 synchronized (mGlobalLock) {
6065 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6066 if (r == null) {
6067 throw new IllegalArgumentException(
6068 "setFocusedActivity: No activity record matching token=" + token);
6069 }
Louis Chang19443452018-10-09 12:10:21 +08006070 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006071 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006072 }
6073 }
6074 }
6075
6076 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006078 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006079 }
6080
6081 @Override
6082 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006083 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006084 }
6085
6086 @Override
6087 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006088 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006089 }
6090
6091 @Override
6092 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6093 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6094 }
6095
6096 @Override
6097 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006098 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006099 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006100
6101 @Override
6102 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6103 synchronized (mGlobalLock) {
6104 mActiveVoiceInteractionServiceComponent = component;
6105 }
6106 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006107
6108 @Override
6109 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6110 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6111 return;
6112 }
6113 synchronized (mGlobalLock) {
6114 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6115 if (types == null) {
6116 if (uid < 0) {
6117 return;
6118 }
6119 types = new ArrayMap<>();
6120 mAllowAppSwitchUids.put(userId, types);
6121 }
6122 if (uid < 0) {
6123 types.remove(type);
6124 } else {
6125 types.put(type, uid);
6126 }
6127 }
6128 }
6129
6130 @Override
6131 public void onUserStopped(int userId) {
6132 synchronized (mGlobalLock) {
6133 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6134 mAllowAppSwitchUids.remove(userId);
6135 }
6136 }
6137
6138 @Override
6139 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6140 synchronized (mGlobalLock) {
6141 return ActivityTaskManagerService.this.isGetTasksAllowed(
6142 caller, callingPid, callingUid);
6143 }
6144 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006145
Riddle Hsua0536432019-02-16 00:38:59 +08006146 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006147 @Override
6148 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006149 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006150 mProcessNames.put(proc.mName, proc.mUid, proc);
6151 }
6152 }
6153
Riddle Hsua0536432019-02-16 00:38:59 +08006154 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006155 @Override
6156 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006157 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006158 mProcessNames.remove(name, uid);
6159 }
6160 }
6161
Riddle Hsua0536432019-02-16 00:38:59 +08006162 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006163 @Override
6164 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006165 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006166 if (proc == mHomeProcess) {
6167 mHomeProcess = null;
6168 }
6169 if (proc == mPreviousProcess) {
6170 mPreviousProcess = null;
6171 }
6172 }
6173 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006174
Riddle Hsua0536432019-02-16 00:38:59 +08006175 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006176 @Override
6177 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006178 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006179 return mTopProcessState;
6180 }
6181 }
6182
Riddle Hsua0536432019-02-16 00:38:59 +08006183 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006184 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006185 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006186 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006187 return proc == mHeavyWeightProcess;
6188 }
6189 }
6190
Riddle Hsua0536432019-02-16 00:38:59 +08006191 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006192 @Override
6193 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006194 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006195 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6196 }
6197 }
6198
6199 @Override
6200 public void finishHeavyWeightApp() {
6201 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006202 if (mHeavyWeightProcess != null) {
6203 mHeavyWeightProcess.finishActivities();
6204 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006205 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6206 mHeavyWeightProcess);
6207 }
6208 }
6209
Riddle Hsua0536432019-02-16 00:38:59 +08006210 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006211 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006212 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006213 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006214 return isSleepingLocked();
6215 }
6216 }
6217
6218 @Override
6219 public boolean isShuttingDown() {
6220 synchronized (mGlobalLock) {
6221 return mShuttingDown;
6222 }
6223 }
6224
6225 @Override
6226 public boolean shuttingDown(boolean booted, int timeout) {
6227 synchronized (mGlobalLock) {
6228 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006229 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006230 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006231 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006232 return mStackSupervisor.shutdownLocked(timeout);
6233 }
6234 }
6235
6236 @Override
6237 public void enableScreenAfterBoot(boolean booted) {
6238 synchronized (mGlobalLock) {
6239 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6240 SystemClock.uptimeMillis());
6241 mWindowManager.enableScreenAfterBoot();
6242 updateEventDispatchingLocked(booted);
6243 }
6244 }
6245
6246 @Override
6247 public boolean showStrictModeViolationDialog() {
6248 synchronized (mGlobalLock) {
6249 return mShowDialogs && !mSleeping && !mShuttingDown;
6250 }
6251 }
6252
6253 @Override
6254 public void showSystemReadyErrorDialogsIfNeeded() {
6255 synchronized (mGlobalLock) {
6256 try {
6257 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6258 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6259 + " data partition or your device will be unstable.");
6260 mUiHandler.post(() -> {
6261 if (mShowDialogs) {
6262 AlertDialog d = new BaseErrorDialog(mUiContext);
6263 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6264 d.setCancelable(false);
6265 d.setTitle(mUiContext.getText(R.string.android_system_label));
6266 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6267 d.setButton(DialogInterface.BUTTON_POSITIVE,
6268 mUiContext.getText(R.string.ok),
6269 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6270 d.show();
6271 }
6272 });
6273 }
6274 } catch (RemoteException e) {
6275 }
6276
6277 if (!Build.isBuildConsistent()) {
6278 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6279 mUiHandler.post(() -> {
6280 if (mShowDialogs) {
6281 AlertDialog d = new BaseErrorDialog(mUiContext);
6282 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6283 d.setCancelable(false);
6284 d.setTitle(mUiContext.getText(R.string.android_system_label));
6285 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6286 d.setButton(DialogInterface.BUTTON_POSITIVE,
6287 mUiContext.getText(R.string.ok),
6288 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6289 d.show();
6290 }
6291 });
6292 }
6293 }
6294 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006295
6296 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006297 public void onProcessMapped(int pid, WindowProcessController proc) {
6298 synchronized (mGlobalLock) {
6299 mPidMap.put(pid, proc);
6300 }
6301 }
6302
6303 @Override
6304 public void onProcessUnMapped(int pid) {
6305 synchronized (mGlobalLock) {
6306 mPidMap.remove(pid);
6307 }
6308 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006309
6310 @Override
6311 public void onPackageDataCleared(String name) {
6312 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006313 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006314 mAppWarnings.onPackageDataCleared(name);
6315 }
6316 }
6317
6318 @Override
6319 public void onPackageUninstalled(String name) {
6320 synchronized (mGlobalLock) {
6321 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006322 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006323 }
6324 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006325
6326 @Override
6327 public void onPackageAdded(String name, boolean replacing) {
6328 synchronized (mGlobalLock) {
6329 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6330 }
6331 }
6332
6333 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006334 public void onPackageReplaced(ApplicationInfo aInfo) {
6335 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006336 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006337 }
6338 }
6339
6340 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006341 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6342 synchronized (mGlobalLock) {
6343 return compatibilityInfoForPackageLocked(ai);
6344 }
6345 }
6346
Yunfan Chen75157d72018-07-27 14:47:21 +09006347 /**
6348 * Set the corresponding display information for the process global configuration. To be
6349 * called when we need to show IME on a different display.
6350 *
6351 * @param pid The process id associated with the IME window.
6352 * @param displayId The ID of the display showing the IME.
6353 */
6354 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006355 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006356 if (pid == MY_PID || pid < 0) {
6357 if (DEBUG_CONFIGURATION) {
6358 Slog.w(TAG,
6359 "Trying to update display configuration for system/invalid process.");
6360 }
6361 return;
6362 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006363 synchronized (mGlobalLock) {
6364 final ActivityDisplay activityDisplay =
6365 mRootActivityContainer.getActivityDisplay(displayId);
6366 if (activityDisplay == null) {
6367 // Call might come when display is not yet added or has been removed.
6368 if (DEBUG_CONFIGURATION) {
6369 Slog.w(TAG, "Trying to update display configuration for non-existing "
6370 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006371 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006372 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006373 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006374 final WindowProcessController process = mPidMap.get(pid);
6375 if (process == null) {
6376 if (DEBUG_CONFIGURATION) {
6377 Slog.w(TAG, "Trying to update display configuration for invalid "
6378 + "process, pid=" + pid);
6379 }
6380 return;
6381 }
6382 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6383 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006384 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006385
6386 @Override
6387 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6388 int requestCode, int resultCode, Intent data) {
6389 synchronized (mGlobalLock) {
6390 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006391 if (r != null && r.getActivityStack() != null) {
6392 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6393 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006394 }
6395 }
6396 }
6397
6398 @Override
6399 public void clearPendingResultForActivity(IBinder activityToken,
6400 WeakReference<PendingIntentRecord> pir) {
6401 synchronized (mGlobalLock) {
6402 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6403 if (r != null && r.pendingResults != null) {
6404 r.pendingResults.remove(pir);
6405 }
6406 }
6407 }
6408
6409 @Override
6410 public IIntentSender getIntentSender(int type, String packageName,
6411 int callingUid, int userId, IBinder token, String resultWho,
6412 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6413 Bundle bOptions) {
6414 synchronized (mGlobalLock) {
6415 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6416 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6417 }
6418 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006419
6420 @Override
6421 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6422 synchronized (mGlobalLock) {
6423 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6424 if (r == null) {
6425 return null;
6426 }
6427 if (r.mServiceConnectionsHolder == null) {
6428 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6429 ActivityTaskManagerService.this, r);
6430 }
6431
6432 return r.mServiceConnectionsHolder;
6433 }
6434 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006435
6436 @Override
6437 public Intent getHomeIntent() {
6438 synchronized (mGlobalLock) {
6439 return ActivityTaskManagerService.this.getHomeIntent();
6440 }
6441 }
6442
6443 @Override
6444 public boolean startHomeActivity(int userId, String reason) {
6445 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006446 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006447 }
6448 }
6449
6450 @Override
6451 public boolean startHomeOnAllDisplays(int userId, String reason) {
6452 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006453 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006454 }
6455 }
6456
Riddle Hsua0536432019-02-16 00:38:59 +08006457 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006458 @Override
6459 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006460 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006461 if (mFactoryTest == FACTORY_TEST_OFF) {
6462 return false;
6463 }
6464 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6465 && wpc.mName.equals(mTopComponent.getPackageName())) {
6466 return true;
6467 }
6468 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6469 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6470 }
6471 }
6472
6473 @Override
6474 public void updateTopComponentForFactoryTest() {
6475 synchronized (mGlobalLock) {
6476 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6477 return;
6478 }
6479 final ResolveInfo ri = mContext.getPackageManager()
6480 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6481 final CharSequence errorMsg;
6482 if (ri != null) {
6483 final ActivityInfo ai = ri.activityInfo;
6484 final ApplicationInfo app = ai.applicationInfo;
6485 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6486 mTopAction = Intent.ACTION_FACTORY_TEST;
6487 mTopData = null;
6488 mTopComponent = new ComponentName(app.packageName, ai.name);
6489 errorMsg = null;
6490 } else {
6491 errorMsg = mContext.getResources().getText(
6492 com.android.internal.R.string.factorytest_not_system);
6493 }
6494 } else {
6495 errorMsg = mContext.getResources().getText(
6496 com.android.internal.R.string.factorytest_no_action);
6497 }
6498 if (errorMsg == null) {
6499 return;
6500 }
6501
6502 mTopAction = null;
6503 mTopData = null;
6504 mTopComponent = null;
6505 mUiHandler.post(() -> {
6506 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6507 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006508 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006509 });
6510 }
6511 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006512
Riddle Hsua0536432019-02-16 00:38:59 +08006513 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006514 @Override
6515 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6516 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006517 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006518 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006519 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006520
6521 wpc.clearRecentTasks();
6522 wpc.clearActivities();
6523
6524 if (wpc.isInstrumenting()) {
6525 finishInstrumentationCallback.run();
6526 }
6527
Jorim Jaggid0752812018-10-16 16:07:20 +02006528 if (!restarting && hasVisibleActivities) {
6529 mWindowManager.deferSurfaceLayout();
6530 try {
6531 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6532 // If there was nothing to resume, and we are not already restarting
6533 // this process, but there is a visible activity that is hosted by the
6534 // process...then make sure all visible activities are running, taking
6535 // care of restarting this process.
6536 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6537 !PRESERVE_WINDOWS);
6538 }
6539 } finally {
6540 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006541 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006542 }
6543 }
6544 }
6545
6546 @Override
6547 public void closeSystemDialogs(String reason) {
6548 enforceNotIsolatedCaller("closeSystemDialogs");
6549
6550 final int pid = Binder.getCallingPid();
6551 final int uid = Binder.getCallingUid();
6552 final long origId = Binder.clearCallingIdentity();
6553 try {
6554 synchronized (mGlobalLock) {
6555 // Only allow this from foreground processes, so that background
6556 // applications can't abuse it to prevent system UI from being shown.
6557 if (uid >= FIRST_APPLICATION_UID) {
6558 final WindowProcessController proc = mPidMap.get(pid);
6559 if (!proc.isPerceptible()) {
6560 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6561 + " from background process " + proc);
6562 return;
6563 }
6564 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006565 mWindowManager.closeSystemDialogs(reason);
6566
Wale Ogunwaled32da472018-11-16 07:19:28 -08006567 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006568 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006569 // Call into AM outside the synchronized block.
6570 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006571 } finally {
6572 Binder.restoreCallingIdentity(origId);
6573 }
6574 }
6575
6576 @Override
6577 public void cleanupDisabledPackageComponents(
6578 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6579 synchronized (mGlobalLock) {
6580 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006581 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006582 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006583 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006584 mStackSupervisor.scheduleIdleLocked();
6585 }
6586
6587 // Clean-up disabled tasks
6588 getRecentTasks().cleanupDisabledPackageTasksLocked(
6589 packageName, disabledClasses, userId);
6590 }
6591 }
6592
6593 @Override
6594 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6595 int userId) {
6596 synchronized (mGlobalLock) {
6597
6598 boolean didSomething =
6599 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006600 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006601 null, doit, evenPersistent, userId);
6602 return didSomething;
6603 }
6604 }
6605
6606 @Override
6607 public void resumeTopActivities(boolean scheduleIdle) {
6608 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006609 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006610 if (scheduleIdle) {
6611 mStackSupervisor.scheduleIdleLocked();
6612 }
6613 }
6614 }
6615
Riddle Hsua0536432019-02-16 00:38:59 +08006616 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006617 @Override
6618 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006619 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006620 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6621 }
6622 }
6623
Riddle Hsua0536432019-02-16 00:38:59 +08006624 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006625 @Override
6626 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006627 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006628 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006629 }
6630 }
6631
6632 @Override
6633 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6634 try {
6635 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6636 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6637 }
6638 } catch (RemoteException ex) {
6639 throw new SecurityException("Fail to check is caller a privileged app", ex);
6640 }
6641
6642 synchronized (mGlobalLock) {
6643 final long ident = Binder.clearCallingIdentity();
6644 try {
6645 if (mAmInternal.shouldConfirmCredentials(userId)) {
6646 if (mKeyguardController.isKeyguardLocked()) {
6647 // Showing launcher to avoid user entering credential twice.
6648 startHomeActivity(currentUserId, "notifyLockedProfile");
6649 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006650 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006651 }
6652 } finally {
6653 Binder.restoreCallingIdentity(ident);
6654 }
6655 }
6656 }
6657
6658 @Override
6659 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6660 mAmInternal.enforceCallingPermission(
6661 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6662
6663 synchronized (mGlobalLock) {
6664 final long ident = Binder.clearCallingIdentity();
6665 try {
6666 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6667 FLAG_ACTIVITY_TASK_ON_HOME);
6668 ActivityOptions activityOptions = options != null
6669 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006670 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006671 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006672 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006673 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006674 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006675 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6676 UserHandle.CURRENT);
6677 } finally {
6678 Binder.restoreCallingIdentity(ident);
6679 }
6680 }
6681 }
6682
6683 @Override
6684 public void writeActivitiesToProto(ProtoOutputStream proto) {
6685 synchronized (mGlobalLock) {
6686 // The output proto of "activity --proto activities"
6687 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006688 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006689 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6690 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006691 }
6692 }
6693
6694 @Override
6695 public void saveANRState(String reason) {
6696 synchronized (mGlobalLock) {
6697 final StringWriter sw = new StringWriter();
6698 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6699 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6700 if (reason != null) {
6701 pw.println(" Reason: " + reason);
6702 }
6703 pw.println();
6704 getActivityStartController().dump(pw, " ", null);
6705 pw.println();
6706 pw.println("-------------------------------------------------------------------------------");
6707 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6708 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6709 "" /* header */);
6710 pw.println();
6711 pw.close();
6712
6713 mLastANRState = sw.toString();
6714 }
6715 }
6716
6717 @Override
6718 public void clearSavedANRState() {
6719 synchronized (mGlobalLock) {
6720 mLastANRState = null;
6721 }
6722 }
6723
6724 @Override
6725 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6726 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6727 synchronized (mGlobalLock) {
6728 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6729 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6730 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6731 dumpLastANRLocked(pw);
6732 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6733 dumpLastANRTracesLocked(pw);
6734 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6735 dumpActivityStarterLocked(pw, dumpPackage);
6736 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6737 dumpActivityContainersLocked(pw);
6738 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6739 if (getRecentTasks() != null) {
6740 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6741 }
6742 }
6743 }
6744 }
6745
6746 @Override
6747 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6748 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6749 int wakefulness) {
6750 synchronized (mGlobalLock) {
6751 if (mHomeProcess != null && (dumpPackage == null
6752 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6753 if (needSep) {
6754 pw.println();
6755 needSep = false;
6756 }
6757 pw.println(" mHomeProcess: " + mHomeProcess);
6758 }
6759 if (mPreviousProcess != null && (dumpPackage == null
6760 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6761 if (needSep) {
6762 pw.println();
6763 needSep = false;
6764 }
6765 pw.println(" mPreviousProcess: " + mPreviousProcess);
6766 }
6767 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6768 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6769 StringBuilder sb = new StringBuilder(128);
6770 sb.append(" mPreviousProcessVisibleTime: ");
6771 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6772 pw.println(sb);
6773 }
6774 if (mHeavyWeightProcess != null && (dumpPackage == null
6775 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6776 if (needSep) {
6777 pw.println();
6778 needSep = false;
6779 }
6780 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6781 }
6782 if (dumpPackage == null) {
6783 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006784 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006785 }
6786 if (dumpAll) {
6787 if (dumpPackage == null) {
6788 pw.println(" mConfigWillChange: "
6789 + getTopDisplayFocusedStack().mConfigWillChange);
6790 }
6791 if (mCompatModePackages.getPackages().size() > 0) {
6792 boolean printed = false;
6793 for (Map.Entry<String, Integer> entry
6794 : mCompatModePackages.getPackages().entrySet()) {
6795 String pkg = entry.getKey();
6796 int mode = entry.getValue();
6797 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6798 continue;
6799 }
6800 if (!printed) {
6801 pw.println(" mScreenCompatPackages:");
6802 printed = true;
6803 }
6804 pw.println(" " + pkg + ": " + mode);
6805 }
6806 }
6807 }
6808
6809 if (dumpPackage == null) {
6810 pw.println(" mWakefulness="
6811 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006812 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 if (mRunningVoice != null) {
6814 pw.println(" mRunningVoice=" + mRunningVoice);
6815 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6816 }
6817 pw.println(" mSleeping=" + mSleeping);
6818 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6819 pw.println(" mVrController=" + mVrController);
6820 }
6821 if (mCurAppTimeTracker != null) {
6822 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6823 }
6824 if (mAllowAppSwitchUids.size() > 0) {
6825 boolean printed = false;
6826 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6827 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6828 for (int j = 0; j < types.size(); j++) {
6829 if (dumpPackage == null ||
6830 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6831 if (needSep) {
6832 pw.println();
6833 needSep = false;
6834 }
6835 if (!printed) {
6836 pw.println(" mAllowAppSwitchUids:");
6837 printed = true;
6838 }
6839 pw.print(" User ");
6840 pw.print(mAllowAppSwitchUids.keyAt(i));
6841 pw.print(": Type ");
6842 pw.print(types.keyAt(j));
6843 pw.print(" = ");
6844 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6845 pw.println();
6846 }
6847 }
6848 }
6849 }
6850 if (dumpPackage == null) {
6851 if (mController != null) {
6852 pw.println(" mController=" + mController
6853 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6854 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006855 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6856 pw.println(" mLaunchingActivityWakeLock="
6857 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 }
6859
6860 return needSep;
6861 }
6862 }
6863
6864 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006865 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6866 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 synchronized (mGlobalLock) {
6868 if (dumpPackage == null) {
6869 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6870 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006871 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6872 if (mRunningVoice != null) {
6873 final long vrToken = proto.start(
6874 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6875 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6876 mRunningVoice.toString());
6877 mVoiceWakeLock.writeToProto(
6878 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6879 proto.end(vrToken);
6880 }
6881 mVrController.writeToProto(proto,
6882 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006883 if (mController != null) {
6884 final long token = proto.start(CONTROLLER);
6885 proto.write(CONTROLLER, mController.toString());
6886 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6887 proto.end(token);
6888 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006889 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6890 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6891 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
6893
6894 if (mHomeProcess != null && (dumpPackage == null
6895 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006896 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006897 }
6898
6899 if (mPreviousProcess != null && (dumpPackage == null
6900 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006901 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006902 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6903 }
6904
6905 if (mHeavyWeightProcess != null && (dumpPackage == null
6906 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006907 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 }
6909
6910 for (Map.Entry<String, Integer> entry
6911 : mCompatModePackages.getPackages().entrySet()) {
6912 String pkg = entry.getKey();
6913 int mode = entry.getValue();
6914 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6915 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6916 proto.write(PACKAGE, pkg);
6917 proto.write(MODE, mode);
6918 proto.end(compatToken);
6919 }
6920 }
6921
6922 if (mCurAppTimeTracker != null) {
6923 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6924 }
6925
6926 }
6927 }
6928
6929 @Override
6930 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6931 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6932 boolean dumpFocusedStackOnly) {
6933 synchronized (mGlobalLock) {
6934 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6935 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6936 }
6937 }
6938
6939 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006940 public void dumpForOom(PrintWriter pw) {
6941 synchronized (mGlobalLock) {
6942 pw.println(" mHomeProcess: " + mHomeProcess);
6943 pw.println(" mPreviousProcess: " + mPreviousProcess);
6944 if (mHeavyWeightProcess != null) {
6945 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6946 }
6947 }
6948 }
6949
6950 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006951 public boolean canGcNow() {
6952 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006953 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 }
6955 }
6956
Riddle Hsua0536432019-02-16 00:38:59 +08006957 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006958 @Override
6959 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006960 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006961 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006962 return top != null ? top.app : null;
6963 }
6964 }
6965
Riddle Hsua0536432019-02-16 00:38:59 +08006966 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006967 @Override
6968 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006969 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006970 if (mRootActivityContainer != null) {
6971 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006972 }
6973 }
6974 }
6975
6976 @Override
6977 public void scheduleDestroyAllActivities(String reason) {
6978 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006979 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006980 }
6981 }
6982
6983 @Override
6984 public void removeUser(int userId) {
6985 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006986 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006987 }
6988 }
6989
6990 @Override
6991 public boolean switchUser(int userId, UserState userState) {
6992 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006993 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 }
6995 }
6996
6997 @Override
6998 public void onHandleAppCrash(WindowProcessController wpc) {
6999 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007000 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007001 }
7002 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007003
7004 @Override
7005 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7006 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007007 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007008 }
7009 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007010
Riddle Hsua0536432019-02-16 00:38:59 +08007011 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007012 @Override
7013 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007014 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007015 }
7016
Riddle Hsua0536432019-02-16 00:38:59 +08007017 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007018 @Override
7019 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007020 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007021 }
7022
Riddle Hsua0536432019-02-16 00:38:59 +08007023 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007024 @Override
7025 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007026 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007027 }
7028
Riddle Hsua0536432019-02-16 00:38:59 +08007029 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007030 @Override
7031 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007032 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007033 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007034
7035 @Override
7036 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007037 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007038 mPendingTempWhitelist.put(uid, tag);
7039 }
7040 }
7041
7042 @Override
7043 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007044 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007045 mPendingTempWhitelist.remove(uid);
7046 }
7047 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007048
7049 @Override
7050 public boolean handleAppCrashInActivityController(String processName, int pid,
7051 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7052 Runnable killCrashingAppCallback) {
7053 synchronized (mGlobalLock) {
7054 if (mController == null) {
7055 return false;
7056 }
7057
7058 try {
7059 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7060 stackTrace)) {
7061 killCrashingAppCallback.run();
7062 return true;
7063 }
7064 } catch (RemoteException e) {
7065 mController = null;
7066 Watchdog.getInstance().setActivityController(null);
7067 }
7068 return false;
7069 }
7070 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007071
7072 @Override
7073 public void removeRecentTasksByPackageName(String packageName, int userId) {
7074 synchronized (mGlobalLock) {
7075 mRecentTasks.removeTasksByPackageName(packageName, userId);
7076 }
7077 }
7078
7079 @Override
7080 public void cleanupRecentTasksForUser(int userId) {
7081 synchronized (mGlobalLock) {
7082 mRecentTasks.cleanupLocked(userId);
7083 }
7084 }
7085
7086 @Override
7087 public void loadRecentTasksForUser(int userId) {
7088 synchronized (mGlobalLock) {
7089 mRecentTasks.loadUserRecentsLocked(userId);
7090 }
7091 }
7092
7093 @Override
7094 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7095 synchronized (mGlobalLock) {
7096 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7097 }
7098 }
7099
7100 @Override
7101 public void flushRecentTasks() {
7102 mRecentTasks.flush();
7103 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007104
7105 @Override
7106 public WindowProcessController getHomeProcess() {
7107 synchronized (mGlobalLock) {
7108 return mHomeProcess;
7109 }
7110 }
7111
7112 @Override
7113 public WindowProcessController getPreviousProcess() {
7114 synchronized (mGlobalLock) {
7115 return mPreviousProcess;
7116 }
7117 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007118
7119 @Override
7120 public void clearLockedTasks(String reason) {
7121 synchronized (mGlobalLock) {
7122 getLockTaskController().clearLockedTasks(reason);
7123 }
7124 }
7125
7126 @Override
7127 public void updateUserConfiguration() {
7128 synchronized (mGlobalLock) {
7129 final Configuration configuration = new Configuration(getGlobalConfiguration());
7130 final int currentUserId = mAmInternal.getCurrentUserId();
7131 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7132 configuration, currentUserId, Settings.System.canWrite(mContext));
7133 updateConfigurationLocked(configuration, null /* starting */,
7134 false /* initLocale */, false /* persistent */, currentUserId,
7135 false /* deferResume */);
7136 }
7137 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007138
7139 @Override
7140 public boolean canShowErrorDialogs() {
7141 synchronized (mGlobalLock) {
7142 return mShowDialogs && !mSleeping && !mShuttingDown
7143 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7144 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7145 mAmInternal.getCurrentUserId())
7146 && !(UserManager.isDeviceInDemoMode(mContext)
7147 && mAmInternal.getCurrentUser().isDemo());
7148 }
7149 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007150
7151 @Override
7152 public void setProfileApp(String profileApp) {
7153 synchronized (mGlobalLock) {
7154 mProfileApp = profileApp;
7155 }
7156 }
7157
7158 @Override
7159 public void setProfileProc(WindowProcessController wpc) {
7160 synchronized (mGlobalLock) {
7161 mProfileProc = wpc;
7162 }
7163 }
7164
7165 @Override
7166 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7167 synchronized (mGlobalLock) {
7168 mProfilerInfo = profilerInfo;
7169 }
7170 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007171
7172 @Override
7173 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7174 synchronized (mGlobalLock) {
7175 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7176 }
7177 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007178
7179 @Override
7180 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7181 synchronized (mGlobalLock) {
7182 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7183 }
7184 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007185
7186 @Override
7187 public boolean isUidForeground(int uid) {
7188 synchronized (mGlobalLock) {
7189 return ActivityTaskManagerService.this.isUidForeground(uid);
7190 }
7191 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007192
7193 @Override
7194 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7195 synchronized (mGlobalLock) {
7196 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7197 }
7198 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007199 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007200}