blob: 6664b7654916618bbaedc4f584496a1d11f01c72 [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
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001669 String restartingName = null;
1670 int restartingUid = 0;
1671 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001672 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001673 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001675 if (r.attachedToProcess()
1676 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1677 // The activity was requested to restart from
1678 // {@link #restartActivityProcessIfVisible}.
1679 restartingName = r.app.mName;
1680 restartingUid = r.app.mUid;
1681 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001682 r.activityStoppedLocked(icicle, persistentState, description);
1683 }
1684 }
1685
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001686 if (restartingName != null) {
1687 // In order to let the foreground activity can be restarted with its saved state from
1688 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1689 // until the activity reports stopped with the state. And the activity record will be
1690 // kept because the record state is restarting, then the activity will be restarted
1691 // immediately if it is still the top one.
1692 mStackSupervisor.removeRestartTimeouts(r);
1693 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1694 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001695 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696
1697 Binder.restoreCallingIdentity(origId);
1698 }
1699
1700 @Override
1701 public final void activityDestroyed(IBinder token) {
1702 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1703 synchronized (mGlobalLock) {
1704 ActivityStack stack = ActivityRecord.getStackLocked(token);
1705 if (stack != null) {
1706 stack.activityDestroyedLocked(token, "activityDestroyed");
1707 }
1708 }
1709 }
1710
1711 @Override
1712 public final void activityRelaunched(IBinder token) {
1713 final long origId = Binder.clearCallingIdentity();
1714 synchronized (mGlobalLock) {
1715 mStackSupervisor.activityRelaunchedLocked(token);
1716 }
1717 Binder.restoreCallingIdentity(origId);
1718 }
1719
1720 public final void activitySlept(IBinder token) {
1721 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1722
1723 final long origId = Binder.clearCallingIdentity();
1724
1725 synchronized (mGlobalLock) {
1726 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1727 if (r != null) {
1728 mStackSupervisor.activitySleptLocked(r);
1729 }
1730 }
1731
1732 Binder.restoreCallingIdentity(origId);
1733 }
1734
1735 @Override
1736 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1737 synchronized (mGlobalLock) {
1738 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1739 if (r == null) {
1740 return;
1741 }
1742 final long origId = Binder.clearCallingIdentity();
1743 try {
1744 r.setRequestedOrientation(requestedOrientation);
1745 } finally {
1746 Binder.restoreCallingIdentity(origId);
1747 }
1748 }
1749 }
1750
1751 @Override
1752 public int getRequestedOrientation(IBinder token) {
1753 synchronized (mGlobalLock) {
1754 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1755 if (r == null) {
1756 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1757 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001758 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 }
1760 }
1761
1762 @Override
1763 public void setImmersive(IBinder token, boolean immersive) {
1764 synchronized (mGlobalLock) {
1765 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1766 if (r == null) {
1767 throw new IllegalArgumentException();
1768 }
1769 r.immersive = immersive;
1770
1771 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001772 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001774 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776 }
1777 }
1778
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001779 void applyUpdateLockStateLocked(ActivityRecord r) {
1780 // Modifications to the UpdateLock state are done on our handler, outside
1781 // the activity manager's locks. The new state is determined based on the
1782 // state *now* of the relevant activity record. The object is passed to
1783 // the handler solely for logging detail, not to be consulted/modified.
1784 final boolean nextState = r != null && r.immersive;
1785 mH.post(() -> {
1786 if (mUpdateLock.isHeld() != nextState) {
1787 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1788 "Applying new update lock state '" + nextState + "' for " + r);
1789 if (nextState) {
1790 mUpdateLock.acquire();
1791 } else {
1792 mUpdateLock.release();
1793 }
1794 }
1795 });
1796 }
1797
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001798 @Override
1799 public boolean isImmersive(IBinder token) {
1800 synchronized (mGlobalLock) {
1801 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1802 if (r == null) {
1803 throw new IllegalArgumentException();
1804 }
1805 return r.immersive;
1806 }
1807 }
1808
1809 @Override
1810 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001813 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 return (r != null) ? r.immersive : false;
1815 }
1816 }
1817
1818 @Override
1819 public void overridePendingTransition(IBinder token, String packageName,
1820 int enterAnim, int exitAnim) {
1821 synchronized (mGlobalLock) {
1822 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1823 if (self == null) {
1824 return;
1825 }
1826
1827 final long origId = Binder.clearCallingIdentity();
1828
1829 if (self.isState(
1830 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001831 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001832 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 }
1834
1835 Binder.restoreCallingIdentity(origId);
1836 }
1837 }
1838
1839 @Override
1840 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001841 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001843 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001844 if (r == null) {
1845 return ActivityManager.COMPAT_MODE_UNKNOWN;
1846 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001847 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001848 }
1849 }
1850
1851 @Override
1852 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001857 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001858 if (r == null) {
1859 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1860 return;
1861 }
1862 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001863 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 }
1865 }
1866
1867 @Override
1868 public int getLaunchedFromUid(IBinder activityToken) {
1869 ActivityRecord srec;
1870 synchronized (mGlobalLock) {
1871 srec = ActivityRecord.forTokenLocked(activityToken);
1872 }
1873 if (srec == null) {
1874 return -1;
1875 }
1876 return srec.launchedFromUid;
1877 }
1878
1879 @Override
1880 public String getLaunchedFromPackage(IBinder activityToken) {
1881 ActivityRecord srec;
1882 synchronized (mGlobalLock) {
1883 srec = ActivityRecord.forTokenLocked(activityToken);
1884 }
1885 if (srec == null) {
1886 return null;
1887 }
1888 return srec.launchedFromPackage;
1889 }
1890
1891 @Override
1892 public boolean convertFromTranslucent(IBinder token) {
1893 final long origId = Binder.clearCallingIdentity();
1894 try {
1895 synchronized (mGlobalLock) {
1896 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1897 if (r == null) {
1898 return false;
1899 }
1900 final boolean translucentChanged = r.changeWindowTranslucency(true);
1901 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001902 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001904 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 return translucentChanged;
1906 }
1907 } finally {
1908 Binder.restoreCallingIdentity(origId);
1909 }
1910 }
1911
1912 @Override
1913 public boolean convertToTranslucent(IBinder token, Bundle options) {
1914 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1915 final long origId = Binder.clearCallingIdentity();
1916 try {
1917 synchronized (mGlobalLock) {
1918 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1919 if (r == null) {
1920 return false;
1921 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001922 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 int index = task.mActivities.lastIndexOf(r);
1924 if (index > 0) {
1925 ActivityRecord under = task.mActivities.get(index - 1);
1926 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1927 }
1928 final boolean translucentChanged = r.changeWindowTranslucency(false);
1929 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001930 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001931 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001932 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001933 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 return translucentChanged;
1935 }
1936 } finally {
1937 Binder.restoreCallingIdentity(origId);
1938 }
1939 }
1940
1941 @Override
1942 public void notifyActivityDrawn(IBinder token) {
1943 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1944 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001945 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001947 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 }
1949 }
1950 }
1951
1952 @Override
1953 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1954 synchronized (mGlobalLock) {
1955 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1956 if (r == null) {
1957 return;
1958 }
1959 r.reportFullyDrawnLocked(restoredFromBundle);
1960 }
1961 }
1962
1963 @Override
1964 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1965 synchronized (mGlobalLock) {
1966 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1967 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1968 return stack.mDisplayId;
1969 }
1970 return DEFAULT_DISPLAY;
1971 }
1972 }
1973
1974 @Override
1975 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001976 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001977 long ident = Binder.clearCallingIdentity();
1978 try {
1979 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001980 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001982 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 }
1984 return null;
1985 }
1986 } finally {
1987 Binder.restoreCallingIdentity(ident);
1988 }
1989 }
1990
1991 @Override
1992 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001993 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1995 final long callingId = Binder.clearCallingIdentity();
1996 try {
1997 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001998 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 if (stack == null) {
2000 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2001 return;
2002 }
2003 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002004 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002005 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 }
2007 }
2008 } finally {
2009 Binder.restoreCallingIdentity(callingId);
2010 }
2011 }
2012
2013 @Override
2014 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002015 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2017 final long callingId = Binder.clearCallingIdentity();
2018 try {
2019 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002020 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002021 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 if (task == null) {
2023 return;
2024 }
2025 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002026 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002027 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 }
2029 }
2030 } finally {
2031 Binder.restoreCallingIdentity(callingId);
2032 }
2033 }
2034
2035 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002036 public void restartActivityProcessIfVisible(IBinder activityToken) {
2037 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2038 final long callingId = Binder.clearCallingIdentity();
2039 try {
2040 synchronized (mGlobalLock) {
2041 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2042 if (r == null) {
2043 return;
2044 }
2045 r.restartProcessIfVisible();
2046 }
2047 } finally {
2048 Binder.restoreCallingIdentity(callingId);
2049 }
2050 }
2051
2052 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002053 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002054 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 synchronized (mGlobalLock) {
2056 final long ident = Binder.clearCallingIdentity();
2057 try {
2058 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2059 "remove-task");
2060 } finally {
2061 Binder.restoreCallingIdentity(ident);
2062 }
2063 }
2064 }
2065
2066 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002067 public void removeAllVisibleRecentTasks() {
2068 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2069 synchronized (mGlobalLock) {
2070 final long ident = Binder.clearCallingIdentity();
2071 try {
2072 getRecentTasks().removeAllVisibleTasks();
2073 } finally {
2074 Binder.restoreCallingIdentity(ident);
2075 }
2076 }
2077 }
2078
2079 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2081 synchronized (mGlobalLock) {
2082 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2083 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002084 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 }
2086 }
2087 return false;
2088 }
2089
2090 @Override
2091 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2092 Intent resultData) {
2093
2094 synchronized (mGlobalLock) {
2095 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2096 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002097 return r.getActivityStack().navigateUpToLocked(
2098 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 }
2100 return false;
2101 }
2102 }
2103
2104 /**
2105 * Attempts to move a task backwards in z-order (the order of activities within the task is
2106 * unchanged).
2107 *
2108 * There are several possible results of this call:
2109 * - if the task is locked, then we will show the lock toast
2110 * - if there is a task behind the provided task, then that task is made visible and resumed as
2111 * this task is moved to the back
2112 * - otherwise, if there are no other tasks in the stack:
2113 * - if this task is in the pinned stack, then we remove the stack completely, which will
2114 * have the effect of moving the task to the top or bottom of the fullscreen stack
2115 * (depending on whether it is visible)
2116 * - otherwise, we simply return home and hide this task
2117 *
2118 * @param token A reference to the activity we wish to move
2119 * @param nonRoot If false then this only works if the activity is the root
2120 * of a task; if true it will work for any activity in a task.
2121 * @return Returns true if the move completed, false if not.
2122 */
2123 @Override
2124 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002125 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 synchronized (mGlobalLock) {
2127 final long origId = Binder.clearCallingIdentity();
2128 try {
2129 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002130 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 if (task != null) {
2132 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2133 }
2134 } finally {
2135 Binder.restoreCallingIdentity(origId);
2136 }
2137 }
2138 return false;
2139 }
2140
2141 @Override
2142 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002143 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002144 long ident = Binder.clearCallingIdentity();
2145 Rect rect = new Rect();
2146 try {
2147 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002148 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2150 if (task == null) {
2151 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2152 return rect;
2153 }
2154 if (task.getStack() != null) {
2155 // Return the bounds from window manager since it will be adjusted for various
2156 // things like the presense of a docked stack for tasks that aren't resizeable.
2157 task.getWindowContainerBounds(rect);
2158 } else {
2159 // Task isn't in window manager yet since it isn't associated with a stack.
2160 // Return the persist value from activity manager
2161 if (!task.matchParentBounds()) {
2162 rect.set(task.getBounds());
2163 } else if (task.mLastNonFullscreenBounds != null) {
2164 rect.set(task.mLastNonFullscreenBounds);
2165 }
2166 }
2167 }
2168 } finally {
2169 Binder.restoreCallingIdentity(ident);
2170 }
2171 return rect;
2172 }
2173
2174 @Override
2175 public ActivityManager.TaskDescription getTaskDescription(int id) {
2176 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002177 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002179 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2181 if (tr != null) {
2182 return tr.lastTaskDescription;
2183 }
2184 }
2185 return null;
2186 }
2187
2188 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002189 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2190 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2191 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2192 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2193 return;
2194 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002195 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002196 synchronized (mGlobalLock) {
2197 final long ident = Binder.clearCallingIdentity();
2198 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002199 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002200 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002201 if (task == null) {
2202 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2203 return;
2204 }
2205
2206 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2207 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2208
2209 if (!task.isActivityTypeStandardOrUndefined()) {
2210 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2211 + " non-standard task " + taskId + " to windowing mode="
2212 + windowingMode);
2213 }
2214
2215 final ActivityStack stack = task.getStack();
2216 if (toTop) {
2217 stack.moveToFront("setTaskWindowingMode", task);
2218 }
2219 stack.setWindowingMode(windowingMode);
2220 } finally {
2221 Binder.restoreCallingIdentity(ident);
2222 }
2223 }
2224 }
2225
2226 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002228 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 ActivityRecord r = getCallingRecordLocked(token);
2230 return r != null ? r.info.packageName : null;
2231 }
2232 }
2233
2234 @Override
2235 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002236 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 ActivityRecord r = getCallingRecordLocked(token);
2238 return r != null ? r.intent.getComponent() : null;
2239 }
2240 }
2241
2242 private ActivityRecord getCallingRecordLocked(IBinder token) {
2243 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2244 if (r == null) {
2245 return null;
2246 }
2247 return r.resultTo;
2248 }
2249
2250 @Override
2251 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002252 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253
2254 synchronized (mGlobalLock) {
2255 final long origId = Binder.clearCallingIdentity();
2256 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002257 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002258 } finally {
2259 Binder.restoreCallingIdentity(origId);
2260 }
2261 }
2262 }
2263
2264 /**
2265 * TODO: Add mController hook
2266 */
2267 @Override
2268 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002269 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002270
2271 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2272 synchronized (mGlobalLock) {
2273 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2274 false /* fromRecents */);
2275 }
2276 }
2277
2278 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2279 boolean fromRecents) {
2280
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002281 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002282 Binder.getCallingUid(), -1, -1, "Task to front")) {
2283 SafeActivityOptions.abort(options);
2284 return;
2285 }
2286 final long origId = Binder.clearCallingIdentity();
2287 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002288 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 if (task == null) {
2290 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002291 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002292 return;
2293 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002294 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002296 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 return;
2298 }
2299 ActivityOptions realOptions = options != null
2300 ? options.getOptions(mStackSupervisor)
2301 : null;
2302 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2303 false /* forceNonResizable */);
2304
2305 final ActivityRecord topActivity = task.getTopActivity();
2306 if (topActivity != null) {
2307
2308 // We are reshowing a task, use a starting window to hide the initial draw delay
2309 // so the transition can start earlier.
2310 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2311 true /* taskSwitch */, fromRecents);
2312 }
2313 } finally {
2314 Binder.restoreCallingIdentity(origId);
2315 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002316 }
2317
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002318 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2319 int callingPid, int callingUid, String name) {
2320 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2321 return true;
2322 }
2323
2324 if (getRecentTasks().isCallerRecents(sourceUid)) {
2325 return true;
2326 }
2327
2328 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2329 if (perm == PackageManager.PERMISSION_GRANTED) {
2330 return true;
2331 }
2332 if (checkAllowAppSwitchUid(sourceUid)) {
2333 return true;
2334 }
2335
2336 // If the actual IPC caller is different from the logical source, then
2337 // also see if they are allowed to control app switches.
2338 if (callingUid != -1 && callingUid != sourceUid) {
2339 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2340 if (perm == PackageManager.PERMISSION_GRANTED) {
2341 return true;
2342 }
2343 if (checkAllowAppSwitchUid(callingUid)) {
2344 return true;
2345 }
2346 }
2347
2348 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2349 return false;
2350 }
2351
2352 private boolean checkAllowAppSwitchUid(int uid) {
2353 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2354 if (types != null) {
2355 for (int i = types.size() - 1; i >= 0; i--) {
2356 if (types.valueAt(i).intValue() == uid) {
2357 return true;
2358 }
2359 }
2360 }
2361 return false;
2362 }
2363
2364 @Override
2365 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2366 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2367 "setActivityController()");
2368 synchronized (mGlobalLock) {
2369 mController = controller;
2370 mControllerIsAMonkey = imAMonkey;
2371 Watchdog.getInstance().setActivityController(controller);
2372 }
2373 }
2374
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002375 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002376 synchronized (mGlobalLock) {
2377 return mController != null && mControllerIsAMonkey;
2378 }
2379 }
2380
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002381 @Override
2382 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2383 synchronized (mGlobalLock) {
2384 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2385 }
2386 }
2387
2388 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002389 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2390 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2391 }
2392
2393 @Override
2394 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2395 @WindowConfiguration.ActivityType int ignoreActivityType,
2396 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2397 final int callingUid = Binder.getCallingUid();
2398 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2399
2400 synchronized (mGlobalLock) {
2401 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2402
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002403 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002404 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002405 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002406 ignoreWindowingMode, callingUid, allowed);
2407 }
2408
2409 return list;
2410 }
2411
2412 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2414 synchronized (mGlobalLock) {
2415 final long origId = Binder.clearCallingIdentity();
2416 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2417 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002418 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 }
2420 Binder.restoreCallingIdentity(origId);
2421 }
2422 }
2423
2424 @Override
2425 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002426 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002427 ActivityStack stack = ActivityRecord.getStackLocked(token);
2428 if (stack != null) {
2429 return stack.willActivityBeVisibleLocked(token);
2430 }
2431 return false;
2432 }
2433 }
2434
2435 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002436 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002437 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002438 synchronized (mGlobalLock) {
2439 final long ident = Binder.clearCallingIdentity();
2440 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002441 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002442 if (task == null) {
2443 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2444 return;
2445 }
2446
2447 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2448 + " to stackId=" + stackId + " toTop=" + toTop);
2449
Wale Ogunwaled32da472018-11-16 07:19:28 -08002450 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002451 if (stack == null) {
2452 throw new IllegalStateException(
2453 "moveTaskToStack: No stack for stackId=" + stackId);
2454 }
2455 if (!stack.isActivityTypeStandardOrUndefined()) {
2456 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2457 + taskId + " to stack " + stackId);
2458 }
2459 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002460 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002461 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2462 }
2463 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2464 "moveTaskToStack");
2465 } finally {
2466 Binder.restoreCallingIdentity(ident);
2467 }
2468 }
2469 }
2470
2471 @Override
2472 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2473 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002474 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002475
2476 final long ident = Binder.clearCallingIdentity();
2477 try {
2478 synchronized (mGlobalLock) {
2479 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002480 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002481 if (stack == null) {
2482 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2483 return;
2484 }
2485 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2486 throw new IllegalArgumentException("Stack: " + stackId
2487 + " doesn't support animated resize.");
2488 }
2489 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2490 animationDuration, false /* fromFullscreen */);
2491 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002492 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002493 if (stack == null) {
2494 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2495 return;
2496 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002497 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002498 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2499 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2500 }
2501 }
2502 } finally {
2503 Binder.restoreCallingIdentity(ident);
2504 }
2505 }
2506
wilsonshih5c4cf522019-01-25 09:03:47 +08002507 @Override
2508 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2509 int animationDuration) {
2510 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2511
2512 final long ident = Binder.clearCallingIdentity();
2513 try {
2514 synchronized (mGlobalLock) {
2515 if (xOffset == 0 && yOffset == 0) {
2516 return;
2517 }
2518 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2519 if (stack == null) {
2520 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2521 return;
2522 }
2523 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2524 throw new IllegalArgumentException("Stack: " + stackId
2525 + " doesn't support animated resize.");
2526 }
2527 final Rect destBounds = new Rect();
2528 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002529 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002530 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2531 return;
2532 }
2533 destBounds.offset(xOffset, yOffset);
2534 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2535 animationDuration, false /* fromFullscreen */);
2536 }
2537 } finally {
2538 Binder.restoreCallingIdentity(ident);
2539 }
2540 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002541 /**
2542 * Moves the specified task to the primary-split-screen stack.
2543 *
2544 * @param taskId Id of task to move.
2545 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2546 * exist already. See
2547 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2548 * and
2549 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2550 * @param toTop If the task and stack should be moved to the top.
2551 * @param animate Whether we should play an animation for the moving the task.
2552 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2553 * stack. Pass {@code null} to use default bounds.
2554 * @param showRecents If the recents activity should be shown on the other side of the task
2555 * going into split-screen mode.
2556 */
2557 @Override
2558 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2559 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002560 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002561 "setTaskWindowingModeSplitScreenPrimary()");
2562 synchronized (mGlobalLock) {
2563 final long ident = Binder.clearCallingIdentity();
2564 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002565 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002566 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002567 if (task == null) {
2568 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2569 return false;
2570 }
2571 if (DEBUG_STACK) Slog.d(TAG_STACK,
2572 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2573 + " to createMode=" + createMode + " toTop=" + toTop);
2574 if (!task.isActivityTypeStandardOrUndefined()) {
2575 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2576 + " non-standard task " + taskId + " to split-screen windowing mode");
2577 }
2578
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002579 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002580 final int windowingMode = task.getWindowingMode();
2581 final ActivityStack stack = task.getStack();
2582 if (toTop) {
2583 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2584 }
2585 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002586 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2587 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588 return windowingMode != task.getWindowingMode();
2589 } finally {
2590 Binder.restoreCallingIdentity(ident);
2591 }
2592 }
2593 }
2594
2595 /**
2596 * Removes stacks in the input windowing modes from the system if they are of activity type
2597 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2598 */
2599 @Override
2600 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002601 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 "removeStacksInWindowingModes()");
2603
2604 synchronized (mGlobalLock) {
2605 final long ident = Binder.clearCallingIdentity();
2606 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002607 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608 } finally {
2609 Binder.restoreCallingIdentity(ident);
2610 }
2611 }
2612 }
2613
2614 @Override
2615 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002616 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 "removeStacksWithActivityTypes()");
2618
2619 synchronized (mGlobalLock) {
2620 final long ident = Binder.clearCallingIdentity();
2621 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002622 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002623 } finally {
2624 Binder.restoreCallingIdentity(ident);
2625 }
2626 }
2627 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002628
2629 @Override
2630 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2631 int userId) {
2632 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002633 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2634 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002635 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002636 final boolean detailed = checkGetTasksPermission(
2637 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2638 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002639 == PackageManager.PERMISSION_GRANTED;
2640
2641 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002642 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002643 callingUid);
2644 }
2645 }
2646
2647 @Override
2648 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002649 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002650 long ident = Binder.clearCallingIdentity();
2651 try {
2652 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002653 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 }
2655 } finally {
2656 Binder.restoreCallingIdentity(ident);
2657 }
2658 }
2659
2660 @Override
2661 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002662 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663 long ident = Binder.clearCallingIdentity();
2664 try {
2665 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002666 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002667 }
2668 } finally {
2669 Binder.restoreCallingIdentity(ident);
2670 }
2671 }
2672
2673 @Override
2674 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002675 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002676 final long callingUid = Binder.getCallingUid();
2677 final long origId = Binder.clearCallingIdentity();
2678 try {
2679 synchronized (mGlobalLock) {
2680 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002681 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002682 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2683 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2684 }
2685 } finally {
2686 Binder.restoreCallingIdentity(origId);
2687 }
2688 }
2689
2690 @Override
2691 public void startLockTaskModeByToken(IBinder token) {
2692 synchronized (mGlobalLock) {
2693 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2694 if (r == null) {
2695 return;
2696 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002697 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002698 }
2699 }
2700
2701 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002702 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002703 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002704 // This makes inner call to look as if it was initiated by system.
2705 long ident = Binder.clearCallingIdentity();
2706 try {
2707 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002708 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002709 MATCH_TASK_IN_STACKS_ONLY);
2710 if (task == null) {
2711 return;
2712 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713
2714 // When starting lock task mode the stack must be in front and focused
2715 task.getStack().moveToFront("startSystemLockTaskMode");
2716 startLockTaskModeLocked(task, true /* isSystemCaller */);
2717 }
2718 } finally {
2719 Binder.restoreCallingIdentity(ident);
2720 }
2721 }
2722
2723 @Override
2724 public void stopLockTaskModeByToken(IBinder token) {
2725 synchronized (mGlobalLock) {
2726 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2727 if (r == null) {
2728 return;
2729 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002730 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002731 }
2732 }
2733
2734 /**
2735 * This API should be called by SystemUI only when user perform certain action to dismiss
2736 * lock task mode. We should only dismiss pinned lock task mode in this case.
2737 */
2738 @Override
2739 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002740 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002741 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2742 }
2743
2744 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2745 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2746 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2747 return;
2748 }
2749
Wale Ogunwaled32da472018-11-16 07:19:28 -08002750 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 if (stack == null || task != stack.topTask()) {
2752 throw new IllegalArgumentException("Invalid task, not in foreground");
2753 }
2754
2755 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2756 // system or a specific app.
2757 // * System-initiated requests will only start the pinned mode (screen pinning)
2758 // * App-initiated requests
2759 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2760 // - will start the pinned mode, otherwise
2761 final int callingUid = Binder.getCallingUid();
2762 long ident = Binder.clearCallingIdentity();
2763 try {
2764 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002765 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002767 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 } finally {
2769 Binder.restoreCallingIdentity(ident);
2770 }
2771 }
2772
2773 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2774 final int callingUid = Binder.getCallingUid();
2775 long ident = Binder.clearCallingIdentity();
2776 try {
2777 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002778 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 }
2780 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2781 // task and jumping straight into a call in the case of emergency call back.
2782 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2783 if (tm != null) {
2784 tm.showInCallScreen(false);
2785 }
2786 } finally {
2787 Binder.restoreCallingIdentity(ident);
2788 }
2789 }
2790
2791 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002792 public void updateLockTaskPackages(int userId, String[] packages) {
2793 final int callingUid = Binder.getCallingUid();
2794 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2795 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2796 "updateLockTaskPackages()");
2797 }
2798 synchronized (this) {
2799 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2800 + Arrays.toString(packages));
2801 getLockTaskController().updateLockTaskPackages(userId, packages);
2802 }
2803 }
2804
2805 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 public boolean isInLockTaskMode() {
2807 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2808 }
2809
2810 @Override
2811 public int getLockTaskModeState() {
2812 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002813 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 }
2815 }
2816
2817 @Override
2818 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2819 synchronized (mGlobalLock) {
2820 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2821 if (r != null) {
2822 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002823 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002825 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827 }
2828 }
2829
2830 @Override
2831 public Bundle getActivityOptions(IBinder token) {
2832 final long origId = Binder.clearCallingIdentity();
2833 try {
2834 synchronized (mGlobalLock) {
2835 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2836 if (r != null) {
2837 final ActivityOptions activityOptions = r.takeOptionsLocked();
2838 return activityOptions == null ? null : activityOptions.toBundle();
2839 }
2840 return null;
2841 }
2842 } finally {
2843 Binder.restoreCallingIdentity(origId);
2844 }
2845 }
2846
2847 @Override
2848 public List<IBinder> getAppTasks(String callingPackage) {
2849 int callingUid = Binder.getCallingUid();
2850 long ident = Binder.clearCallingIdentity();
2851 try {
2852 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002853 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 }
2855 } finally {
2856 Binder.restoreCallingIdentity(ident);
2857 }
2858 }
2859
2860 @Override
2861 public void finishVoiceTask(IVoiceInteractionSession session) {
2862 synchronized (mGlobalLock) {
2863 final long origId = Binder.clearCallingIdentity();
2864 try {
2865 // TODO: VI Consider treating local voice interactions and voice tasks
2866 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002867 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 } finally {
2869 Binder.restoreCallingIdentity(origId);
2870 }
2871 }
2872
2873 }
2874
2875 @Override
2876 public boolean isTopOfTask(IBinder token) {
2877 synchronized (mGlobalLock) {
2878 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002879 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 }
2881 }
2882
2883 @Override
2884 public void notifyLaunchTaskBehindComplete(IBinder token) {
2885 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2886 }
2887
2888 @Override
2889 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002890 mH.post(() -> {
2891 synchronized (mGlobalLock) {
2892 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002893 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002894 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002895 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002896 } catch (RemoteException e) {
2897 }
2898 }
2899 }
2900
2901 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903
2904 /** Called from an app when assist data is ready. */
2905 @Override
2906 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2907 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002908 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 synchronized (pae) {
2910 pae.result = extras;
2911 pae.structure = structure;
2912 pae.content = content;
2913 if (referrer != null) {
2914 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2915 }
2916 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002917 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002918 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2919 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002920 structure.setHomeActivity(pae.isHome);
2921 }
2922 pae.haveResult = true;
2923 pae.notifyAll();
2924 if (pae.intent == null && pae.receiver == null) {
2925 // Caller is just waiting for the result.
2926 return;
2927 }
2928 }
2929 // We are now ready to launch the assist activity.
2930 IAssistDataReceiver sendReceiver = null;
2931 Bundle sendBundle = null;
2932 synchronized (mGlobalLock) {
2933 buildAssistBundleLocked(pae, extras);
2934 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002935 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936 if (!exists) {
2937 // Timed out.
2938 return;
2939 }
2940
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002941 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 // Caller wants result sent back to them.
2943 sendBundle = new Bundle();
2944 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2945 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2946 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2947 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2948 }
2949 }
2950 if (sendReceiver != null) {
2951 try {
2952 sendReceiver.onHandleAssistData(sendBundle);
2953 } catch (RemoteException e) {
2954 }
2955 return;
2956 }
2957
2958 final long ident = Binder.clearCallingIdentity();
2959 try {
2960 if (TextUtils.equals(pae.intent.getAction(),
2961 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2962 pae.intent.putExtras(pae.extras);
2963 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2964 } else {
2965 pae.intent.replaceExtras(pae.extras);
2966 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2967 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2968 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002969 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970
2971 try {
2972 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2973 } catch (ActivityNotFoundException e) {
2974 Slog.w(TAG, "No activity to handle assist action.", e);
2975 }
2976 }
2977 } finally {
2978 Binder.restoreCallingIdentity(ident);
2979 }
2980 }
2981
2982 @Override
2983 public int addAppTask(IBinder activityToken, Intent intent,
2984 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2985 final int callingUid = Binder.getCallingUid();
2986 final long callingIdent = Binder.clearCallingIdentity();
2987
2988 try {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2991 if (r == null) {
2992 throw new IllegalArgumentException("Activity does not exist; token="
2993 + activityToken);
2994 }
2995 ComponentName comp = intent.getComponent();
2996 if (comp == null) {
2997 throw new IllegalArgumentException("Intent " + intent
2998 + " must specify explicit component");
2999 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003000 if (thumbnail.getWidth() != mThumbnailWidth
3001 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003002 throw new IllegalArgumentException("Bad thumbnail size: got "
3003 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003004 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003005 }
3006 if (intent.getSelector() != null) {
3007 intent.setSelector(null);
3008 }
3009 if (intent.getSourceBounds() != null) {
3010 intent.setSourceBounds(null);
3011 }
3012 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3013 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3014 // The caller has added this as an auto-remove task... that makes no
3015 // sense, so turn off auto-remove.
3016 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3017 }
3018 }
3019 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3020 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3021 if (ainfo.applicationInfo.uid != callingUid) {
3022 throw new SecurityException(
3023 "Can't add task for another application: target uid="
3024 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3025 }
3026
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003027 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003028 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003029 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003031 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 // The app has too many tasks already and we can't add any more
3033 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3034 return INVALID_TASK_ID;
3035 }
3036 task.lastTaskDescription.copyFrom(description);
3037
3038 // TODO: Send the thumbnail to WM to store it.
3039
3040 return task.taskId;
3041 }
3042 } finally {
3043 Binder.restoreCallingIdentity(callingIdent);
3044 }
3045 }
3046
3047 @Override
3048 public Point getAppTaskThumbnailSize() {
3049 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003050 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 }
3052 }
3053
3054 @Override
3055 public void setTaskResizeable(int taskId, int resizeableMode) {
3056 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003057 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3059 if (task == null) {
3060 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3061 return;
3062 }
3063 task.setResizeMode(resizeableMode);
3064 }
3065 }
3066
3067 @Override
3068 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003069 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 long ident = Binder.clearCallingIdentity();
3071 try {
3072 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003073 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003074 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 if (task == null) {
3076 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3077 return;
3078 }
3079 // Place the task in the right stack if it isn't there already based on
3080 // the requested bounds.
3081 // The stack transition logic is:
3082 // - a null bounds on a freeform task moves that task to fullscreen
3083 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3084 // that task to freeform
3085 // - otherwise the task is not moved
3086 ActivityStack stack = task.getStack();
3087 if (!task.getWindowConfiguration().canResizeTask()) {
3088 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3089 }
3090 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3091 stack = stack.getDisplay().getOrCreateStack(
3092 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3093 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3094 stack = stack.getDisplay().getOrCreateStack(
3095 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3096 }
3097
3098 // Reparent the task to the right stack if necessary
3099 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3100 if (stack != task.getStack()) {
3101 // Defer resume until the task is resized below
3102 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3103 DEFER_RESUME, "resizeTask");
3104 preserveWindow = false;
3105 }
3106
3107 // After reparenting (which only resizes the task to the stack bounds), resize the
3108 // task to the actual bounds provided
3109 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3110 }
3111 } finally {
3112 Binder.restoreCallingIdentity(ident);
3113 }
3114 }
3115
3116 @Override
3117 public boolean releaseActivityInstance(IBinder token) {
3118 synchronized (mGlobalLock) {
3119 final long origId = Binder.clearCallingIdentity();
3120 try {
3121 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3122 if (r == null) {
3123 return false;
3124 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003125 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003126 } finally {
3127 Binder.restoreCallingIdentity(origId);
3128 }
3129 }
3130 }
3131
3132 @Override
3133 public void releaseSomeActivities(IApplicationThread appInt) {
3134 synchronized (mGlobalLock) {
3135 final long origId = Binder.clearCallingIdentity();
3136 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003137 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003138 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 } finally {
3140 Binder.restoreCallingIdentity(origId);
3141 }
3142 }
3143 }
3144
3145 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003146 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003147 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 != PackageManager.PERMISSION_GRANTED) {
3149 throw new SecurityException("Requires permission "
3150 + android.Manifest.permission.DEVICE_POWER);
3151 }
3152
3153 synchronized (mGlobalLock) {
3154 long ident = Binder.clearCallingIdentity();
3155 if (mKeyguardShown != keyguardShowing) {
3156 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003157 final Message msg = PooledLambda.obtainMessage(
3158 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3159 keyguardShowing);
3160 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 }
3162 try {
wilsonshih177261f2019-02-22 12:02:18 +08003163 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 } finally {
3165 Binder.restoreCallingIdentity(ident);
3166 }
3167 }
3168
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003169 mH.post(() -> {
3170 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3171 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3172 }
3173 });
3174 }
3175
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003176 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003177 mH.post(() -> {
3178 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3179 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3180 }
3181 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 }
3183
3184 @Override
3185 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3187 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188
3189 final File passedIconFile = new File(filePath);
3190 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3191 passedIconFile.getName());
3192 if (!legitIconFile.getPath().equals(filePath)
3193 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3194 throw new IllegalArgumentException("Bad file path: " + filePath
3195 + " passed for userId " + userId);
3196 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003197 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 }
3199
3200 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003201 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003202 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3203 final ActivityOptions activityOptions = safeOptions != null
3204 ? safeOptions.getOptions(mStackSupervisor)
3205 : null;
3206 if (activityOptions == null
3207 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3208 || activityOptions.getCustomInPlaceResId() == 0) {
3209 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3210 "with valid animation");
3211 }
lumark588a3e82018-07-20 18:53:54 +08003212 // Get top display of front most application.
3213 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3214 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003215 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3216 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3217 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003218 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003219 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003220 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003221 }
3222
3223 @Override
3224 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003225 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 synchronized (mGlobalLock) {
3227 final long ident = Binder.clearCallingIdentity();
3228 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003229 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003230 if (stack == null) {
3231 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3232 return;
3233 }
3234 if (!stack.isActivityTypeStandardOrUndefined()) {
3235 throw new IllegalArgumentException(
3236 "Removing non-standard stack is not allowed.");
3237 }
3238 mStackSupervisor.removeStack(stack);
3239 } finally {
3240 Binder.restoreCallingIdentity(ident);
3241 }
3242 }
3243 }
3244
3245 @Override
3246 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003247 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003248
3249 synchronized (mGlobalLock) {
3250 final long ident = Binder.clearCallingIdentity();
3251 try {
3252 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3253 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003254 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 } finally {
3256 Binder.restoreCallingIdentity(ident);
3257 }
3258 }
3259 }
3260
3261 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003262 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003263 synchronized (mGlobalLock) {
3264 long ident = Binder.clearCallingIdentity();
3265 try {
3266 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3267 if (r == null) {
3268 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003269 "toggleFreeformWindowingMode: No activity record matching token="
3270 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 }
3272
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003273 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003274 if (stack == null) {
3275 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3276 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003277 }
3278
Yunfan Chend967af82019-01-17 18:30:18 +09003279 if (!stack.inFreeformWindowingMode()
3280 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3281 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3282 + "toggle between fullscreen and freeform.");
3283 }
3284
3285 if (stack.inFreeformWindowingMode()) {
3286 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3287 } else {
3288 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3289 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003290 } finally {
3291 Binder.restoreCallingIdentity(ident);
3292 }
3293 }
3294 }
3295
3296 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3297 @Override
3298 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003299 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003300 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003301 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 }
3303
3304 /** Unregister a task stack listener so that it stops receiving callbacks. */
3305 @Override
3306 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003307 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003309 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 }
3311
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 @Override
3313 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3314 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3315 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3316 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3317 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3318 }
3319
3320 @Override
3321 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3322 IBinder activityToken, int flags) {
3323 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3324 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3325 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3326 }
3327
3328 @Override
3329 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3330 Bundle args) {
3331 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3332 true /* focused */, true /* newSessionId */, userHandle, args,
3333 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3334 }
3335
3336 @Override
3337 public Bundle getAssistContextExtras(int requestType) {
3338 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3339 null, null, true /* focused */, true /* newSessionId */,
3340 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3341 if (pae == null) {
3342 return null;
3343 }
3344 synchronized (pae) {
3345 while (!pae.haveResult) {
3346 try {
3347 pae.wait();
3348 } catch (InterruptedException e) {
3349 }
3350 }
3351 }
3352 synchronized (mGlobalLock) {
3353 buildAssistBundleLocked(pae, pae.result);
3354 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003355 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 }
3357 return pae.extras;
3358 }
3359
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003360 /**
3361 * Binder IPC calls go through the public entry point.
3362 * This can be called with or without the global lock held.
3363 */
3364 private static int checkCallingPermission(String permission) {
3365 return checkPermission(
3366 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3367 }
3368
3369 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003370 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003371 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3372 mAmInternal.enforceCallingPermission(permission, func);
3373 }
3374 }
3375
3376 @VisibleForTesting
3377 int checkGetTasksPermission(String permission, int pid, int uid) {
3378 return checkPermission(permission, pid, uid);
3379 }
3380
3381 static int checkPermission(String permission, int pid, int uid) {
3382 if (permission == null) {
3383 return PackageManager.PERMISSION_DENIED;
3384 }
3385 return checkComponentPermission(permission, pid, uid, -1, true);
3386 }
3387
Wale Ogunwale214f3482018-10-04 11:00:47 -07003388 public static int checkComponentPermission(String permission, int pid, int uid,
3389 int owningUid, boolean exported) {
3390 return ActivityManagerService.checkComponentPermission(
3391 permission, pid, uid, owningUid, exported);
3392 }
3393
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003394 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3395 if (getRecentTasks().isCallerRecents(callingUid)) {
3396 // Always allow the recents component to get tasks
3397 return true;
3398 }
3399
3400 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3401 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3402 if (!allowed) {
3403 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3404 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3405 // Temporary compatibility: some existing apps on the system image may
3406 // still be requesting the old permission and not switched to the new
3407 // one; if so, we'll still allow them full access. This means we need
3408 // to see if they are holding the old permission and are a system app.
3409 try {
3410 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3411 allowed = true;
3412 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3413 + " is using old GET_TASKS but privileged; allowing");
3414 }
3415 } catch (RemoteException e) {
3416 }
3417 }
3418 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3419 + " does not hold REAL_GET_TASKS; limiting output");
3420 }
3421 return allowed;
3422 }
3423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3425 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3426 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3427 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003428 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 "enqueueAssistContext()");
3430
3431 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003432 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 if (activity == null) {
3434 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3435 return null;
3436 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003437 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3439 return null;
3440 }
3441 if (focused) {
3442 if (activityToken != null) {
3443 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3444 if (activity != caller) {
3445 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3446 + " is not current top " + activity);
3447 return null;
3448 }
3449 }
3450 } else {
3451 activity = ActivityRecord.forTokenLocked(activityToken);
3452 if (activity == null) {
3453 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3454 + " couldn't be found");
3455 return null;
3456 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003457 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3459 return null;
3460 }
3461 }
3462
3463 PendingAssistExtras pae;
3464 Bundle extras = new Bundle();
3465 if (args != null) {
3466 extras.putAll(args);
3467 }
3468 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003469 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470
3471 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3472 userHandle);
3473 pae.isHome = activity.isActivityTypeHome();
3474
3475 // Increment the sessionId if necessary
3476 if (newSessionId) {
3477 mViSessionId++;
3478 }
3479 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003480 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3481 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003483 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 } catch (RemoteException e) {
3485 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3486 return null;
3487 }
3488 return pae;
3489 }
3490 }
3491
3492 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3493 if (result != null) {
3494 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3495 }
3496 if (pae.hint != null) {
3497 pae.extras.putBoolean(pae.hint, true);
3498 }
3499 }
3500
3501 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3502 IAssistDataReceiver receiver;
3503 synchronized (mGlobalLock) {
3504 mPendingAssistExtras.remove(pae);
3505 receiver = pae.receiver;
3506 }
3507 if (receiver != null) {
3508 // Caller wants result sent back to them.
3509 Bundle sendBundle = new Bundle();
3510 // At least return the receiver extras
3511 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3512 try {
3513 pae.receiver.onHandleAssistData(sendBundle);
3514 } catch (RemoteException e) {
3515 }
3516 }
3517 }
3518
3519 public class PendingAssistExtras extends Binder implements Runnable {
3520 public final ActivityRecord activity;
3521 public boolean isHome;
3522 public final Bundle extras;
3523 public final Intent intent;
3524 public final String hint;
3525 public final IAssistDataReceiver receiver;
3526 public final int userHandle;
3527 public boolean haveResult = false;
3528 public Bundle result = null;
3529 public AssistStructure structure = null;
3530 public AssistContent content = null;
3531 public Bundle receiverExtras;
3532
3533 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3534 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3535 int _userHandle) {
3536 activity = _activity;
3537 extras = _extras;
3538 intent = _intent;
3539 hint = _hint;
3540 receiver = _receiver;
3541 receiverExtras = _receiverExtras;
3542 userHandle = _userHandle;
3543 }
3544
3545 @Override
3546 public void run() {
3547 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3548 synchronized (this) {
3549 haveResult = true;
3550 notifyAll();
3551 }
3552 pendingAssistExtrasTimedOut(this);
3553 }
3554 }
3555
3556 @Override
3557 public boolean isAssistDataAllowedOnCurrentActivity() {
3558 int userId;
3559 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003560 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003561 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3562 return false;
3563 }
3564
3565 final ActivityRecord activity = focusedStack.getTopActivity();
3566 if (activity == null) {
3567 return false;
3568 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003569 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003570 }
3571 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3572 }
3573
3574 @Override
3575 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3576 long ident = Binder.clearCallingIdentity();
3577 try {
3578 synchronized (mGlobalLock) {
3579 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003580 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003581 if (top != caller) {
3582 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3583 + " is not current top " + top);
3584 return false;
3585 }
3586 if (!top.nowVisible) {
3587 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3588 + " is not visible");
3589 return false;
3590 }
3591 }
3592 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3593 token);
3594 } finally {
3595 Binder.restoreCallingIdentity(ident);
3596 }
3597 }
3598
3599 @Override
3600 public boolean isRootVoiceInteraction(IBinder token) {
3601 synchronized (mGlobalLock) {
3602 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3603 if (r == null) {
3604 return false;
3605 }
3606 return r.rootVoiceInteraction;
3607 }
3608 }
3609
Wale Ogunwalef6733932018-06-27 05:14:34 -07003610 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3611 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3612 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3613 if (activityToCallback == null) return;
3614 activityToCallback.setVoiceSessionLocked(voiceSession);
3615
3616 // Inform the activity
3617 try {
3618 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3619 voiceInteractor);
3620 long token = Binder.clearCallingIdentity();
3621 try {
3622 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3623 } finally {
3624 Binder.restoreCallingIdentity(token);
3625 }
3626 // TODO: VI Should we cache the activity so that it's easier to find later
3627 // rather than scan through all the stacks and activities?
3628 } catch (RemoteException re) {
3629 activityToCallback.clearVoiceSessionLocked();
3630 // TODO: VI Should this terminate the voice session?
3631 }
3632 }
3633
3634 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3635 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3636 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3637 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3638 boolean wasRunningVoice = mRunningVoice != null;
3639 mRunningVoice = session;
3640 if (!wasRunningVoice) {
3641 mVoiceWakeLock.acquire();
3642 updateSleepIfNeededLocked();
3643 }
3644 }
3645 }
3646
3647 void finishRunningVoiceLocked() {
3648 if (mRunningVoice != null) {
3649 mRunningVoice = null;
3650 mVoiceWakeLock.release();
3651 updateSleepIfNeededLocked();
3652 }
3653 }
3654
3655 @Override
3656 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3657 synchronized (mGlobalLock) {
3658 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3659 if (keepAwake) {
3660 mVoiceWakeLock.acquire();
3661 } else {
3662 mVoiceWakeLock.release();
3663 }
3664 }
3665 }
3666 }
3667
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 @Override
3669 public ComponentName getActivityClassForToken(IBinder token) {
3670 synchronized (mGlobalLock) {
3671 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3672 if (r == null) {
3673 return null;
3674 }
3675 return r.intent.getComponent();
3676 }
3677 }
3678
3679 @Override
3680 public String getPackageForToken(IBinder token) {
3681 synchronized (mGlobalLock) {
3682 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3683 if (r == null) {
3684 return null;
3685 }
3686 return r.packageName;
3687 }
3688 }
3689
3690 @Override
3691 public void showLockTaskEscapeMessage(IBinder token) {
3692 synchronized (mGlobalLock) {
3693 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3694 if (r == null) {
3695 return;
3696 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003697 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003698 }
3699 }
3700
3701 @Override
3702 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003703 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003704 final long token = Binder.clearCallingIdentity();
3705 try {
3706 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003707 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 }
3709 } finally {
3710 Binder.restoreCallingIdentity(token);
3711 }
3712 }
3713
3714 /**
3715 * Try to place task to provided position. The final position might be different depending on
3716 * current user and stacks state. The task will be moved to target stack if it's currently in
3717 * different stack.
3718 */
3719 @Override
3720 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003721 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003722 synchronized (mGlobalLock) {
3723 long ident = Binder.clearCallingIdentity();
3724 try {
3725 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3726 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003727 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003728 if (task == null) {
3729 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3730 + taskId);
3731 }
3732
Wale Ogunwaled32da472018-11-16 07:19:28 -08003733 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003734
3735 if (stack == null) {
3736 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3737 + stackId);
3738 }
3739 if (!stack.isActivityTypeStandardOrUndefined()) {
3740 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3741 + " the position of task " + taskId + " in/to non-standard stack");
3742 }
3743
3744 // TODO: Have the callers of this API call a separate reparent method if that is
3745 // what they intended to do vs. having this method also do reparenting.
3746 if (task.getStack() == stack) {
3747 // Change position in current stack.
3748 stack.positionChildAt(task, position);
3749 } else {
3750 // Reparent to new stack.
3751 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3752 !DEFER_RESUME, "positionTaskInStack");
3753 }
3754 } finally {
3755 Binder.restoreCallingIdentity(ident);
3756 }
3757 }
3758 }
3759
3760 @Override
3761 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3762 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3763 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3764 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3765 synchronized (mGlobalLock) {
3766 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3767 if (record == null) {
3768 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3769 + "found for: " + token);
3770 }
3771 record.setSizeConfigurations(horizontalSizeConfiguration,
3772 verticalSizeConfigurations, smallestSizeConfigurations);
3773 }
3774 }
3775
3776 /**
3777 * Dismisses split-screen multi-window mode.
3778 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3779 */
3780 @Override
3781 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003782 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003783 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3784 final long ident = Binder.clearCallingIdentity();
3785 try {
3786 synchronized (mGlobalLock) {
3787 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003788 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003789 if (stack == null) {
3790 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3791 return;
3792 }
3793
3794 if (toTop) {
3795 // Caller wants the current split-screen primary stack to be the top stack after
3796 // it goes fullscreen, so move it to the front.
3797 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003798 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003799 // In this case the current split-screen primary stack shouldn't be the top
3800 // stack after it goes fullscreen, but it current has focus, so we move the
3801 // focus to the top-most split-screen secondary stack next to it.
3802 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3803 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3804 if (otherStack != null) {
3805 otherStack.moveToFront("dismissSplitScreenMode_other");
3806 }
3807 }
3808
Evan Rosky10475742018-09-05 19:02:48 -07003809 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 }
3811 } finally {
3812 Binder.restoreCallingIdentity(ident);
3813 }
3814 }
3815
3816 /**
3817 * Dismisses Pip
3818 * @param animate True if the dismissal should be animated.
3819 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3820 * default animation duration should be used.
3821 */
3822 @Override
3823 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003824 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003825 final long ident = Binder.clearCallingIdentity();
3826 try {
3827 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003828 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003829 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003830 if (stack == null) {
3831 Slog.w(TAG, "dismissPip: pinned stack not found.");
3832 return;
3833 }
3834 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3835 throw new IllegalArgumentException("Stack: " + stack
3836 + " doesn't support animated resize.");
3837 }
3838 if (animate) {
3839 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3840 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3841 } else {
3842 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3843 }
3844 }
3845 } finally {
3846 Binder.restoreCallingIdentity(ident);
3847 }
3848 }
3849
3850 @Override
3851 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003852 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003853 synchronized (mGlobalLock) {
3854 mSuppressResizeConfigChanges = suppress;
3855 }
3856 }
3857
3858 /**
3859 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3860 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3861 * activity and clearing the task at the same time.
3862 */
3863 @Override
3864 // TODO: API should just be about changing windowing modes...
3865 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003866 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003867 "moveTasksToFullscreenStack()");
3868 synchronized (mGlobalLock) {
3869 final long origId = Binder.clearCallingIdentity();
3870 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003871 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 if (stack != null){
3873 if (!stack.isActivityTypeStandardOrUndefined()) {
3874 throw new IllegalArgumentException(
3875 "You can't move tasks from non-standard stacks.");
3876 }
3877 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3878 }
3879 } finally {
3880 Binder.restoreCallingIdentity(origId);
3881 }
3882 }
3883 }
3884
3885 /**
3886 * Moves the top activity in the input stackId to the pinned stack.
3887 *
3888 * @param stackId Id of stack to move the top activity to pinned stack.
3889 * @param bounds Bounds to use for pinned stack.
3890 *
3891 * @return True if the top activity of the input stack was successfully moved to the pinned
3892 * stack.
3893 */
3894 @Override
3895 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003896 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003897 "moveTopActivityToPinnedStack()");
3898 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003899 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3901 + "Device doesn't support picture-in-picture mode");
3902 }
3903
3904 long ident = Binder.clearCallingIdentity();
3905 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003906 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003907 } finally {
3908 Binder.restoreCallingIdentity(ident);
3909 }
3910 }
3911 }
3912
3913 @Override
3914 public boolean isInMultiWindowMode(IBinder token) {
3915 final long origId = Binder.clearCallingIdentity();
3916 try {
3917 synchronized (mGlobalLock) {
3918 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3919 if (r == null) {
3920 return false;
3921 }
3922 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3923 return r.inMultiWindowMode();
3924 }
3925 } finally {
3926 Binder.restoreCallingIdentity(origId);
3927 }
3928 }
3929
3930 @Override
3931 public boolean isInPictureInPictureMode(IBinder token) {
3932 final long origId = Binder.clearCallingIdentity();
3933 try {
3934 synchronized (mGlobalLock) {
3935 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3936 }
3937 } finally {
3938 Binder.restoreCallingIdentity(origId);
3939 }
3940 }
3941
3942 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003943 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3944 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 return false;
3946 }
3947
3948 // If we are animating to fullscreen then we have already dispatched the PIP mode
3949 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003950 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3951 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 }
3953
3954 @Override
3955 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3956 final long origId = Binder.clearCallingIdentity();
3957 try {
3958 synchronized (mGlobalLock) {
3959 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3960 "enterPictureInPictureMode", token, params);
3961
3962 // If the activity is already in picture in picture mode, then just return early
3963 if (isInPictureInPictureMode(r)) {
3964 return true;
3965 }
3966
3967 // Activity supports picture-in-picture, now check that we can enter PiP at this
3968 // point, if it is
3969 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3970 false /* beforeStopping */)) {
3971 return false;
3972 }
3973
3974 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003975 synchronized (mGlobalLock) {
3976 // Only update the saved args from the args that are set
3977 r.pictureInPictureArgs.copyOnlySet(params);
3978 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3979 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3980 // Adjust the source bounds by the insets for the transition down
3981 final Rect sourceBounds = new Rect(
3982 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003983 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003984 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003985 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003986 stack.setPictureInPictureAspectRatio(aspectRatio);
3987 stack.setPictureInPictureActions(actions);
3988 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3989 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3990 logPictureInPictureArgs(params);
3991 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 };
3993
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003994 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 // If the keyguard is showing or occluded, then try and dismiss it before
3996 // entering picture-in-picture (this will prompt the user to authenticate if the
3997 // device is currently locked).
3998 dismissKeyguard(token, new KeyguardDismissCallback() {
3999 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 public void onDismissSucceeded() {
4001 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 }
4003 }, null /* message */);
4004 } else {
4005 // Enter picture in picture immediately otherwise
4006 enterPipRunnable.run();
4007 }
4008 return true;
4009 }
4010 } finally {
4011 Binder.restoreCallingIdentity(origId);
4012 }
4013 }
4014
4015 @Override
4016 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4017 final long origId = Binder.clearCallingIdentity();
4018 try {
4019 synchronized (mGlobalLock) {
4020 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4021 "setPictureInPictureParams", token, params);
4022
4023 // Only update the saved args from the args that are set
4024 r.pictureInPictureArgs.copyOnlySet(params);
4025 if (r.inPinnedWindowingMode()) {
4026 // If the activity is already in picture-in-picture, update the pinned stack now
4027 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4028 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004029 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004030 if (!stack.isAnimatingBoundsToFullscreen()) {
4031 stack.setPictureInPictureAspectRatio(
4032 r.pictureInPictureArgs.getAspectRatio());
4033 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4034 }
4035 }
4036 logPictureInPictureArgs(params);
4037 }
4038 } finally {
4039 Binder.restoreCallingIdentity(origId);
4040 }
4041 }
4042
4043 @Override
4044 public int getMaxNumPictureInPictureActions(IBinder token) {
4045 // Currently, this is a static constant, but later, we may change this to be dependent on
4046 // the context of the activity
4047 return 3;
4048 }
4049
4050 private void logPictureInPictureArgs(PictureInPictureParams params) {
4051 if (params.hasSetActions()) {
4052 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4053 params.getActions().size());
4054 }
4055 if (params.hasSetAspectRatio()) {
4056 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4057 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4058 MetricsLogger.action(lm);
4059 }
4060 }
4061
4062 /**
4063 * Checks the state of the system and the activity associated with the given {@param token} to
4064 * verify that picture-in-picture is supported for that activity.
4065 *
4066 * @return the activity record for the given {@param token} if all the checks pass.
4067 */
4068 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4069 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004070 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 throw new IllegalStateException(caller
4072 + ": Device doesn't support picture-in-picture mode.");
4073 }
4074
4075 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4076 if (r == null) {
4077 throw new IllegalStateException(caller
4078 + ": Can't find activity for token=" + token);
4079 }
4080
4081 if (!r.supportsPictureInPicture()) {
4082 throw new IllegalStateException(caller
4083 + ": Current activity does not support picture-in-picture.");
4084 }
4085
4086 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004087 && !mWindowManager.isValidPictureInPictureAspectRatio(
4088 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004089 final float minAspectRatio = mContext.getResources().getFloat(
4090 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4091 final float maxAspectRatio = mContext.getResources().getFloat(
4092 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4093 throw new IllegalArgumentException(String.format(caller
4094 + ": Aspect ratio is too extreme (must be between %f and %f).",
4095 minAspectRatio, maxAspectRatio));
4096 }
4097
4098 // Truncate the number of actions if necessary
4099 params.truncateActions(getMaxNumPictureInPictureActions(token));
4100
4101 return r;
4102 }
4103
4104 @Override
4105 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004106 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107 synchronized (mGlobalLock) {
4108 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4109 if (r == null) {
4110 throw new IllegalArgumentException("Activity does not exist; token="
4111 + activityToken);
4112 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004113 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004114 }
4115 }
4116
4117 @Override
4118 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4119 Rect tempDockedTaskInsetBounds,
4120 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004121 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 long ident = Binder.clearCallingIdentity();
4123 try {
4124 synchronized (mGlobalLock) {
4125 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4126 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4127 PRESERVE_WINDOWS);
4128 }
4129 } finally {
4130 Binder.restoreCallingIdentity(ident);
4131 }
4132 }
4133
4134 @Override
4135 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004136 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004137 final long ident = Binder.clearCallingIdentity();
4138 try {
4139 synchronized (mGlobalLock) {
4140 mStackSupervisor.setSplitScreenResizing(resizing);
4141 }
4142 } finally {
4143 Binder.restoreCallingIdentity(ident);
4144 }
4145 }
4146
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 /**
4148 * Check that we have the features required for VR-related API calls, and throw an exception if
4149 * not.
4150 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004151 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004152 if (!mContext.getPackageManager().hasSystemFeature(
4153 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4154 throw new UnsupportedOperationException("VR mode not supported on this device!");
4155 }
4156 }
4157
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 @Override
4159 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004160 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004161
4162 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4163
4164 ActivityRecord r;
4165 synchronized (mGlobalLock) {
4166 r = ActivityRecord.isInStackLocked(token);
4167 }
4168
4169 if (r == null) {
4170 throw new IllegalArgumentException();
4171 }
4172
4173 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004174 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004175 VrManagerInternal.NO_ERROR) {
4176 return err;
4177 }
4178
4179 // Clear the binder calling uid since this path may call moveToTask().
4180 final long callingId = Binder.clearCallingIdentity();
4181 try {
4182 synchronized (mGlobalLock) {
4183 r.requestedVrComponent = (enabled) ? packageName : null;
4184
4185 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004186 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004187 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188 }
4189 return 0;
4190 }
4191 } finally {
4192 Binder.restoreCallingIdentity(callingId);
4193 }
4194 }
4195
4196 @Override
4197 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4198 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4199 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004200 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4202 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4203 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004204 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 || activity.voiceSession != null) {
4206 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4207 return;
4208 }
4209 if (activity.pendingVoiceInteractionStart) {
4210 Slog.w(TAG, "Pending start of voice interaction already.");
4211 return;
4212 }
4213 activity.pendingVoiceInteractionStart = true;
4214 }
4215 LocalServices.getService(VoiceInteractionManagerInternal.class)
4216 .startLocalVoiceInteraction(callingActivity, options);
4217 }
4218
4219 @Override
4220 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4221 LocalServices.getService(VoiceInteractionManagerInternal.class)
4222 .stopLocalVoiceInteraction(callingActivity);
4223 }
4224
4225 @Override
4226 public boolean supportsLocalVoiceInteraction() {
4227 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4228 .supportsLocalVoiceInteraction();
4229 }
4230
4231 /** Notifies all listeners when the pinned stack animation starts. */
4232 @Override
4233 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004234 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004235 }
4236
4237 /** Notifies all listeners when the pinned stack animation ends. */
4238 @Override
4239 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004240 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 }
4242
4243 @Override
4244 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004245 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 final long ident = Binder.clearCallingIdentity();
4247 try {
4248 synchronized (mGlobalLock) {
4249 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4250 }
4251 } finally {
4252 Binder.restoreCallingIdentity(ident);
4253 }
4254 }
4255
4256 @Override
4257 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004258 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259
4260 synchronized (mGlobalLock) {
4261 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004262 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 // Call might come when display is not yet added or has already been removed.
4264 if (DEBUG_CONFIGURATION) {
4265 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4266 + displayId);
4267 }
4268 return false;
4269 }
4270
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 }
4275
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004277 final Message msg = PooledLambda.obtainMessage(
4278 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4279 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004280 }
4281
4282 final long origId = Binder.clearCallingIdentity();
4283 try {
4284 if (values != null) {
4285 Settings.System.clearConfiguration(values);
4286 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4289 return mTmpUpdateConfigurationResult.changes != 0;
4290 } finally {
4291 Binder.restoreCallingIdentity(origId);
4292 }
4293 }
4294 }
4295
4296 @Override
4297 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004298 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299
4300 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004301 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004303 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 }
4305
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004307 final Message msg = PooledLambda.obtainMessage(
4308 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4309 DEFAULT_DISPLAY);
4310 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 }
4312
4313 final long origId = Binder.clearCallingIdentity();
4314 try {
4315 if (values != null) {
4316 Settings.System.clearConfiguration(values);
4317 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004318 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 UserHandle.USER_NULL, false /* deferResume */,
4320 mTmpUpdateConfigurationResult);
4321 return mTmpUpdateConfigurationResult.changes != 0;
4322 } finally {
4323 Binder.restoreCallingIdentity(origId);
4324 }
4325 }
4326 }
4327
4328 @Override
4329 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4330 CharSequence message) {
4331 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4334 }
4335 final long callingId = Binder.clearCallingIdentity();
4336 try {
4337 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004338 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 }
4340 } finally {
4341 Binder.restoreCallingIdentity(callingId);
4342 }
4343 }
4344
4345 @Override
4346 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 "cancelTaskWindowTransition()");
4349 final long ident = Binder.clearCallingIdentity();
4350 try {
4351 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004352 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004353 MATCH_TASK_IN_STACKS_ONLY);
4354 if (task == null) {
4355 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4356 return;
4357 }
4358 task.cancelWindowTransition();
4359 }
4360 } finally {
4361 Binder.restoreCallingIdentity(ident);
4362 }
4363 }
4364
4365 @Override
4366 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004367 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 final long ident = Binder.clearCallingIdentity();
4369 try {
4370 final TaskRecord task;
4371 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004372 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4374 if (task == null) {
4375 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4376 return null;
4377 }
4378 }
4379 // Don't call this while holding the lock as this operation might hit the disk.
4380 return task.getSnapshot(reducedResolution);
4381 } finally {
4382 Binder.restoreCallingIdentity(ident);
4383 }
4384 }
4385
4386 @Override
4387 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4388 synchronized (mGlobalLock) {
4389 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4390 if (r == null) {
4391 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4392 + token);
4393 return;
4394 }
4395 final long origId = Binder.clearCallingIdentity();
4396 try {
4397 r.setDisablePreviewScreenshots(disable);
4398 } finally {
4399 Binder.restoreCallingIdentity(origId);
4400 }
4401 }
4402 }
4403
4404 /** Return the user id of the last resumed activity. */
4405 @Override
4406 public @UserIdInt
4407 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004408 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4410 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004411 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004414 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 }
4416 }
4417
4418 @Override
4419 public void updateLockTaskFeatures(int userId, int flags) {
4420 final int callingUid = Binder.getCallingUid();
4421 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004422 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 "updateLockTaskFeatures()");
4424 }
4425 synchronized (mGlobalLock) {
4426 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4427 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004428 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 }
4430 }
4431
4432 @Override
4433 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4434 synchronized (mGlobalLock) {
4435 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4436 if (r == null) {
4437 return;
4438 }
4439 final long origId = Binder.clearCallingIdentity();
4440 try {
4441 r.setShowWhenLocked(showWhenLocked);
4442 } finally {
4443 Binder.restoreCallingIdentity(origId);
4444 }
4445 }
4446 }
4447
4448 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004449 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4450 synchronized (mGlobalLock) {
4451 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4452 if (r == null) {
4453 return;
4454 }
4455 final long origId = Binder.clearCallingIdentity();
4456 try {
4457 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4458 } finally {
4459 Binder.restoreCallingIdentity(origId);
4460 }
4461 }
4462 }
4463
4464 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4466 synchronized (mGlobalLock) {
4467 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4468 if (r == null) {
4469 return;
4470 }
4471 final long origId = Binder.clearCallingIdentity();
4472 try {
4473 r.setTurnScreenOn(turnScreenOn);
4474 } finally {
4475 Binder.restoreCallingIdentity(origId);
4476 }
4477 }
4478 }
4479
4480 @Override
4481 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004482 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 "registerRemoteAnimations");
4484 definition.setCallingPid(Binder.getCallingPid());
4485 synchronized (mGlobalLock) {
4486 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4487 if (r == null) {
4488 return;
4489 }
4490 final long origId = Binder.clearCallingIdentity();
4491 try {
4492 r.registerRemoteAnimations(definition);
4493 } finally {
4494 Binder.restoreCallingIdentity(origId);
4495 }
4496 }
4497 }
4498
4499 @Override
4500 public void registerRemoteAnimationForNextActivityStart(String packageName,
4501 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004502 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 "registerRemoteAnimationForNextActivityStart");
4504 adapter.setCallingPid(Binder.getCallingPid());
4505 synchronized (mGlobalLock) {
4506 final long origId = Binder.clearCallingIdentity();
4507 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004508 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 packageName, adapter);
4510 } finally {
4511 Binder.restoreCallingIdentity(origId);
4512 }
4513 }
4514 }
4515
Evan Rosky966759f2019-01-15 10:33:58 -08004516 @Override
4517 public void registerRemoteAnimationsForDisplay(int displayId,
4518 RemoteAnimationDefinition definition) {
4519 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4520 "registerRemoteAnimations");
4521 definition.setCallingPid(Binder.getCallingPid());
4522 synchronized (mGlobalLock) {
4523 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4524 if (display == null) {
4525 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4526 return;
4527 }
4528 final long origId = Binder.clearCallingIdentity();
4529 try {
4530 display.mDisplayContent.registerRemoteAnimations(definition);
4531 } finally {
4532 Binder.restoreCallingIdentity(origId);
4533 }
4534 }
4535 }
4536
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004537 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4538 @Override
4539 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4540 synchronized (mGlobalLock) {
4541 final long origId = Binder.clearCallingIdentity();
4542 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004543 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004544 } finally {
4545 Binder.restoreCallingIdentity(origId);
4546 }
4547 }
4548 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004549
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004550 @Override
4551 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004552 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004553 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004554 final int pid = Binder.getCallingPid();
4555 final WindowProcessController wpc = mPidMap.get(pid);
4556 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004557 }
4558 }
4559
4560 @Override
4561 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004562 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004563 != PERMISSION_GRANTED) {
4564 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4565 + Binder.getCallingPid()
4566 + ", uid=" + Binder.getCallingUid()
4567 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4568 Slog.w(TAG, msg);
4569 throw new SecurityException(msg);
4570 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004571 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004572 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004573 final int pid = Binder.getCallingPid();
4574 final WindowProcessController proc = mPidMap.get(pid);
4575 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004576 }
4577 }
4578
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004579 @Override
4580 public void stopAppSwitches() {
4581 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4582 synchronized (mGlobalLock) {
4583 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4584 mDidAppSwitch = false;
4585 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4586 }
4587 }
4588
4589 @Override
4590 public void resumeAppSwitches() {
4591 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4592 synchronized (mGlobalLock) {
4593 // Note that we don't execute any pending app switches... we will
4594 // let those wait until either the timeout, or the next start
4595 // activity request.
4596 mAppSwitchesAllowedTime = 0;
4597 }
4598 }
4599
4600 void onStartActivitySetDidAppSwitch() {
4601 if (mDidAppSwitch) {
4602 // This is the second allowed switch since we stopped switches, so now just generally
4603 // allow switches. Use case:
4604 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4605 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4606 // anyone to switch again).
4607 mAppSwitchesAllowedTime = 0;
4608 } else {
4609 mDidAppSwitch = true;
4610 }
4611 }
4612
4613 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004614 boolean shouldDisableNonVrUiLocked() {
4615 return mVrController.shouldDisableNonVrUiLocked();
4616 }
4617
Wale Ogunwale53783742018-09-16 10:21:51 -07004618 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004619 // VR apps are expected to run in a main display. If an app is turning on VR for
4620 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4621 // fullscreen stack before enabling VR Mode.
4622 // TODO: The goal of this code is to keep the VR app on the main display. When the
4623 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4624 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4625 // option would be a better choice here.
4626 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4627 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4628 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004629 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004630 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004631 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004632 }
4633 mH.post(() -> {
4634 if (!mVrController.onVrModeChanged(r)) {
4635 return;
4636 }
4637 synchronized (mGlobalLock) {
4638 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4639 mWindowManager.disableNonVrUi(disableNonVrUi);
4640 if (disableNonVrUi) {
4641 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4642 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004643 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004644 }
4645 }
4646 });
4647 }
4648
Wale Ogunwale53783742018-09-16 10:21:51 -07004649 @Override
4650 public int getPackageScreenCompatMode(String packageName) {
4651 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4652 synchronized (mGlobalLock) {
4653 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4654 }
4655 }
4656
4657 @Override
4658 public void setPackageScreenCompatMode(String packageName, int mode) {
4659 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4660 "setPackageScreenCompatMode");
4661 synchronized (mGlobalLock) {
4662 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4663 }
4664 }
4665
4666 @Override
4667 public boolean getPackageAskScreenCompat(String packageName) {
4668 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4669 synchronized (mGlobalLock) {
4670 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4671 }
4672 }
4673
4674 @Override
4675 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4676 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4677 "setPackageAskScreenCompat");
4678 synchronized (mGlobalLock) {
4679 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4680 }
4681 }
4682
Wale Ogunwale64258362018-10-16 15:13:37 -07004683 public static String relaunchReasonToString(int relaunchReason) {
4684 switch (relaunchReason) {
4685 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4686 return "window_resize";
4687 case RELAUNCH_REASON_FREE_RESIZE:
4688 return "free_resize";
4689 default:
4690 return null;
4691 }
4692 }
4693
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004694 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004695 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 }
4697
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 /** Pokes the task persister. */
4699 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4700 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4701 }
4702
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004703 boolean isKeyguardLocked() {
4704 return mKeyguardController.isKeyguardLocked();
4705 }
4706
Garfield Tan01548632018-11-27 10:15:48 -08004707 /**
4708 * Clears launch params for the given package.
4709 * @param packageNames the names of the packages of which the launch params are to be cleared
4710 */
4711 @Override
4712 public void clearLaunchParamsForPackages(List<String> packageNames) {
4713 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4714 "clearLaunchParamsForPackages");
4715 synchronized (mGlobalLock) {
4716 for (int i = 0; i < packageNames.size(); ++i) {
4717 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4718 }
4719 }
4720 }
4721
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004722 /**
4723 * Makes the display with the given id a single task instance display. I.e the display can only
4724 * contain one task.
4725 */
4726 @Override
4727 public void setDisplayToSingleTaskInstance(int displayId) {
4728 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4729 "setDisplayToSingleTaskInstance");
4730 final long origId = Binder.clearCallingIdentity();
4731 try {
4732 final ActivityDisplay display =
4733 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4734 if (display != null) {
4735 display.setDisplayToSingleTaskInstance();
4736 }
4737 } finally {
4738 Binder.restoreCallingIdentity(origId);
4739 }
4740 }
4741
Wale Ogunwale31913b52018-10-13 08:29:31 -07004742 void dumpLastANRLocked(PrintWriter pw) {
4743 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4744 if (mLastANRState == null) {
4745 pw.println(" <no ANR has occurred since boot>");
4746 } else {
4747 pw.println(mLastANRState);
4748 }
4749 }
4750
4751 void dumpLastANRTracesLocked(PrintWriter pw) {
4752 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4753
4754 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4755 if (ArrayUtils.isEmpty(files)) {
4756 pw.println(" <no ANR has occurred since boot>");
4757 return;
4758 }
4759 // Find the latest file.
4760 File latest = null;
4761 for (File f : files) {
4762 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4763 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004764 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004765 }
4766 pw.print("File: ");
4767 pw.print(latest.getName());
4768 pw.println();
4769 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4770 String line;
4771 while ((line = in.readLine()) != null) {
4772 pw.println(line);
4773 }
4774 } catch (IOException e) {
4775 pw.print("Unable to read: ");
4776 pw.print(e);
4777 pw.println();
4778 }
4779 }
4780
4781 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4782 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4783 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4784 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4785 }
4786
4787 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4788 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4789 pw.println(header);
4790
Wale Ogunwaled32da472018-11-16 07:19:28 -08004791 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004792 dumpPackage);
4793 boolean needSep = printedAnything;
4794
4795 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004796 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004797 " ResumedActivity: ");
4798 if (printed) {
4799 printedAnything = true;
4800 needSep = false;
4801 }
4802
4803 if (dumpPackage == null) {
4804 if (needSep) {
4805 pw.println();
4806 }
4807 printedAnything = true;
4808 mStackSupervisor.dump(pw, " ");
4809 }
4810
4811 if (!printedAnything) {
4812 pw.println(" (nothing)");
4813 }
4814 }
4815
4816 void dumpActivityContainersLocked(PrintWriter pw) {
4817 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004818 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004819 pw.println(" ");
4820 }
4821
4822 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4823 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4824 getActivityStartController().dump(pw, "", dumpPackage);
4825 }
4826
4827 /**
4828 * There are three things that cmd can be:
4829 * - a flattened component name that matches an existing activity
4830 * - the cmd arg isn't the flattened component name of an existing activity:
4831 * dump all activity whose component contains the cmd as a substring
4832 * - A hex number of the ActivityRecord object instance.
4833 *
4834 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4835 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4836 */
4837 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4838 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4839 ArrayList<ActivityRecord> activities;
4840
4841 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004842 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004843 dumpFocusedStackOnly);
4844 }
4845
4846 if (activities.size() <= 0) {
4847 return false;
4848 }
4849
4850 String[] newArgs = new String[args.length - opti];
4851 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4852
4853 TaskRecord lastTask = null;
4854 boolean needSep = false;
4855 for (int i = activities.size() - 1; i >= 0; i--) {
4856 ActivityRecord r = activities.get(i);
4857 if (needSep) {
4858 pw.println();
4859 }
4860 needSep = true;
4861 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004862 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004863 if (lastTask != task) {
4864 lastTask = task;
4865 pw.print("TASK "); pw.print(lastTask.affinity);
4866 pw.print(" id="); pw.print(lastTask.taskId);
4867 pw.print(" userId="); pw.println(lastTask.userId);
4868 if (dumpAll) {
4869 lastTask.dump(pw, " ");
4870 }
4871 }
4872 }
4873 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4874 }
4875 return true;
4876 }
4877
4878 /**
4879 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4880 * there is a thread associated with the activity.
4881 */
4882 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4883 final ActivityRecord r, String[] args, boolean dumpAll) {
4884 String innerPrefix = prefix + " ";
4885 synchronized (mGlobalLock) {
4886 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4887 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4888 pw.print(" pid=");
4889 if (r.hasProcess()) pw.println(r.app.getPid());
4890 else pw.println("(not running)");
4891 if (dumpAll) {
4892 r.dump(pw, innerPrefix);
4893 }
4894 }
4895 if (r.attachedToProcess()) {
4896 // flush anything that is already in the PrintWriter since the thread is going
4897 // to write to the file descriptor directly
4898 pw.flush();
4899 try {
4900 TransferPipe tp = new TransferPipe();
4901 try {
4902 r.app.getThread().dumpActivity(tp.getWriteFd(),
4903 r.appToken, innerPrefix, args);
4904 tp.go(fd);
4905 } finally {
4906 tp.kill();
4907 }
4908 } catch (IOException e) {
4909 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4910 } catch (RemoteException e) {
4911 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4912 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004913 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004914 }
4915
sanryhuang498e77e2018-12-06 14:57:01 +08004916 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4917 boolean testPssMode) {
4918 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4919 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4920 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004921 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004922 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4923 st.toString());
4924 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004925 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4926 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4927 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004928 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4929 testPssMode);
4930 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004931 }
4932
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004933 int getCurrentUserId() {
4934 return mAmInternal.getCurrentUserId();
4935 }
4936
4937 private void enforceNotIsolatedCaller(String caller) {
4938 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4939 throw new SecurityException("Isolated process not allowed to call " + caller);
4940 }
4941 }
4942
Wale Ogunwalef6733932018-06-27 05:14:34 -07004943 public Configuration getConfiguration() {
4944 Configuration ci;
4945 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004946 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004947 ci.userSetLocale = false;
4948 }
4949 return ci;
4950 }
4951
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004952 /**
4953 * Current global configuration information. Contains general settings for the entire system,
4954 * also corresponds to the merged configuration of the default display.
4955 */
4956 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004957 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004958 }
4959
4960 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4961 boolean initLocale) {
4962 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4963 }
4964
4965 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4966 boolean initLocale, boolean deferResume) {
4967 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4968 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4969 UserHandle.USER_NULL, deferResume);
4970 }
4971
Wale Ogunwale59507092018-10-29 09:00:30 -07004972 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004973 final long origId = Binder.clearCallingIdentity();
4974 try {
4975 synchronized (mGlobalLock) {
4976 updateConfigurationLocked(values, null, false, true, userId,
4977 false /* deferResume */);
4978 }
4979 } finally {
4980 Binder.restoreCallingIdentity(origId);
4981 }
4982 }
4983
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004984 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4985 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4986 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4987 deferResume, null /* result */);
4988 }
4989
4990 /**
4991 * Do either or both things: (1) change the current configuration, and (2)
4992 * make sure the given activity is running with the (now) current
4993 * configuration. Returns true if the activity has been left running, or
4994 * false if <var>starting</var> is being destroyed to match the new
4995 * configuration.
4996 *
4997 * @param userId is only used when persistent parameter is set to true to persist configuration
4998 * for that particular user
4999 */
5000 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5001 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5002 ActivityTaskManagerService.UpdateConfigurationResult result) {
5003 int changes = 0;
5004 boolean kept = true;
5005
5006 if (mWindowManager != null) {
5007 mWindowManager.deferSurfaceLayout();
5008 }
5009 try {
5010 if (values != null) {
5011 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5012 deferResume);
5013 }
5014
5015 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5016 } finally {
5017 if (mWindowManager != null) {
5018 mWindowManager.continueSurfaceLayout();
5019 }
5020 }
5021
5022 if (result != null) {
5023 result.changes = changes;
5024 result.activityRelaunched = !kept;
5025 }
5026 return kept;
5027 }
5028
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005029 /** Update default (global) configuration and notify listeners about changes. */
5030 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5031 boolean persistent, int userId, boolean deferResume) {
5032 mTempConfig.setTo(getGlobalConfiguration());
5033 final int changes = mTempConfig.updateFrom(values);
5034 if (changes == 0) {
5035 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5036 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5037 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5038 // (even if there are no actual changes) to unfreeze the window.
5039 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5040 return 0;
5041 }
5042
5043 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5044 "Updating global configuration to: " + values);
5045
5046 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5047 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5048 values.colorMode,
5049 values.densityDpi,
5050 values.fontScale,
5051 values.hardKeyboardHidden,
5052 values.keyboard,
5053 values.keyboardHidden,
5054 values.mcc,
5055 values.mnc,
5056 values.navigation,
5057 values.navigationHidden,
5058 values.orientation,
5059 values.screenHeightDp,
5060 values.screenLayout,
5061 values.screenWidthDp,
5062 values.smallestScreenWidthDp,
5063 values.touchscreen,
5064 values.uiMode);
5065
5066
5067 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5068 final LocaleList locales = values.getLocales();
5069 int bestLocaleIndex = 0;
5070 if (locales.size() > 1) {
5071 if (mSupportedSystemLocales == null) {
5072 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5073 }
5074 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5075 }
5076 SystemProperties.set("persist.sys.locale",
5077 locales.get(bestLocaleIndex).toLanguageTag());
5078 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005079
5080 final Message m = PooledLambda.obtainMessage(
5081 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5082 locales.get(bestLocaleIndex));
5083 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005084 }
5085
Yunfan Chen75157d72018-07-27 14:47:21 +09005086 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005087
5088 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005089 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005090
5091 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5092 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005093 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005094
5095 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005096 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005097
5098 AttributeCache ac = AttributeCache.instance();
5099 if (ac != null) {
5100 ac.updateConfiguration(mTempConfig);
5101 }
5102
5103 // Make sure all resources in our process are updated right now, so that anyone who is going
5104 // to retrieve resource values after we return will be sure to get the new ones. This is
5105 // especially important during boot, where the first config change needs to guarantee all
5106 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005107 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005108
5109 // We need another copy of global config because we're scheduling some calls instead of
5110 // running them in place. We need to be sure that object we send will be handled unchanged.
5111 final Configuration configCopy = new Configuration(mTempConfig);
5112 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005113 final Message msg = PooledLambda.obtainMessage(
5114 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5115 this, userId, configCopy);
5116 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005117 }
5118
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005119 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005120 final int pid = mPidMap.keyAt(i);
5121 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005122 if (DEBUG_CONFIGURATION) {
5123 Slog.v(TAG_CONFIGURATION, "Update process config of "
5124 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005125 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005126 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005127 }
5128
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005129 final Message msg = PooledLambda.obtainMessage(
5130 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5131 mAmInternal, changes, initLocale);
5132 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005133
5134 // Override configuration of the default display duplicates global config, so we need to
5135 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005136 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 DEFAULT_DISPLAY);
5138
5139 return changes;
5140 }
5141
5142 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5143 boolean deferResume, int displayId) {
5144 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5145 displayId, null /* result */);
5146 }
5147
5148 /**
5149 * Updates override configuration specific for the selected display. If no config is provided,
5150 * new one will be computed in WM based on current display info.
5151 */
5152 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5153 ActivityRecord starting, boolean deferResume, int displayId,
5154 ActivityTaskManagerService.UpdateConfigurationResult result) {
5155 int changes = 0;
5156 boolean kept = true;
5157
5158 if (mWindowManager != null) {
5159 mWindowManager.deferSurfaceLayout();
5160 }
5161 try {
5162 if (values != null) {
5163 if (displayId == DEFAULT_DISPLAY) {
5164 // Override configuration of the default display duplicates global config, so
5165 // we're calling global config update instead for default display. It will also
5166 // apply the correct override config.
5167 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5168 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5169 } else {
5170 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5171 }
5172 }
5173
5174 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5175 } finally {
5176 if (mWindowManager != null) {
5177 mWindowManager.continueSurfaceLayout();
5178 }
5179 }
5180
5181 if (result != null) {
5182 result.changes = changes;
5183 result.activityRelaunched = !kept;
5184 }
5185 return kept;
5186 }
5187
5188 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5189 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005190 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005191 final int changes = mTempConfig.updateFrom(values);
5192 if (changes != 0) {
5193 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5194 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005195 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196
5197 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5198 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005199 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005200
Wale Ogunwale5c918702018-10-18 11:06:33 -07005201 // Post message to start process to avoid possible deadlock of calling into AMS with
5202 // the ATMS lock held.
5203 final Message msg = PooledLambda.obtainMessage(
5204 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5205 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5206 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005207 }
5208 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005209 return changes;
5210 }
5211
Wale Ogunwalef6733932018-06-27 05:14:34 -07005212 private void updateEventDispatchingLocked(boolean booted) {
5213 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5214 }
5215
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005216 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5217 final ContentResolver resolver = mContext.getContentResolver();
5218 Settings.System.putConfigurationForUser(resolver, config, userId);
5219 }
5220
5221 private void sendLocaleToMountDaemonMsg(Locale l) {
5222 try {
5223 IBinder service = ServiceManager.getService("mount");
5224 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5225 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5226 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5227 } catch (RemoteException e) {
5228 Log.e(TAG, "Error storing locale for decryption UI", e);
5229 }
5230 }
5231
Alison Cichowlas3e340502018-08-07 17:15:01 -04005232 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5233 mStartActivitySources.remove(permissionToken);
5234 mExpiredStartAsCallerTokens.add(permissionToken);
5235 }
5236
5237 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5238 mExpiredStartAsCallerTokens.remove(permissionToken);
5239 }
5240
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005241 boolean isActivityStartsLoggingEnabled() {
5242 return mAmInternal.isActivityStartsLoggingEnabled();
5243 }
5244
Michal Karpinski8596ded2018-11-14 14:43:48 +00005245 boolean isBackgroundActivityStartsEnabled() {
5246 return mAmInternal.isBackgroundActivityStartsEnabled();
5247 }
5248
Wale Ogunwalef6733932018-06-27 05:14:34 -07005249 void enableScreenAfterBoot(boolean booted) {
5250 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5251 SystemClock.uptimeMillis());
5252 mWindowManager.enableScreenAfterBoot();
5253
5254 synchronized (mGlobalLock) {
5255 updateEventDispatchingLocked(booted);
5256 }
5257 }
5258
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005259 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5260 if (r == null || !r.hasProcess()) {
5261 return KEY_DISPATCHING_TIMEOUT_MS;
5262 }
5263 return getInputDispatchingTimeoutLocked(r.app);
5264 }
5265
5266 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005267 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005268 }
5269
Wale Ogunwalef6733932018-06-27 05:14:34 -07005270 /**
5271 * Decide based on the configuration whether we should show the ANR,
5272 * crash, etc dialogs. The idea is that if there is no affordance to
5273 * press the on-screen buttons, or the user experience would be more
5274 * greatly impacted than the crash itself, we shouldn't show the dialog.
5275 *
5276 * A thought: SystemUI might also want to get told about this, the Power
5277 * dialog / global actions also might want different behaviors.
5278 */
5279 private void updateShouldShowDialogsLocked(Configuration config) {
5280 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5281 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5282 && config.navigation == Configuration.NAVIGATION_NONAV);
5283 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5284 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5285 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5286 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5287 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5288 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5289 HIDE_ERROR_DIALOGS, 0) != 0;
5290 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5291 }
5292
5293 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5294 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5295 FONT_SCALE, 1.0f, userId);
5296
5297 synchronized (this) {
5298 if (getGlobalConfiguration().fontScale == scaleFactor) {
5299 return;
5300 }
5301
5302 final Configuration configuration
5303 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5304 configuration.fontScale = scaleFactor;
5305 updatePersistentConfiguration(configuration, userId);
5306 }
5307 }
5308
5309 // Actually is sleeping or shutting down or whatever else in the future
5310 // is an inactive state.
5311 boolean isSleepingOrShuttingDownLocked() {
5312 return isSleepingLocked() || mShuttingDown;
5313 }
5314
5315 boolean isSleepingLocked() {
5316 return mSleeping;
5317 }
5318
Riddle Hsu16567132018-08-16 21:37:47 +08005319 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005320 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005321 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005322 if (task.isActivityTypeStandard()) {
5323 if (mCurAppTimeTracker != r.appTimeTracker) {
5324 // We are switching app tracking. Complete the current one.
5325 if (mCurAppTimeTracker != null) {
5326 mCurAppTimeTracker.stop();
5327 mH.obtainMessage(
5328 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005329 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005330 mCurAppTimeTracker = null;
5331 }
5332 if (r.appTimeTracker != null) {
5333 mCurAppTimeTracker = r.appTimeTracker;
5334 startTimeTrackingFocusedActivityLocked();
5335 }
5336 } else {
5337 startTimeTrackingFocusedActivityLocked();
5338 }
5339 } else {
5340 r.appTimeTracker = null;
5341 }
5342 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5343 // TODO: Probably not, because we don't want to resume voice on switching
5344 // back to this activity
5345 if (task.voiceInteractor != null) {
5346 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5347 } else {
5348 finishRunningVoiceLocked();
5349
5350 if (mLastResumedActivity != null) {
5351 final IVoiceInteractionSession session;
5352
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005353 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005354 if (lastResumedActivityTask != null
5355 && lastResumedActivityTask.voiceSession != null) {
5356 session = lastResumedActivityTask.voiceSession;
5357 } else {
5358 session = mLastResumedActivity.voiceSession;
5359 }
5360
5361 if (session != null) {
5362 // We had been in a voice interaction session, but now focused has
5363 // move to something different. Just finish the session, we can't
5364 // return to it and retain the proper state and synchronization with
5365 // the voice interaction service.
5366 finishVoiceTask(session);
5367 }
5368 }
5369 }
5370
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005371 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5372 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005373 }
5374 updateResumedAppTrace(r);
5375 mLastResumedActivity = r;
5376
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005377 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378
5379 applyUpdateLockStateLocked(r);
5380 applyUpdateVrModeLocked(r);
5381
5382 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005383 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005384 r == null ? "NULL" : r.shortComponentName,
5385 reason);
5386 }
5387
5388 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5389 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005390 final ActivityTaskManagerInternal.SleepToken token =
5391 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 updateSleepIfNeededLocked();
5393 return token;
5394 }
5395 }
5396
5397 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005398 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005399 final boolean wasSleeping = mSleeping;
5400 boolean updateOomAdj = false;
5401
5402 if (!shouldSleep) {
5403 // If wasSleeping is true, we need to wake up activity manager state from when
5404 // we started sleeping. In either case, we need to apply the sleep tokens, which
5405 // will wake up stacks or put them to sleep as appropriate.
5406 if (wasSleeping) {
5407 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005408 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5409 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005410 startTimeTrackingFocusedActivityLocked();
5411 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5412 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5413 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005414 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 if (wasSleeping) {
5416 updateOomAdj = true;
5417 }
5418 } else if (!mSleeping && shouldSleep) {
5419 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005420 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5421 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 if (mCurAppTimeTracker != null) {
5423 mCurAppTimeTracker.stop();
5424 }
5425 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5426 mStackSupervisor.goingToSleepLocked();
5427 updateResumedAppTrace(null /* resumed */);
5428 updateOomAdj = true;
5429 }
5430 if (updateOomAdj) {
5431 mH.post(mAmInternal::updateOomAdj);
5432 }
5433 }
5434
5435 void updateOomAdj() {
5436 mH.post(mAmInternal::updateOomAdj);
5437 }
5438
Wale Ogunwale53783742018-09-16 10:21:51 -07005439 void updateCpuStats() {
5440 mH.post(mAmInternal::updateCpuStats);
5441 }
5442
Hui Yu03d12402018-12-06 18:00:37 -08005443 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5444 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005445 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5446 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005447 mH.sendMessage(m);
5448 }
5449
Hui Yu03d12402018-12-06 18:00:37 -08005450 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005451 ComponentName taskRoot = null;
5452 final TaskRecord task = activity.getTaskRecord();
5453 if (task != null) {
5454 final ActivityRecord rootActivity = task.getRootActivity();
5455 if (rootActivity != null) {
5456 taskRoot = rootActivity.mActivityComponent;
5457 }
5458 }
5459
Hui Yu03d12402018-12-06 18:00:37 -08005460 final Message m = PooledLambda.obtainMessage(
5461 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005462 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005463 mH.sendMessage(m);
5464 }
5465
Wale Ogunwale53783742018-09-16 10:21:51 -07005466 void setBooting(boolean booting) {
5467 mAmInternal.setBooting(booting);
5468 }
5469
5470 boolean isBooting() {
5471 return mAmInternal.isBooting();
5472 }
5473
5474 void setBooted(boolean booted) {
5475 mAmInternal.setBooted(booted);
5476 }
5477
5478 boolean isBooted() {
5479 return mAmInternal.isBooted();
5480 }
5481
5482 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5483 mH.post(() -> {
5484 if (finishBooting) {
5485 mAmInternal.finishBooting();
5486 }
5487 if (enableScreen) {
5488 mInternal.enableScreenAfterBoot(isBooted());
5489 }
5490 });
5491 }
5492
5493 void setHeavyWeightProcess(ActivityRecord root) {
5494 mHeavyWeightProcess = root.app;
5495 final Message m = PooledLambda.obtainMessage(
5496 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005497 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005498 mH.sendMessage(m);
5499 }
5500
5501 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5502 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5503 return;
5504 }
5505
5506 mHeavyWeightProcess = null;
5507 final Message m = PooledLambda.obtainMessage(
5508 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5509 proc.mUserId);
5510 mH.sendMessage(m);
5511 }
5512
5513 private void cancelHeavyWeightProcessNotification(int userId) {
5514 final INotificationManager inm = NotificationManager.getService();
5515 if (inm == null) {
5516 return;
5517 }
5518 try {
5519 inm.cancelNotificationWithTag("android", null,
5520 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5521 } catch (RuntimeException e) {
5522 Slog.w(TAG, "Error canceling notification for service", e);
5523 } catch (RemoteException e) {
5524 }
5525
5526 }
5527
5528 private void postHeavyWeightProcessNotification(
5529 WindowProcessController proc, Intent intent, int userId) {
5530 if (proc == null) {
5531 return;
5532 }
5533
5534 final INotificationManager inm = NotificationManager.getService();
5535 if (inm == null) {
5536 return;
5537 }
5538
5539 try {
5540 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5541 String text = mContext.getString(R.string.heavy_weight_notification,
5542 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5543 Notification notification =
5544 new Notification.Builder(context,
5545 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5546 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5547 .setWhen(0)
5548 .setOngoing(true)
5549 .setTicker(text)
5550 .setColor(mContext.getColor(
5551 com.android.internal.R.color.system_notification_accent_color))
5552 .setContentTitle(text)
5553 .setContentText(
5554 mContext.getText(R.string.heavy_weight_notification_detail))
5555 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5556 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5557 new UserHandle(userId)))
5558 .build();
5559 try {
5560 inm.enqueueNotificationWithTag("android", "android", null,
5561 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5562 } catch (RuntimeException e) {
5563 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5564 } catch (RemoteException e) {
5565 }
5566 } catch (PackageManager.NameNotFoundException e) {
5567 Slog.w(TAG, "Unable to create context for heavy notification", e);
5568 }
5569
5570 }
5571
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005572 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5573 IBinder token, String resultWho, int requestCode, Intent[] intents,
5574 String[] resolvedTypes, int flags, Bundle bOptions) {
5575
5576 ActivityRecord activity = null;
5577 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5578 activity = ActivityRecord.isInStackLocked(token);
5579 if (activity == null) {
5580 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5581 return null;
5582 }
5583 if (activity.finishing) {
5584 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5585 return null;
5586 }
5587 }
5588
5589 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5590 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5591 bOptions);
5592 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5593 if (noCreate) {
5594 return rec;
5595 }
5596 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5597 if (activity.pendingResults == null) {
5598 activity.pendingResults = new HashSet<>();
5599 }
5600 activity.pendingResults.add(rec.ref);
5601 }
5602 return rec;
5603 }
5604
Andrii Kulian52d255c2018-07-13 11:32:19 -07005605 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005607 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005608 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5609 mCurAppTimeTracker.start(resumedActivity.packageName);
5610 }
5611 }
5612
5613 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5614 if (mTracedResumedActivity != null) {
5615 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5616 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5617 }
5618 if (resumed != null) {
5619 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5620 constructResumedTraceName(resumed.packageName), 0);
5621 }
5622 mTracedResumedActivity = resumed;
5623 }
5624
5625 private String constructResumedTraceName(String packageName) {
5626 return "focused app: " + packageName;
5627 }
5628
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005629 /** Applies latest configuration and/or visibility updates if needed. */
5630 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5631 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005632 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005633 // mainStack is null during startup.
5634 if (mainStack != null) {
5635 if (changes != 0 && starting == null) {
5636 // If the configuration changed, and the caller is not already
5637 // in the process of starting an activity, then find the top
5638 // activity to check if its configuration needs to change.
5639 starting = mainStack.topRunningActivityLocked();
5640 }
5641
5642 if (starting != null) {
5643 kept = starting.ensureActivityConfiguration(changes,
5644 false /* preserveWindow */);
5645 // And we need to make sure at this point that all other activities
5646 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005647 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005648 !PRESERVE_WINDOWS);
5649 }
5650 }
5651
5652 return kept;
5653 }
5654
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005655 void scheduleAppGcsLocked() {
5656 mH.post(() -> mAmInternal.scheduleAppGcs());
5657 }
5658
Wale Ogunwale53783742018-09-16 10:21:51 -07005659 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5660 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5661 }
5662
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005663 /**
5664 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5665 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5666 * on demand.
5667 */
5668 IPackageManager getPackageManager() {
5669 return AppGlobals.getPackageManager();
5670 }
5671
5672 PackageManagerInternal getPackageManagerInternalLocked() {
5673 if (mPmInternal == null) {
5674 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5675 }
5676 return mPmInternal;
5677 }
5678
Wale Ogunwale008163e2018-07-23 23:11:08 -07005679 AppWarnings getAppWarningsLocked() {
5680 return mAppWarnings;
5681 }
5682
Wale Ogunwale214f3482018-10-04 11:00:47 -07005683 Intent getHomeIntent() {
5684 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5685 intent.setComponent(mTopComponent);
5686 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5687 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5688 intent.addCategory(Intent.CATEGORY_HOME);
5689 }
5690 return intent;
5691 }
5692
Chilun2ef71f72018-11-16 17:57:15 +08005693 /**
5694 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5695 * activities.
5696 *
5697 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5698 * component defined in config_secondaryHomeComponent.
5699 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5700 */
5701 Intent getSecondaryHomeIntent(String preferredPackage) {
5702 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5703 if (preferredPackage == null) {
5704 // Using the component stored in config if no package name.
5705 final String secondaryHomeComponent = mContext.getResources().getString(
5706 com.android.internal.R.string.config_secondaryHomeComponent);
5707 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5708 } else {
5709 intent.setPackage(preferredPackage);
5710 }
5711 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5712 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5713 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5714 }
5715 return intent;
5716 }
5717
Wale Ogunwale214f3482018-10-04 11:00:47 -07005718 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5719 if (info == null) return null;
5720 ApplicationInfo newInfo = new ApplicationInfo(info);
5721 newInfo.initForUser(userId);
5722 return newInfo;
5723 }
5724
Wale Ogunwale9c103022018-10-18 07:44:54 -07005725 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005726 if (uid == SYSTEM_UID) {
5727 // The system gets to run in any process. If there are multiple processes with the same
5728 // uid, just pick the first (this should never happen).
5729 final SparseArray<WindowProcessController> procs =
5730 mProcessNames.getMap().get(processName);
5731 if (procs == null) return null;
5732 final int procCount = procs.size();
5733 for (int i = 0; i < procCount; i++) {
5734 final int procUid = procs.keyAt(i);
5735 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5736 // Don't use an app process or different user process for system component.
5737 continue;
5738 }
5739 return procs.valueAt(i);
5740 }
5741 }
5742
5743 return mProcessNames.get(processName, uid);
5744 }
5745
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005746 WindowProcessController getProcessController(IApplicationThread thread) {
5747 if (thread == null) {
5748 return null;
5749 }
5750
5751 final IBinder threadBinder = thread.asBinder();
5752 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5753 for (int i = pmap.size()-1; i >= 0; i--) {
5754 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5755 for (int j = procs.size() - 1; j >= 0; j--) {
5756 final WindowProcessController proc = procs.valueAt(j);
5757 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5758 return proc;
5759 }
5760 }
5761 }
5762
5763 return null;
5764 }
5765
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005766 WindowProcessController getProcessController(int pid, int uid) {
5767 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5768 for (int i = pmap.size()-1; i >= 0; i--) {
5769 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5770 for (int j = procs.size() - 1; j >= 0; j--) {
5771 final WindowProcessController proc = procs.valueAt(j);
5772 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5773 return proc;
5774 }
5775 }
5776 }
5777 return null;
5778 }
5779
Riddle Hsua0536432019-02-16 00:38:59 +08005780 int getUidState(int uid) {
5781 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005782 }
5783
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005784 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005785 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005786 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5787 }
5788
Michal Karpinski4026cae2019-02-12 11:51:47 +00005789 boolean isDeviceOwner(String packageName) {
5790 if (packageName == null) {
5791 return false;
5792 }
5793 return packageName.equals(mDeviceOwnerPackageName);
5794 }
5795
5796 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5797 mDeviceOwnerPackageName = deviceOwnerPkg;
5798 }
5799
Wale Ogunwale9de19442018-10-18 19:05:03 -07005800 /**
5801 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5802 * the whitelist
5803 */
5804 String getPendingTempWhitelistTagForUidLocked(int uid) {
5805 return mPendingTempWhitelist.get(uid);
5806 }
5807
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005808 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5809 if (true || Build.IS_USER) {
5810 return;
5811 }
5812
5813 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5814 StrictMode.allowThreadDiskWrites();
5815 try {
5816 File tracesDir = new File("/data/anr");
5817 File tracesFile = null;
5818 try {
5819 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5820
5821 StringBuilder sb = new StringBuilder();
5822 Time tobj = new Time();
5823 tobj.set(System.currentTimeMillis());
5824 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5825 sb.append(": ");
5826 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5827 sb.append(" since ");
5828 sb.append(msg);
5829 FileOutputStream fos = new FileOutputStream(tracesFile);
5830 fos.write(sb.toString().getBytes());
5831 if (app == null) {
5832 fos.write("\n*** No application process!".getBytes());
5833 }
5834 fos.close();
5835 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5836 } catch (IOException e) {
5837 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5838 return;
5839 }
5840
5841 if (app != null && app.getPid() > 0) {
5842 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5843 firstPids.add(app.getPid());
5844 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5845 }
5846
5847 File lastTracesFile = null;
5848 File curTracesFile = null;
5849 for (int i=9; i>=0; i--) {
5850 String name = String.format(Locale.US, "slow%02d.txt", i);
5851 curTracesFile = new File(tracesDir, name);
5852 if (curTracesFile.exists()) {
5853 if (lastTracesFile != null) {
5854 curTracesFile.renameTo(lastTracesFile);
5855 } else {
5856 curTracesFile.delete();
5857 }
5858 }
5859 lastTracesFile = curTracesFile;
5860 }
5861 tracesFile.renameTo(curTracesFile);
5862 } finally {
5863 StrictMode.setThreadPolicy(oldPolicy);
5864 }
5865 }
5866
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005867 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005868 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005869
5870
Wale Ogunwale98875612018-10-12 07:53:02 -07005871 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5872 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005873
Riddle Hsud93a6c42018-11-29 21:50:06 +08005874 H(Looper looper) {
5875 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005876 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005877
5878 @Override
5879 public void handleMessage(Message msg) {
5880 switch (msg.what) {
5881 case REPORT_TIME_TRACKER_MSG: {
5882 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5883 tracker.deliverResult(mContext);
5884 } break;
5885 }
5886 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005887 }
5888
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005889 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005890 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005891
5892 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005893 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005894 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005895
5896 @Override
5897 public void handleMessage(Message msg) {
5898 switch (msg.what) {
5899 case DISMISS_DIALOG_UI_MSG: {
5900 final Dialog d = (Dialog) msg.obj;
5901 d.dismiss();
5902 break;
5903 }
5904 }
5905 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005906 }
5907
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005908 final class LocalService extends ActivityTaskManagerInternal {
5909 @Override
5910 public SleepToken acquireSleepToken(String tag, int displayId) {
5911 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005912 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005913 }
5914
5915 @Override
5916 public ComponentName getHomeActivityForUser(int userId) {
5917 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005918 final ActivityRecord homeActivity =
5919 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005920 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005921 }
5922 }
5923
5924 @Override
5925 public void onLocalVoiceInteractionStarted(IBinder activity,
5926 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5927 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005928 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005929 }
5930 }
5931
5932 @Override
5933 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5934 synchronized (mGlobalLock) {
5935 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5936 reasons, timestamp);
5937 }
5938 }
5939
5940 @Override
5941 public void notifyAppTransitionFinished() {
5942 synchronized (mGlobalLock) {
5943 mStackSupervisor.notifyAppTransitionDone();
5944 }
5945 }
5946
5947 @Override
5948 public void notifyAppTransitionCancelled() {
5949 synchronized (mGlobalLock) {
5950 mStackSupervisor.notifyAppTransitionDone();
5951 }
5952 }
5953
5954 @Override
5955 public List<IBinder> getTopVisibleActivities() {
5956 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005957 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005958 }
5959 }
5960
5961 @Override
5962 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5963 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005964 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005965 }
5966 }
5967
5968 @Override
5969 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5970 Bundle bOptions) {
5971 Preconditions.checkNotNull(intents, "intents");
5972 final String[] resolvedTypes = new String[intents.length];
5973
5974 // UID of the package on user userId.
5975 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5976 // packageUid may not be initialized.
5977 int packageUid = 0;
5978 final long ident = Binder.clearCallingIdentity();
5979
5980 try {
5981 for (int i = 0; i < intents.length; i++) {
5982 resolvedTypes[i] =
5983 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5984 }
5985
5986 packageUid = AppGlobals.getPackageManager().getPackageUid(
5987 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5988 } catch (RemoteException e) {
5989 // Shouldn't happen.
5990 } finally {
5991 Binder.restoreCallingIdentity(ident);
5992 }
5993
Riddle Hsu591bf612019-02-14 17:55:31 +08005994 return getActivityStartController().startActivitiesInPackage(
5995 packageUid, packageName,
5996 intents, resolvedTypes, null /* resultTo */,
5997 SafeActivityOptions.fromBundle(bOptions), userId,
5998 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5999 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006000 }
6001
6002 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006003 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6004 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6005 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6006 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006007 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006008 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006009 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6010 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6011 userId, validateIncomingUser, originatingPendingIntent,
6012 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006013 }
6014 }
6015
6016 @Override
6017 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6018 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6019 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6020 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006021 PendingIntentRecord originatingPendingIntent,
6022 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006023 synchronized (mGlobalLock) {
6024 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6025 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6026 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006027 validateIncomingUser, originatingPendingIntent,
6028 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006029 }
6030 }
6031
6032 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006033 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6034 Intent intent, Bundle options, int userId) {
6035 return ActivityTaskManagerService.this.startActivityAsUser(
6036 caller, callerPacakge, intent,
6037 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6038 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6039 false /*validateIncomingUser*/);
6040 }
6041
6042 @Override
lumark588a3e82018-07-20 18:53:54 +08006043 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006044 synchronized (mGlobalLock) {
6045
6046 // We might change the visibilities here, so prepare an empty app transition which
6047 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006048 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006049 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006050 if (activityDisplay == null) {
6051 return;
6052 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006053 final DisplayContent dc = activityDisplay.mDisplayContent;
6054 final boolean wasTransitionSet =
6055 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006057 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006058 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006059 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006060
6061 // If there was a transition set already we don't want to interfere with it as we
6062 // might be starting it too early.
6063 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006064 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006065 }
6066 }
6067 if (callback != null) {
6068 callback.run();
6069 }
6070 }
6071
6072 @Override
6073 public void notifyKeyguardTrustedChanged() {
6074 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006075 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006076 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 }
6078 }
6079 }
6080
6081 /**
6082 * Called after virtual display Id is updated by
6083 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6084 * {@param vrVr2dDisplayId}.
6085 */
6086 @Override
6087 public void setVr2dDisplayId(int vr2dDisplayId) {
6088 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6089 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006090 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006091 }
6092 }
6093
6094 @Override
6095 public void setFocusedActivity(IBinder token) {
6096 synchronized (mGlobalLock) {
6097 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6098 if (r == null) {
6099 throw new IllegalArgumentException(
6100 "setFocusedActivity: No activity record matching token=" + token);
6101 }
Louis Chang19443452018-10-09 12:10:21 +08006102 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006103 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006104 }
6105 }
6106 }
6107
6108 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006109 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006110 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006111 }
6112
6113 @Override
6114 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006115 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 }
6117
6118 @Override
6119 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006120 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006121 }
6122
6123 @Override
6124 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6125 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6126 }
6127
6128 @Override
6129 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006130 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006132
6133 @Override
6134 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6135 synchronized (mGlobalLock) {
6136 mActiveVoiceInteractionServiceComponent = component;
6137 }
6138 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006139
6140 @Override
6141 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6142 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6143 return;
6144 }
6145 synchronized (mGlobalLock) {
6146 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6147 if (types == null) {
6148 if (uid < 0) {
6149 return;
6150 }
6151 types = new ArrayMap<>();
6152 mAllowAppSwitchUids.put(userId, types);
6153 }
6154 if (uid < 0) {
6155 types.remove(type);
6156 } else {
6157 types.put(type, uid);
6158 }
6159 }
6160 }
6161
6162 @Override
6163 public void onUserStopped(int userId) {
6164 synchronized (mGlobalLock) {
6165 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6166 mAllowAppSwitchUids.remove(userId);
6167 }
6168 }
6169
6170 @Override
6171 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6172 synchronized (mGlobalLock) {
6173 return ActivityTaskManagerService.this.isGetTasksAllowed(
6174 caller, callingPid, callingUid);
6175 }
6176 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006177
Riddle Hsua0536432019-02-16 00:38:59 +08006178 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006179 @Override
6180 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006181 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006182 mProcessNames.put(proc.mName, proc.mUid, proc);
6183 }
6184 }
6185
Riddle Hsua0536432019-02-16 00:38:59 +08006186 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006187 @Override
6188 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006189 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006190 mProcessNames.remove(name, uid);
6191 }
6192 }
6193
Riddle Hsua0536432019-02-16 00:38:59 +08006194 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006195 @Override
6196 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006197 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006198 if (proc == mHomeProcess) {
6199 mHomeProcess = null;
6200 }
6201 if (proc == mPreviousProcess) {
6202 mPreviousProcess = null;
6203 }
6204 }
6205 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006206
Riddle Hsua0536432019-02-16 00:38:59 +08006207 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006208 @Override
6209 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006210 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006211 return mTopProcessState;
6212 }
6213 }
6214
Riddle Hsua0536432019-02-16 00:38:59 +08006215 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006216 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006217 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006218 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006219 return proc == mHeavyWeightProcess;
6220 }
6221 }
6222
Riddle Hsua0536432019-02-16 00:38:59 +08006223 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006224 @Override
6225 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006226 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006227 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6228 }
6229 }
6230
6231 @Override
6232 public void finishHeavyWeightApp() {
6233 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006234 if (mHeavyWeightProcess != null) {
6235 mHeavyWeightProcess.finishActivities();
6236 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006237 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6238 mHeavyWeightProcess);
6239 }
6240 }
6241
Riddle Hsua0536432019-02-16 00:38:59 +08006242 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006243 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006244 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006245 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006246 return isSleepingLocked();
6247 }
6248 }
6249
6250 @Override
6251 public boolean isShuttingDown() {
6252 synchronized (mGlobalLock) {
6253 return mShuttingDown;
6254 }
6255 }
6256
6257 @Override
6258 public boolean shuttingDown(boolean booted, int timeout) {
6259 synchronized (mGlobalLock) {
6260 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006261 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006262 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006263 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006264 return mStackSupervisor.shutdownLocked(timeout);
6265 }
6266 }
6267
6268 @Override
6269 public void enableScreenAfterBoot(boolean booted) {
6270 synchronized (mGlobalLock) {
6271 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6272 SystemClock.uptimeMillis());
6273 mWindowManager.enableScreenAfterBoot();
6274 updateEventDispatchingLocked(booted);
6275 }
6276 }
6277
6278 @Override
6279 public boolean showStrictModeViolationDialog() {
6280 synchronized (mGlobalLock) {
6281 return mShowDialogs && !mSleeping && !mShuttingDown;
6282 }
6283 }
6284
6285 @Override
6286 public void showSystemReadyErrorDialogsIfNeeded() {
6287 synchronized (mGlobalLock) {
6288 try {
6289 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6290 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6291 + " data partition or your device will be unstable.");
6292 mUiHandler.post(() -> {
6293 if (mShowDialogs) {
6294 AlertDialog d = new BaseErrorDialog(mUiContext);
6295 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6296 d.setCancelable(false);
6297 d.setTitle(mUiContext.getText(R.string.android_system_label));
6298 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6299 d.setButton(DialogInterface.BUTTON_POSITIVE,
6300 mUiContext.getText(R.string.ok),
6301 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6302 d.show();
6303 }
6304 });
6305 }
6306 } catch (RemoteException e) {
6307 }
6308
6309 if (!Build.isBuildConsistent()) {
6310 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6311 mUiHandler.post(() -> {
6312 if (mShowDialogs) {
6313 AlertDialog d = new BaseErrorDialog(mUiContext);
6314 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6315 d.setCancelable(false);
6316 d.setTitle(mUiContext.getText(R.string.android_system_label));
6317 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6318 d.setButton(DialogInterface.BUTTON_POSITIVE,
6319 mUiContext.getText(R.string.ok),
6320 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6321 d.show();
6322 }
6323 });
6324 }
6325 }
6326 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006327
6328 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006329 public void onProcessMapped(int pid, WindowProcessController proc) {
6330 synchronized (mGlobalLock) {
6331 mPidMap.put(pid, proc);
6332 }
6333 }
6334
6335 @Override
6336 public void onProcessUnMapped(int pid) {
6337 synchronized (mGlobalLock) {
6338 mPidMap.remove(pid);
6339 }
6340 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006341
6342 @Override
6343 public void onPackageDataCleared(String name) {
6344 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006345 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006346 mAppWarnings.onPackageDataCleared(name);
6347 }
6348 }
6349
6350 @Override
6351 public void onPackageUninstalled(String name) {
6352 synchronized (mGlobalLock) {
6353 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006354 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006355 }
6356 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006357
6358 @Override
6359 public void onPackageAdded(String name, boolean replacing) {
6360 synchronized (mGlobalLock) {
6361 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6362 }
6363 }
6364
6365 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006366 public void onPackageReplaced(ApplicationInfo aInfo) {
6367 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006368 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006369 }
6370 }
6371
6372 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006373 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6374 synchronized (mGlobalLock) {
6375 return compatibilityInfoForPackageLocked(ai);
6376 }
6377 }
6378
Yunfan Chen75157d72018-07-27 14:47:21 +09006379 /**
6380 * Set the corresponding display information for the process global configuration. To be
6381 * called when we need to show IME on a different display.
6382 *
6383 * @param pid The process id associated with the IME window.
6384 * @param displayId The ID of the display showing the IME.
6385 */
6386 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006387 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006388 if (pid == MY_PID || pid < 0) {
6389 if (DEBUG_CONFIGURATION) {
6390 Slog.w(TAG,
6391 "Trying to update display configuration for system/invalid process.");
6392 }
6393 return;
6394 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006395 synchronized (mGlobalLock) {
6396 final ActivityDisplay activityDisplay =
6397 mRootActivityContainer.getActivityDisplay(displayId);
6398 if (activityDisplay == null) {
6399 // Call might come when display is not yet added or has been removed.
6400 if (DEBUG_CONFIGURATION) {
6401 Slog.w(TAG, "Trying to update display configuration for non-existing "
6402 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006403 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006404 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006405 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006406 final WindowProcessController process = mPidMap.get(pid);
6407 if (process == null) {
6408 if (DEBUG_CONFIGURATION) {
6409 Slog.w(TAG, "Trying to update display configuration for invalid "
6410 + "process, pid=" + pid);
6411 }
6412 return;
6413 }
6414 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6415 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006416 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006417
6418 @Override
6419 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6420 int requestCode, int resultCode, Intent data) {
6421 synchronized (mGlobalLock) {
6422 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006423 if (r != null && r.getActivityStack() != null) {
6424 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6425 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006426 }
6427 }
6428 }
6429
6430 @Override
6431 public void clearPendingResultForActivity(IBinder activityToken,
6432 WeakReference<PendingIntentRecord> pir) {
6433 synchronized (mGlobalLock) {
6434 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6435 if (r != null && r.pendingResults != null) {
6436 r.pendingResults.remove(pir);
6437 }
6438 }
6439 }
6440
6441 @Override
6442 public IIntentSender getIntentSender(int type, String packageName,
6443 int callingUid, int userId, IBinder token, String resultWho,
6444 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6445 Bundle bOptions) {
6446 synchronized (mGlobalLock) {
6447 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6448 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6449 }
6450 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006451
6452 @Override
6453 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6454 synchronized (mGlobalLock) {
6455 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6456 if (r == null) {
6457 return null;
6458 }
6459 if (r.mServiceConnectionsHolder == null) {
6460 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6461 ActivityTaskManagerService.this, r);
6462 }
6463
6464 return r.mServiceConnectionsHolder;
6465 }
6466 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006467
6468 @Override
6469 public Intent getHomeIntent() {
6470 synchronized (mGlobalLock) {
6471 return ActivityTaskManagerService.this.getHomeIntent();
6472 }
6473 }
6474
6475 @Override
6476 public boolean startHomeActivity(int userId, String reason) {
6477 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006478 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006479 }
6480 }
6481
6482 @Override
6483 public boolean startHomeOnAllDisplays(int userId, String reason) {
6484 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006485 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006486 }
6487 }
6488
Riddle Hsua0536432019-02-16 00:38:59 +08006489 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006490 @Override
6491 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006492 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006493 if (mFactoryTest == FACTORY_TEST_OFF) {
6494 return false;
6495 }
6496 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6497 && wpc.mName.equals(mTopComponent.getPackageName())) {
6498 return true;
6499 }
6500 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6501 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6502 }
6503 }
6504
6505 @Override
6506 public void updateTopComponentForFactoryTest() {
6507 synchronized (mGlobalLock) {
6508 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6509 return;
6510 }
6511 final ResolveInfo ri = mContext.getPackageManager()
6512 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6513 final CharSequence errorMsg;
6514 if (ri != null) {
6515 final ActivityInfo ai = ri.activityInfo;
6516 final ApplicationInfo app = ai.applicationInfo;
6517 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6518 mTopAction = Intent.ACTION_FACTORY_TEST;
6519 mTopData = null;
6520 mTopComponent = new ComponentName(app.packageName, ai.name);
6521 errorMsg = null;
6522 } else {
6523 errorMsg = mContext.getResources().getText(
6524 com.android.internal.R.string.factorytest_not_system);
6525 }
6526 } else {
6527 errorMsg = mContext.getResources().getText(
6528 com.android.internal.R.string.factorytest_no_action);
6529 }
6530 if (errorMsg == null) {
6531 return;
6532 }
6533
6534 mTopAction = null;
6535 mTopData = null;
6536 mTopComponent = null;
6537 mUiHandler.post(() -> {
6538 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6539 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006540 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006541 });
6542 }
6543 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006544
Riddle Hsua0536432019-02-16 00:38:59 +08006545 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006546 @Override
6547 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6548 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006549 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006550 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006551 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006552
6553 wpc.clearRecentTasks();
6554 wpc.clearActivities();
6555
6556 if (wpc.isInstrumenting()) {
6557 finishInstrumentationCallback.run();
6558 }
6559
Jorim Jaggid0752812018-10-16 16:07:20 +02006560 if (!restarting && hasVisibleActivities) {
6561 mWindowManager.deferSurfaceLayout();
6562 try {
6563 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6564 // If there was nothing to resume, and we are not already restarting
6565 // this process, but there is a visible activity that is hosted by the
6566 // process...then make sure all visible activities are running, taking
6567 // care of restarting this process.
6568 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6569 !PRESERVE_WINDOWS);
6570 }
6571 } finally {
6572 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006573 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006574 }
6575 }
6576 }
6577
6578 @Override
6579 public void closeSystemDialogs(String reason) {
6580 enforceNotIsolatedCaller("closeSystemDialogs");
6581
6582 final int pid = Binder.getCallingPid();
6583 final int uid = Binder.getCallingUid();
6584 final long origId = Binder.clearCallingIdentity();
6585 try {
6586 synchronized (mGlobalLock) {
6587 // Only allow this from foreground processes, so that background
6588 // applications can't abuse it to prevent system UI from being shown.
6589 if (uid >= FIRST_APPLICATION_UID) {
6590 final WindowProcessController proc = mPidMap.get(pid);
6591 if (!proc.isPerceptible()) {
6592 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6593 + " from background process " + proc);
6594 return;
6595 }
6596 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006597 mWindowManager.closeSystemDialogs(reason);
6598
Wale Ogunwaled32da472018-11-16 07:19:28 -08006599 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006600 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006601 // Call into AM outside the synchronized block.
6602 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006603 } finally {
6604 Binder.restoreCallingIdentity(origId);
6605 }
6606 }
6607
6608 @Override
6609 public void cleanupDisabledPackageComponents(
6610 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6611 synchronized (mGlobalLock) {
6612 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006613 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006614 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006615 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006616 mStackSupervisor.scheduleIdleLocked();
6617 }
6618
6619 // Clean-up disabled tasks
6620 getRecentTasks().cleanupDisabledPackageTasksLocked(
6621 packageName, disabledClasses, userId);
6622 }
6623 }
6624
6625 @Override
6626 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6627 int userId) {
6628 synchronized (mGlobalLock) {
6629
6630 boolean didSomething =
6631 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006632 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006633 null, doit, evenPersistent, userId);
6634 return didSomething;
6635 }
6636 }
6637
6638 @Override
6639 public void resumeTopActivities(boolean scheduleIdle) {
6640 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006641 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006642 if (scheduleIdle) {
6643 mStackSupervisor.scheduleIdleLocked();
6644 }
6645 }
6646 }
6647
Riddle Hsua0536432019-02-16 00:38:59 +08006648 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006649 @Override
6650 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006651 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006652 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6653 }
6654 }
6655
Riddle Hsua0536432019-02-16 00:38:59 +08006656 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006657 @Override
6658 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006659 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006660 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006661 }
6662 }
6663
6664 @Override
6665 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6666 try {
6667 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6668 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6669 }
6670 } catch (RemoteException ex) {
6671 throw new SecurityException("Fail to check is caller a privileged app", ex);
6672 }
6673
6674 synchronized (mGlobalLock) {
6675 final long ident = Binder.clearCallingIdentity();
6676 try {
6677 if (mAmInternal.shouldConfirmCredentials(userId)) {
6678 if (mKeyguardController.isKeyguardLocked()) {
6679 // Showing launcher to avoid user entering credential twice.
6680 startHomeActivity(currentUserId, "notifyLockedProfile");
6681 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006682 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006683 }
6684 } finally {
6685 Binder.restoreCallingIdentity(ident);
6686 }
6687 }
6688 }
6689
6690 @Override
6691 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6692 mAmInternal.enforceCallingPermission(
6693 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6694
6695 synchronized (mGlobalLock) {
6696 final long ident = Binder.clearCallingIdentity();
6697 try {
6698 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6699 FLAG_ACTIVITY_TASK_ON_HOME);
6700 ActivityOptions activityOptions = options != null
6701 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006702 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006703 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006704 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006705 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006706 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6708 UserHandle.CURRENT);
6709 } finally {
6710 Binder.restoreCallingIdentity(ident);
6711 }
6712 }
6713 }
6714
6715 @Override
6716 public void writeActivitiesToProto(ProtoOutputStream proto) {
6717 synchronized (mGlobalLock) {
6718 // The output proto of "activity --proto activities"
6719 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006720 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006721 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6722 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 }
6724 }
6725
6726 @Override
6727 public void saveANRState(String reason) {
6728 synchronized (mGlobalLock) {
6729 final StringWriter sw = new StringWriter();
6730 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6731 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6732 if (reason != null) {
6733 pw.println(" Reason: " + reason);
6734 }
6735 pw.println();
6736 getActivityStartController().dump(pw, " ", null);
6737 pw.println();
6738 pw.println("-------------------------------------------------------------------------------");
6739 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6740 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6741 "" /* header */);
6742 pw.println();
6743 pw.close();
6744
6745 mLastANRState = sw.toString();
6746 }
6747 }
6748
6749 @Override
6750 public void clearSavedANRState() {
6751 synchronized (mGlobalLock) {
6752 mLastANRState = null;
6753 }
6754 }
6755
6756 @Override
6757 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6758 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6759 synchronized (mGlobalLock) {
6760 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6761 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6762 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6763 dumpLastANRLocked(pw);
6764 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6765 dumpLastANRTracesLocked(pw);
6766 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6767 dumpActivityStarterLocked(pw, dumpPackage);
6768 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6769 dumpActivityContainersLocked(pw);
6770 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6771 if (getRecentTasks() != null) {
6772 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6773 }
6774 }
6775 }
6776 }
6777
6778 @Override
6779 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6780 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6781 int wakefulness) {
6782 synchronized (mGlobalLock) {
6783 if (mHomeProcess != null && (dumpPackage == null
6784 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6785 if (needSep) {
6786 pw.println();
6787 needSep = false;
6788 }
6789 pw.println(" mHomeProcess: " + mHomeProcess);
6790 }
6791 if (mPreviousProcess != null && (dumpPackage == null
6792 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6793 if (needSep) {
6794 pw.println();
6795 needSep = false;
6796 }
6797 pw.println(" mPreviousProcess: " + mPreviousProcess);
6798 }
6799 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6800 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6801 StringBuilder sb = new StringBuilder(128);
6802 sb.append(" mPreviousProcessVisibleTime: ");
6803 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6804 pw.println(sb);
6805 }
6806 if (mHeavyWeightProcess != null && (dumpPackage == null
6807 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6808 if (needSep) {
6809 pw.println();
6810 needSep = false;
6811 }
6812 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6813 }
6814 if (dumpPackage == null) {
6815 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006816 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 }
6818 if (dumpAll) {
6819 if (dumpPackage == null) {
6820 pw.println(" mConfigWillChange: "
6821 + getTopDisplayFocusedStack().mConfigWillChange);
6822 }
6823 if (mCompatModePackages.getPackages().size() > 0) {
6824 boolean printed = false;
6825 for (Map.Entry<String, Integer> entry
6826 : mCompatModePackages.getPackages().entrySet()) {
6827 String pkg = entry.getKey();
6828 int mode = entry.getValue();
6829 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6830 continue;
6831 }
6832 if (!printed) {
6833 pw.println(" mScreenCompatPackages:");
6834 printed = true;
6835 }
6836 pw.println(" " + pkg + ": " + mode);
6837 }
6838 }
6839 }
6840
6841 if (dumpPackage == null) {
6842 pw.println(" mWakefulness="
6843 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006844 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 if (mRunningVoice != null) {
6846 pw.println(" mRunningVoice=" + mRunningVoice);
6847 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6848 }
6849 pw.println(" mSleeping=" + mSleeping);
6850 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6851 pw.println(" mVrController=" + mVrController);
6852 }
6853 if (mCurAppTimeTracker != null) {
6854 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6855 }
6856 if (mAllowAppSwitchUids.size() > 0) {
6857 boolean printed = false;
6858 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6859 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6860 for (int j = 0; j < types.size(); j++) {
6861 if (dumpPackage == null ||
6862 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6863 if (needSep) {
6864 pw.println();
6865 needSep = false;
6866 }
6867 if (!printed) {
6868 pw.println(" mAllowAppSwitchUids:");
6869 printed = true;
6870 }
6871 pw.print(" User ");
6872 pw.print(mAllowAppSwitchUids.keyAt(i));
6873 pw.print(": Type ");
6874 pw.print(types.keyAt(j));
6875 pw.print(" = ");
6876 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6877 pw.println();
6878 }
6879 }
6880 }
6881 }
6882 if (dumpPackage == null) {
6883 if (mController != null) {
6884 pw.println(" mController=" + mController
6885 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6886 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006887 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6888 pw.println(" mLaunchingActivityWakeLock="
6889 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 }
6891
6892 return needSep;
6893 }
6894 }
6895
6896 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006897 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6898 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006899 synchronized (mGlobalLock) {
6900 if (dumpPackage == null) {
6901 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6902 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006903 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6904 if (mRunningVoice != null) {
6905 final long vrToken = proto.start(
6906 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6907 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6908 mRunningVoice.toString());
6909 mVoiceWakeLock.writeToProto(
6910 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6911 proto.end(vrToken);
6912 }
6913 mVrController.writeToProto(proto,
6914 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 if (mController != null) {
6916 final long token = proto.start(CONTROLLER);
6917 proto.write(CONTROLLER, mController.toString());
6918 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6919 proto.end(token);
6920 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006921 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6922 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6923 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006924 }
6925
6926 if (mHomeProcess != null && (dumpPackage == null
6927 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006928 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 }
6930
6931 if (mPreviousProcess != null && (dumpPackage == null
6932 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006933 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6935 }
6936
6937 if (mHeavyWeightProcess != null && (dumpPackage == null
6938 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006939 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 }
6941
6942 for (Map.Entry<String, Integer> entry
6943 : mCompatModePackages.getPackages().entrySet()) {
6944 String pkg = entry.getKey();
6945 int mode = entry.getValue();
6946 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6947 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6948 proto.write(PACKAGE, pkg);
6949 proto.write(MODE, mode);
6950 proto.end(compatToken);
6951 }
6952 }
6953
6954 if (mCurAppTimeTracker != null) {
6955 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6956 }
6957
6958 }
6959 }
6960
6961 @Override
6962 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6963 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6964 boolean dumpFocusedStackOnly) {
6965 synchronized (mGlobalLock) {
6966 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6967 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6968 }
6969 }
6970
6971 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006972 public void dumpForOom(PrintWriter pw) {
6973 synchronized (mGlobalLock) {
6974 pw.println(" mHomeProcess: " + mHomeProcess);
6975 pw.println(" mPreviousProcess: " + mPreviousProcess);
6976 if (mHeavyWeightProcess != null) {
6977 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6978 }
6979 }
6980 }
6981
6982 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006983 public boolean canGcNow() {
6984 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006985 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006986 }
6987 }
6988
Riddle Hsua0536432019-02-16 00:38:59 +08006989 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006990 @Override
6991 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006992 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006993 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 return top != null ? top.app : null;
6995 }
6996 }
6997
Riddle Hsua0536432019-02-16 00:38:59 +08006998 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006999 @Override
7000 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007001 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007002 if (mRootActivityContainer != null) {
7003 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007004 }
7005 }
7006 }
7007
7008 @Override
7009 public void scheduleDestroyAllActivities(String reason) {
7010 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007011 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007012 }
7013 }
7014
7015 @Override
7016 public void removeUser(int userId) {
7017 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007018 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007019 }
7020 }
7021
7022 @Override
7023 public boolean switchUser(int userId, UserState userState) {
7024 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007025 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007026 }
7027 }
7028
7029 @Override
7030 public void onHandleAppCrash(WindowProcessController wpc) {
7031 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007032 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 }
7034 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007035
7036 @Override
7037 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7038 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007039 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007040 }
7041 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007042
Riddle Hsua0536432019-02-16 00:38:59 +08007043 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007044 @Override
7045 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007046 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007047 }
7048
Riddle Hsua0536432019-02-16 00:38:59 +08007049 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007050 @Override
7051 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007052 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007053 }
7054
Riddle Hsua0536432019-02-16 00:38:59 +08007055 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007056 @Override
7057 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007058 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007059 }
7060
Riddle Hsua0536432019-02-16 00:38:59 +08007061 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007062 @Override
7063 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007064 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007065 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007066
7067 @Override
7068 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007069 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007070 mPendingTempWhitelist.put(uid, tag);
7071 }
7072 }
7073
7074 @Override
7075 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007076 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007077 mPendingTempWhitelist.remove(uid);
7078 }
7079 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007080
7081 @Override
7082 public boolean handleAppCrashInActivityController(String processName, int pid,
7083 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7084 Runnable killCrashingAppCallback) {
7085 synchronized (mGlobalLock) {
7086 if (mController == null) {
7087 return false;
7088 }
7089
7090 try {
7091 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7092 stackTrace)) {
7093 killCrashingAppCallback.run();
7094 return true;
7095 }
7096 } catch (RemoteException e) {
7097 mController = null;
7098 Watchdog.getInstance().setActivityController(null);
7099 }
7100 return false;
7101 }
7102 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007103
7104 @Override
7105 public void removeRecentTasksByPackageName(String packageName, int userId) {
7106 synchronized (mGlobalLock) {
7107 mRecentTasks.removeTasksByPackageName(packageName, userId);
7108 }
7109 }
7110
7111 @Override
7112 public void cleanupRecentTasksForUser(int userId) {
7113 synchronized (mGlobalLock) {
7114 mRecentTasks.cleanupLocked(userId);
7115 }
7116 }
7117
7118 @Override
7119 public void loadRecentTasksForUser(int userId) {
7120 synchronized (mGlobalLock) {
7121 mRecentTasks.loadUserRecentsLocked(userId);
7122 }
7123 }
7124
7125 @Override
7126 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7127 synchronized (mGlobalLock) {
7128 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7129 }
7130 }
7131
7132 @Override
7133 public void flushRecentTasks() {
7134 mRecentTasks.flush();
7135 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007136
7137 @Override
7138 public WindowProcessController getHomeProcess() {
7139 synchronized (mGlobalLock) {
7140 return mHomeProcess;
7141 }
7142 }
7143
7144 @Override
7145 public WindowProcessController getPreviousProcess() {
7146 synchronized (mGlobalLock) {
7147 return mPreviousProcess;
7148 }
7149 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007150
7151 @Override
7152 public void clearLockedTasks(String reason) {
7153 synchronized (mGlobalLock) {
7154 getLockTaskController().clearLockedTasks(reason);
7155 }
7156 }
7157
7158 @Override
7159 public void updateUserConfiguration() {
7160 synchronized (mGlobalLock) {
7161 final Configuration configuration = new Configuration(getGlobalConfiguration());
7162 final int currentUserId = mAmInternal.getCurrentUserId();
7163 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7164 configuration, currentUserId, Settings.System.canWrite(mContext));
7165 updateConfigurationLocked(configuration, null /* starting */,
7166 false /* initLocale */, false /* persistent */, currentUserId,
7167 false /* deferResume */);
7168 }
7169 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007170
7171 @Override
7172 public boolean canShowErrorDialogs() {
7173 synchronized (mGlobalLock) {
7174 return mShowDialogs && !mSleeping && !mShuttingDown
7175 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7176 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7177 mAmInternal.getCurrentUserId())
7178 && !(UserManager.isDeviceInDemoMode(mContext)
7179 && mAmInternal.getCurrentUser().isDemo());
7180 }
7181 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007182
7183 @Override
7184 public void setProfileApp(String profileApp) {
7185 synchronized (mGlobalLock) {
7186 mProfileApp = profileApp;
7187 }
7188 }
7189
7190 @Override
7191 public void setProfileProc(WindowProcessController wpc) {
7192 synchronized (mGlobalLock) {
7193 mProfileProc = wpc;
7194 }
7195 }
7196
7197 @Override
7198 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7199 synchronized (mGlobalLock) {
7200 mProfilerInfo = profilerInfo;
7201 }
7202 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007203
7204 @Override
7205 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7206 synchronized (mGlobalLock) {
7207 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7208 }
7209 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007210
7211 @Override
7212 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7213 synchronized (mGlobalLock) {
7214 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7215 }
7216 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007217
7218 @Override
7219 public boolean isUidForeground(int uid) {
7220 synchronized (mGlobalLock) {
7221 return ActivityTaskManagerService.this.isUidForeground(uid);
7222 }
7223 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007224
7225 @Override
7226 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7227 synchronized (mGlobalLock) {
7228 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7229 }
7230 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007231 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007232}