blob: e742df53e8f8fe0fe94ed5f41d9b94099001eb9c [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
1637 public final void activityPaused(IBinder token) {
1638 final long origId = Binder.clearCallingIdentity();
1639 synchronized (mGlobalLock) {
1640 ActivityStack stack = ActivityRecord.getStackLocked(token);
1641 if (stack != null) {
1642 stack.activityPausedLocked(token, false);
1643 }
1644 }
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647
1648 @Override
1649 public final void activityStopped(IBinder token, Bundle icicle,
1650 PersistableBundle persistentState, CharSequence description) {
1651 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1652
1653 // Refuse possible leaked file descriptors
1654 if (icicle != null && icicle.hasFileDescriptors()) {
1655 throw new IllegalArgumentException("File descriptors passed in Bundle");
1656 }
1657
1658 final long origId = Binder.clearCallingIdentity();
1659
1660 synchronized (mGlobalLock) {
1661 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1662 if (r != null) {
1663 r.activityStoppedLocked(icicle, persistentState, description);
1664 }
1665 }
1666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001667 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001668
1669 Binder.restoreCallingIdentity(origId);
1670 }
1671
1672 @Override
1673 public final void activityDestroyed(IBinder token) {
1674 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1675 synchronized (mGlobalLock) {
1676 ActivityStack stack = ActivityRecord.getStackLocked(token);
1677 if (stack != null) {
1678 stack.activityDestroyedLocked(token, "activityDestroyed");
1679 }
1680 }
1681 }
1682
1683 @Override
1684 public final void activityRelaunched(IBinder token) {
1685 final long origId = Binder.clearCallingIdentity();
1686 synchronized (mGlobalLock) {
1687 mStackSupervisor.activityRelaunchedLocked(token);
1688 }
1689 Binder.restoreCallingIdentity(origId);
1690 }
1691
1692 public final void activitySlept(IBinder token) {
1693 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1694
1695 final long origId = Binder.clearCallingIdentity();
1696
1697 synchronized (mGlobalLock) {
1698 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1699 if (r != null) {
1700 mStackSupervisor.activitySleptLocked(r);
1701 }
1702 }
1703
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706
1707 @Override
1708 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1709 synchronized (mGlobalLock) {
1710 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1711 if (r == null) {
1712 return;
1713 }
1714 final long origId = Binder.clearCallingIdentity();
1715 try {
1716 r.setRequestedOrientation(requestedOrientation);
1717 } finally {
1718 Binder.restoreCallingIdentity(origId);
1719 }
1720 }
1721 }
1722
1723 @Override
1724 public int getRequestedOrientation(IBinder token) {
1725 synchronized (mGlobalLock) {
1726 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1727 if (r == null) {
1728 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1729 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001730 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 }
1732 }
1733
1734 @Override
1735 public void setImmersive(IBinder token, boolean immersive) {
1736 synchronized (mGlobalLock) {
1737 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1738 if (r == null) {
1739 throw new IllegalArgumentException();
1740 }
1741 r.immersive = immersive;
1742
1743 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001744 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001746 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747 }
1748 }
1749 }
1750
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001751 void applyUpdateLockStateLocked(ActivityRecord r) {
1752 // Modifications to the UpdateLock state are done on our handler, outside
1753 // the activity manager's locks. The new state is determined based on the
1754 // state *now* of the relevant activity record. The object is passed to
1755 // the handler solely for logging detail, not to be consulted/modified.
1756 final boolean nextState = r != null && r.immersive;
1757 mH.post(() -> {
1758 if (mUpdateLock.isHeld() != nextState) {
1759 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1760 "Applying new update lock state '" + nextState + "' for " + r);
1761 if (nextState) {
1762 mUpdateLock.acquire();
1763 } else {
1764 mUpdateLock.release();
1765 }
1766 }
1767 });
1768 }
1769
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 @Override
1771 public boolean isImmersive(IBinder token) {
1772 synchronized (mGlobalLock) {
1773 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1774 if (r == null) {
1775 throw new IllegalArgumentException();
1776 }
1777 return r.immersive;
1778 }
1779 }
1780
1781 @Override
1782 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001783 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001784 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001785 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001786 return (r != null) ? r.immersive : false;
1787 }
1788 }
1789
1790 @Override
1791 public void overridePendingTransition(IBinder token, String packageName,
1792 int enterAnim, int exitAnim) {
1793 synchronized (mGlobalLock) {
1794 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1795 if (self == null) {
1796 return;
1797 }
1798
1799 final long origId = Binder.clearCallingIdentity();
1800
1801 if (self.isState(
1802 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001803 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001804 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 }
1806
1807 Binder.restoreCallingIdentity(origId);
1808 }
1809 }
1810
1811 @Override
1812 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001813 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001815 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 if (r == null) {
1817 return ActivityManager.COMPAT_MODE_UNKNOWN;
1818 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001819 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001820 }
1821 }
1822
1823 @Override
1824 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001825 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001827 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001829 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001830 if (r == null) {
1831 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1832 return;
1833 }
1834 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001835 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001836 }
1837 }
1838
1839 @Override
1840 public int getLaunchedFromUid(IBinder activityToken) {
1841 ActivityRecord srec;
1842 synchronized (mGlobalLock) {
1843 srec = ActivityRecord.forTokenLocked(activityToken);
1844 }
1845 if (srec == null) {
1846 return -1;
1847 }
1848 return srec.launchedFromUid;
1849 }
1850
1851 @Override
1852 public String getLaunchedFromPackage(IBinder activityToken) {
1853 ActivityRecord srec;
1854 synchronized (mGlobalLock) {
1855 srec = ActivityRecord.forTokenLocked(activityToken);
1856 }
1857 if (srec == null) {
1858 return null;
1859 }
1860 return srec.launchedFromPackage;
1861 }
1862
1863 @Override
1864 public boolean convertFromTranslucent(IBinder token) {
1865 final long origId = Binder.clearCallingIdentity();
1866 try {
1867 synchronized (mGlobalLock) {
1868 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1869 if (r == null) {
1870 return false;
1871 }
1872 final boolean translucentChanged = r.changeWindowTranslucency(true);
1873 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001874 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 return translucentChanged;
1878 }
1879 } finally {
1880 Binder.restoreCallingIdentity(origId);
1881 }
1882 }
1883
1884 @Override
1885 public boolean convertToTranslucent(IBinder token, Bundle options) {
1886 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1887 final long origId = Binder.clearCallingIdentity();
1888 try {
1889 synchronized (mGlobalLock) {
1890 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1891 if (r == null) {
1892 return false;
1893 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001894 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 int index = task.mActivities.lastIndexOf(r);
1896 if (index > 0) {
1897 ActivityRecord under = task.mActivities.get(index - 1);
1898 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1899 }
1900 final boolean translucentChanged = r.changeWindowTranslucency(false);
1901 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001902 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001904 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001905 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 return translucentChanged;
1907 }
1908 } finally {
1909 Binder.restoreCallingIdentity(origId);
1910 }
1911 }
1912
1913 @Override
1914 public void notifyActivityDrawn(IBinder token) {
1915 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1916 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001917 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001919 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 }
1921 }
1922 }
1923
1924 @Override
1925 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1926 synchronized (mGlobalLock) {
1927 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1928 if (r == null) {
1929 return;
1930 }
1931 r.reportFullyDrawnLocked(restoredFromBundle);
1932 }
1933 }
1934
1935 @Override
1936 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1937 synchronized (mGlobalLock) {
1938 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1939 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1940 return stack.mDisplayId;
1941 }
1942 return DEFAULT_DISPLAY;
1943 }
1944 }
1945
1946 @Override
1947 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 long ident = Binder.clearCallingIdentity();
1950 try {
1951 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001952 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001954 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 }
1956 return null;
1957 }
1958 } finally {
1959 Binder.restoreCallingIdentity(ident);
1960 }
1961 }
1962
1963 @Override
1964 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001965 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1967 final long callingId = Binder.clearCallingIdentity();
1968 try {
1969 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001970 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 if (stack == null) {
1972 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1973 return;
1974 }
1975 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001976 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001977 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 }
1979 }
1980 } finally {
1981 Binder.restoreCallingIdentity(callingId);
1982 }
1983 }
1984
1985 @Override
1986 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001987 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1989 final long callingId = Binder.clearCallingIdentity();
1990 try {
1991 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001992 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001993 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 if (task == null) {
1995 return;
1996 }
1997 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001998 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001999 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 }
2001 }
2002 } finally {
2003 Binder.restoreCallingIdentity(callingId);
2004 }
2005 }
2006
2007 @Override
2008 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 synchronized (mGlobalLock) {
2011 final long ident = Binder.clearCallingIdentity();
2012 try {
2013 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2014 "remove-task");
2015 } finally {
2016 Binder.restoreCallingIdentity(ident);
2017 }
2018 }
2019 }
2020
2021 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002022 public void removeAllVisibleRecentTasks() {
2023 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2024 synchronized (mGlobalLock) {
2025 final long ident = Binder.clearCallingIdentity();
2026 try {
2027 getRecentTasks().removeAllVisibleTasks();
2028 } finally {
2029 Binder.restoreCallingIdentity(ident);
2030 }
2031 }
2032 }
2033
2034 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2036 synchronized (mGlobalLock) {
2037 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2038 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002039 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 }
2042 return false;
2043 }
2044
2045 @Override
2046 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2047 Intent resultData) {
2048
2049 synchronized (mGlobalLock) {
2050 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2051 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002052 return r.getActivityStack().navigateUpToLocked(
2053 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 return false;
2056 }
2057 }
2058
2059 /**
2060 * Attempts to move a task backwards in z-order (the order of activities within the task is
2061 * unchanged).
2062 *
2063 * There are several possible results of this call:
2064 * - if the task is locked, then we will show the lock toast
2065 * - if there is a task behind the provided task, then that task is made visible and resumed as
2066 * this task is moved to the back
2067 * - otherwise, if there are no other tasks in the stack:
2068 * - if this task is in the pinned stack, then we remove the stack completely, which will
2069 * have the effect of moving the task to the top or bottom of the fullscreen stack
2070 * (depending on whether it is visible)
2071 * - otherwise, we simply return home and hide this task
2072 *
2073 * @param token A reference to the activity we wish to move
2074 * @param nonRoot If false then this only works if the activity is the root
2075 * of a task; if true it will work for any activity in a task.
2076 * @return Returns true if the move completed, false if not.
2077 */
2078 @Override
2079 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002080 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 synchronized (mGlobalLock) {
2082 final long origId = Binder.clearCallingIdentity();
2083 try {
2084 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002085 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 if (task != null) {
2087 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2088 }
2089 } finally {
2090 Binder.restoreCallingIdentity(origId);
2091 }
2092 }
2093 return false;
2094 }
2095
2096 @Override
2097 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002098 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 long ident = Binder.clearCallingIdentity();
2100 Rect rect = new Rect();
2101 try {
2102 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002103 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002104 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2105 if (task == null) {
2106 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2107 return rect;
2108 }
2109 if (task.getStack() != null) {
2110 // Return the bounds from window manager since it will be adjusted for various
2111 // things like the presense of a docked stack for tasks that aren't resizeable.
2112 task.getWindowContainerBounds(rect);
2113 } else {
2114 // Task isn't in window manager yet since it isn't associated with a stack.
2115 // Return the persist value from activity manager
2116 if (!task.matchParentBounds()) {
2117 rect.set(task.getBounds());
2118 } else if (task.mLastNonFullscreenBounds != null) {
2119 rect.set(task.mLastNonFullscreenBounds);
2120 }
2121 }
2122 }
2123 } finally {
2124 Binder.restoreCallingIdentity(ident);
2125 }
2126 return rect;
2127 }
2128
2129 @Override
2130 public ActivityManager.TaskDescription getTaskDescription(int id) {
2131 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002132 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002134 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002135 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2136 if (tr != null) {
2137 return tr.lastTaskDescription;
2138 }
2139 }
2140 return null;
2141 }
2142
2143 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002144 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2145 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2146 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2147 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2148 return;
2149 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002150 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002151 synchronized (mGlobalLock) {
2152 final long ident = Binder.clearCallingIdentity();
2153 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002154 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002155 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002156 if (task == null) {
2157 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2158 return;
2159 }
2160
2161 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2162 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2163
2164 if (!task.isActivityTypeStandardOrUndefined()) {
2165 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2166 + " non-standard task " + taskId + " to windowing mode="
2167 + windowingMode);
2168 }
2169
2170 final ActivityStack stack = task.getStack();
2171 if (toTop) {
2172 stack.moveToFront("setTaskWindowingMode", task);
2173 }
2174 stack.setWindowingMode(windowingMode);
2175 } finally {
2176 Binder.restoreCallingIdentity(ident);
2177 }
2178 }
2179 }
2180
2181 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002183 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 ActivityRecord r = getCallingRecordLocked(token);
2185 return r != null ? r.info.packageName : null;
2186 }
2187 }
2188
2189 @Override
2190 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 ActivityRecord r = getCallingRecordLocked(token);
2193 return r != null ? r.intent.getComponent() : null;
2194 }
2195 }
2196
2197 private ActivityRecord getCallingRecordLocked(IBinder token) {
2198 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2199 if (r == null) {
2200 return null;
2201 }
2202 return r.resultTo;
2203 }
2204
2205 @Override
2206 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002207 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002208
2209 synchronized (mGlobalLock) {
2210 final long origId = Binder.clearCallingIdentity();
2211 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002212 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 } finally {
2214 Binder.restoreCallingIdentity(origId);
2215 }
2216 }
2217 }
2218
2219 /**
2220 * TODO: Add mController hook
2221 */
2222 @Override
2223 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002224 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225
2226 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2227 synchronized (mGlobalLock) {
2228 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2229 false /* fromRecents */);
2230 }
2231 }
2232
2233 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2234 boolean fromRecents) {
2235
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002236 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 Binder.getCallingUid(), -1, -1, "Task to front")) {
2238 SafeActivityOptions.abort(options);
2239 return;
2240 }
2241 final long origId = Binder.clearCallingIdentity();
2242 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002243 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 if (task == null) {
2245 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002246 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 return;
2248 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002249 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002251 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002252 return;
2253 }
2254 ActivityOptions realOptions = options != null
2255 ? options.getOptions(mStackSupervisor)
2256 : null;
2257 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2258 false /* forceNonResizable */);
2259
2260 final ActivityRecord topActivity = task.getTopActivity();
2261 if (topActivity != null) {
2262
2263 // We are reshowing a task, use a starting window to hide the initial draw delay
2264 // so the transition can start earlier.
2265 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2266 true /* taskSwitch */, fromRecents);
2267 }
2268 } finally {
2269 Binder.restoreCallingIdentity(origId);
2270 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002271 }
2272
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002273 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2274 int callingPid, int callingUid, String name) {
2275 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2276 return true;
2277 }
2278
2279 if (getRecentTasks().isCallerRecents(sourceUid)) {
2280 return true;
2281 }
2282
2283 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2284 if (perm == PackageManager.PERMISSION_GRANTED) {
2285 return true;
2286 }
2287 if (checkAllowAppSwitchUid(sourceUid)) {
2288 return true;
2289 }
2290
2291 // If the actual IPC caller is different from the logical source, then
2292 // also see if they are allowed to control app switches.
2293 if (callingUid != -1 && callingUid != sourceUid) {
2294 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2295 if (perm == PackageManager.PERMISSION_GRANTED) {
2296 return true;
2297 }
2298 if (checkAllowAppSwitchUid(callingUid)) {
2299 return true;
2300 }
2301 }
2302
2303 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2304 return false;
2305 }
2306
2307 private boolean checkAllowAppSwitchUid(int uid) {
2308 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2309 if (types != null) {
2310 for (int i = types.size() - 1; i >= 0; i--) {
2311 if (types.valueAt(i).intValue() == uid) {
2312 return true;
2313 }
2314 }
2315 }
2316 return false;
2317 }
2318
2319 @Override
2320 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2321 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2322 "setActivityController()");
2323 synchronized (mGlobalLock) {
2324 mController = controller;
2325 mControllerIsAMonkey = imAMonkey;
2326 Watchdog.getInstance().setActivityController(controller);
2327 }
2328 }
2329
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002330 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002331 synchronized (mGlobalLock) {
2332 return mController != null && mControllerIsAMonkey;
2333 }
2334 }
2335
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336 @Override
2337 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2338 synchronized (mGlobalLock) {
2339 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2340 }
2341 }
2342
2343 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002344 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2345 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2346 }
2347
2348 @Override
2349 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2350 @WindowConfiguration.ActivityType int ignoreActivityType,
2351 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2352 final int callingUid = Binder.getCallingUid();
2353 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2354
2355 synchronized (mGlobalLock) {
2356 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2357
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002358 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002359 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002360 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002361 ignoreWindowingMode, callingUid, allowed);
2362 }
2363
2364 return list;
2365 }
2366
2367 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2369 synchronized (mGlobalLock) {
2370 final long origId = Binder.clearCallingIdentity();
2371 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2372 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002373 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 }
2375 Binder.restoreCallingIdentity(origId);
2376 }
2377 }
2378
2379 @Override
2380 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002381 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 ActivityStack stack = ActivityRecord.getStackLocked(token);
2383 if (stack != null) {
2384 return stack.willActivityBeVisibleLocked(token);
2385 }
2386 return false;
2387 }
2388 }
2389
2390 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002391 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002392 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002393 synchronized (mGlobalLock) {
2394 final long ident = Binder.clearCallingIdentity();
2395 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002396 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002397 if (task == null) {
2398 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2399 return;
2400 }
2401
2402 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2403 + " to stackId=" + stackId + " toTop=" + toTop);
2404
Wale Ogunwaled32da472018-11-16 07:19:28 -08002405 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002406 if (stack == null) {
2407 throw new IllegalStateException(
2408 "moveTaskToStack: No stack for stackId=" + stackId);
2409 }
2410 if (!stack.isActivityTypeStandardOrUndefined()) {
2411 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2412 + taskId + " to stack " + stackId);
2413 }
2414 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002416 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2417 }
2418 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2419 "moveTaskToStack");
2420 } finally {
2421 Binder.restoreCallingIdentity(ident);
2422 }
2423 }
2424 }
2425
2426 @Override
2427 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2428 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002429 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002430
2431 final long ident = Binder.clearCallingIdentity();
2432 try {
2433 synchronized (mGlobalLock) {
2434 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002435 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002436 if (stack == null) {
2437 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2438 return;
2439 }
2440 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2441 throw new IllegalArgumentException("Stack: " + stackId
2442 + " doesn't support animated resize.");
2443 }
2444 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2445 animationDuration, false /* fromFullscreen */);
2446 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002447 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002448 if (stack == null) {
2449 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2450 return;
2451 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002452 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002453 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2454 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2455 }
2456 }
2457 } finally {
2458 Binder.restoreCallingIdentity(ident);
2459 }
2460 }
2461
wilsonshih5c4cf522019-01-25 09:03:47 +08002462 @Override
2463 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2464 int animationDuration) {
2465 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2466
2467 final long ident = Binder.clearCallingIdentity();
2468 try {
2469 synchronized (mGlobalLock) {
2470 if (xOffset == 0 && yOffset == 0) {
2471 return;
2472 }
2473 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2474 if (stack == null) {
2475 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2476 return;
2477 }
2478 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2479 throw new IllegalArgumentException("Stack: " + stackId
2480 + " doesn't support animated resize.");
2481 }
2482 final Rect destBounds = new Rect();
2483 stack.getAnimationOrCurrentBounds(destBounds);
2484 if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
2485 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2486 return;
2487 }
2488 destBounds.offset(xOffset, yOffset);
2489 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2490 animationDuration, false /* fromFullscreen */);
2491 }
2492 } finally {
2493 Binder.restoreCallingIdentity(ident);
2494 }
2495 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002496 /**
2497 * Moves the specified task to the primary-split-screen stack.
2498 *
2499 * @param taskId Id of task to move.
2500 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2501 * exist already. See
2502 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2503 * and
2504 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2505 * @param toTop If the task and stack should be moved to the top.
2506 * @param animate Whether we should play an animation for the moving the task.
2507 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2508 * stack. Pass {@code null} to use default bounds.
2509 * @param showRecents If the recents activity should be shown on the other side of the task
2510 * going into split-screen mode.
2511 */
2512 @Override
2513 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2514 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002515 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002516 "setTaskWindowingModeSplitScreenPrimary()");
2517 synchronized (mGlobalLock) {
2518 final long ident = Binder.clearCallingIdentity();
2519 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002520 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002521 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002522 if (task == null) {
2523 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2524 return false;
2525 }
2526 if (DEBUG_STACK) Slog.d(TAG_STACK,
2527 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2528 + " to createMode=" + createMode + " toTop=" + toTop);
2529 if (!task.isActivityTypeStandardOrUndefined()) {
2530 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2531 + " non-standard task " + taskId + " to split-screen windowing mode");
2532 }
2533
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002534 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 final int windowingMode = task.getWindowingMode();
2536 final ActivityStack stack = task.getStack();
2537 if (toTop) {
2538 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2539 }
2540 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002541 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2542 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 return windowingMode != task.getWindowingMode();
2544 } finally {
2545 Binder.restoreCallingIdentity(ident);
2546 }
2547 }
2548 }
2549
2550 /**
2551 * Removes stacks in the input windowing modes from the system if they are of activity type
2552 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2553 */
2554 @Override
2555 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002556 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 "removeStacksInWindowingModes()");
2558
2559 synchronized (mGlobalLock) {
2560 final long ident = Binder.clearCallingIdentity();
2561 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002562 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 } finally {
2564 Binder.restoreCallingIdentity(ident);
2565 }
2566 }
2567 }
2568
2569 @Override
2570 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572 "removeStacksWithActivityTypes()");
2573
2574 synchronized (mGlobalLock) {
2575 final long ident = Binder.clearCallingIdentity();
2576 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002577 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 } finally {
2579 Binder.restoreCallingIdentity(ident);
2580 }
2581 }
2582 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583
2584 @Override
2585 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2586 int userId) {
2587 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002588 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2589 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002590 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002591 final boolean detailed = checkGetTasksPermission(
2592 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2593 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002594 == PackageManager.PERMISSION_GRANTED;
2595
2596 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002597 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 callingUid);
2599 }
2600 }
2601
2602 @Override
2603 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002604 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002605 long ident = Binder.clearCallingIdentity();
2606 try {
2607 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002608 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002609 }
2610 } finally {
2611 Binder.restoreCallingIdentity(ident);
2612 }
2613 }
2614
2615 @Override
2616 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002617 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002618 long ident = Binder.clearCallingIdentity();
2619 try {
2620 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002621 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002622 }
2623 } finally {
2624 Binder.restoreCallingIdentity(ident);
2625 }
2626 }
2627
2628 @Override
2629 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002630 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002631 final long callingUid = Binder.getCallingUid();
2632 final long origId = Binder.clearCallingIdentity();
2633 try {
2634 synchronized (mGlobalLock) {
2635 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002636 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002637 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2638 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2639 }
2640 } finally {
2641 Binder.restoreCallingIdentity(origId);
2642 }
2643 }
2644
2645 @Override
2646 public void startLockTaskModeByToken(IBinder token) {
2647 synchronized (mGlobalLock) {
2648 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2649 if (r == null) {
2650 return;
2651 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002652 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002653 }
2654 }
2655
2656 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002657 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002658 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002659 // This makes inner call to look as if it was initiated by system.
2660 long ident = Binder.clearCallingIdentity();
2661 try {
2662 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002663 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002664 MATCH_TASK_IN_STACKS_ONLY);
2665 if (task == null) {
2666 return;
2667 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002668
2669 // When starting lock task mode the stack must be in front and focused
2670 task.getStack().moveToFront("startSystemLockTaskMode");
2671 startLockTaskModeLocked(task, true /* isSystemCaller */);
2672 }
2673 } finally {
2674 Binder.restoreCallingIdentity(ident);
2675 }
2676 }
2677
2678 @Override
2679 public void stopLockTaskModeByToken(IBinder token) {
2680 synchronized (mGlobalLock) {
2681 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2682 if (r == null) {
2683 return;
2684 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002685 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002686 }
2687 }
2688
2689 /**
2690 * This API should be called by SystemUI only when user perform certain action to dismiss
2691 * lock task mode. We should only dismiss pinned lock task mode in this case.
2692 */
2693 @Override
2694 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002695 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002696 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2697 }
2698
2699 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2700 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2701 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2702 return;
2703 }
2704
Wale Ogunwaled32da472018-11-16 07:19:28 -08002705 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002706 if (stack == null || task != stack.topTask()) {
2707 throw new IllegalArgumentException("Invalid task, not in foreground");
2708 }
2709
2710 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2711 // system or a specific app.
2712 // * System-initiated requests will only start the pinned mode (screen pinning)
2713 // * App-initiated requests
2714 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2715 // - will start the pinned mode, otherwise
2716 final int callingUid = Binder.getCallingUid();
2717 long ident = Binder.clearCallingIdentity();
2718 try {
2719 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002720 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002722 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002723 } finally {
2724 Binder.restoreCallingIdentity(ident);
2725 }
2726 }
2727
2728 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2729 final int callingUid = Binder.getCallingUid();
2730 long ident = Binder.clearCallingIdentity();
2731 try {
2732 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002733 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002734 }
2735 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2736 // task and jumping straight into a call in the case of emergency call back.
2737 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2738 if (tm != null) {
2739 tm.showInCallScreen(false);
2740 }
2741 } finally {
2742 Binder.restoreCallingIdentity(ident);
2743 }
2744 }
2745
2746 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002747 public void updateLockTaskPackages(int userId, String[] packages) {
2748 final int callingUid = Binder.getCallingUid();
2749 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2750 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2751 "updateLockTaskPackages()");
2752 }
2753 synchronized (this) {
2754 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2755 + Arrays.toString(packages));
2756 getLockTaskController().updateLockTaskPackages(userId, packages);
2757 }
2758 }
2759
2760 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 public boolean isInLockTaskMode() {
2762 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2763 }
2764
2765 @Override
2766 public int getLockTaskModeState() {
2767 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002768 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 }
2770 }
2771
2772 @Override
2773 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2774 synchronized (mGlobalLock) {
2775 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2776 if (r != null) {
2777 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002778 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002780 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002781 }
2782 }
2783 }
2784
2785 @Override
2786 public Bundle getActivityOptions(IBinder token) {
2787 final long origId = Binder.clearCallingIdentity();
2788 try {
2789 synchronized (mGlobalLock) {
2790 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2791 if (r != null) {
2792 final ActivityOptions activityOptions = r.takeOptionsLocked();
2793 return activityOptions == null ? null : activityOptions.toBundle();
2794 }
2795 return null;
2796 }
2797 } finally {
2798 Binder.restoreCallingIdentity(origId);
2799 }
2800 }
2801
2802 @Override
2803 public List<IBinder> getAppTasks(String callingPackage) {
2804 int callingUid = Binder.getCallingUid();
2805 long ident = Binder.clearCallingIdentity();
2806 try {
2807 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002808 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810 } finally {
2811 Binder.restoreCallingIdentity(ident);
2812 }
2813 }
2814
2815 @Override
2816 public void finishVoiceTask(IVoiceInteractionSession session) {
2817 synchronized (mGlobalLock) {
2818 final long origId = Binder.clearCallingIdentity();
2819 try {
2820 // TODO: VI Consider treating local voice interactions and voice tasks
2821 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002822 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 } finally {
2824 Binder.restoreCallingIdentity(origId);
2825 }
2826 }
2827
2828 }
2829
2830 @Override
2831 public boolean isTopOfTask(IBinder token) {
2832 synchronized (mGlobalLock) {
2833 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002834 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835 }
2836 }
2837
2838 @Override
2839 public void notifyLaunchTaskBehindComplete(IBinder token) {
2840 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2841 }
2842
2843 @Override
2844 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002845 mH.post(() -> {
2846 synchronized (mGlobalLock) {
2847 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002848 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002849 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002850 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002851 } catch (RemoteException e) {
2852 }
2853 }
2854 }
2855
2856 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 }
2858
2859 /** Called from an app when assist data is ready. */
2860 @Override
2861 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2862 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002863 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 synchronized (pae) {
2865 pae.result = extras;
2866 pae.structure = structure;
2867 pae.content = content;
2868 if (referrer != null) {
2869 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2870 }
2871 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002872 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002873 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2874 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875 structure.setHomeActivity(pae.isHome);
2876 }
2877 pae.haveResult = true;
2878 pae.notifyAll();
2879 if (pae.intent == null && pae.receiver == null) {
2880 // Caller is just waiting for the result.
2881 return;
2882 }
2883 }
2884 // We are now ready to launch the assist activity.
2885 IAssistDataReceiver sendReceiver = null;
2886 Bundle sendBundle = null;
2887 synchronized (mGlobalLock) {
2888 buildAssistBundleLocked(pae, extras);
2889 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002890 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 if (!exists) {
2892 // Timed out.
2893 return;
2894 }
2895
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002896 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 // Caller wants result sent back to them.
2898 sendBundle = new Bundle();
2899 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2900 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2901 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2902 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2903 }
2904 }
2905 if (sendReceiver != null) {
2906 try {
2907 sendReceiver.onHandleAssistData(sendBundle);
2908 } catch (RemoteException e) {
2909 }
2910 return;
2911 }
2912
2913 final long ident = Binder.clearCallingIdentity();
2914 try {
2915 if (TextUtils.equals(pae.intent.getAction(),
2916 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2917 pae.intent.putExtras(pae.extras);
2918 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2919 } else {
2920 pae.intent.replaceExtras(pae.extras);
2921 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2922 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2923 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002924 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925
2926 try {
2927 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2928 } catch (ActivityNotFoundException e) {
2929 Slog.w(TAG, "No activity to handle assist action.", e);
2930 }
2931 }
2932 } finally {
2933 Binder.restoreCallingIdentity(ident);
2934 }
2935 }
2936
2937 @Override
2938 public int addAppTask(IBinder activityToken, Intent intent,
2939 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2940 final int callingUid = Binder.getCallingUid();
2941 final long callingIdent = Binder.clearCallingIdentity();
2942
2943 try {
2944 synchronized (mGlobalLock) {
2945 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2946 if (r == null) {
2947 throw new IllegalArgumentException("Activity does not exist; token="
2948 + activityToken);
2949 }
2950 ComponentName comp = intent.getComponent();
2951 if (comp == null) {
2952 throw new IllegalArgumentException("Intent " + intent
2953 + " must specify explicit component");
2954 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002955 if (thumbnail.getWidth() != mThumbnailWidth
2956 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 throw new IllegalArgumentException("Bad thumbnail size: got "
2958 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002959 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002960 }
2961 if (intent.getSelector() != null) {
2962 intent.setSelector(null);
2963 }
2964 if (intent.getSourceBounds() != null) {
2965 intent.setSourceBounds(null);
2966 }
2967 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2968 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2969 // The caller has added this as an auto-remove task... that makes no
2970 // sense, so turn off auto-remove.
2971 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2972 }
2973 }
2974 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2975 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2976 if (ainfo.applicationInfo.uid != callingUid) {
2977 throw new SecurityException(
2978 "Can't add task for another application: target uid="
2979 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2980 }
2981
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002982 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002984 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002986 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002987 // The app has too many tasks already and we can't add any more
2988 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2989 return INVALID_TASK_ID;
2990 }
2991 task.lastTaskDescription.copyFrom(description);
2992
2993 // TODO: Send the thumbnail to WM to store it.
2994
2995 return task.taskId;
2996 }
2997 } finally {
2998 Binder.restoreCallingIdentity(callingIdent);
2999 }
3000 }
3001
3002 @Override
3003 public Point getAppTaskThumbnailSize() {
3004 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003005 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 }
3007 }
3008
3009 @Override
3010 public void setTaskResizeable(int taskId, int resizeableMode) {
3011 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003012 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3014 if (task == null) {
3015 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3016 return;
3017 }
3018 task.setResizeMode(resizeableMode);
3019 }
3020 }
3021
3022 @Override
3023 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003024 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 long ident = Binder.clearCallingIdentity();
3026 try {
3027 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003028 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003029 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 if (task == null) {
3031 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3032 return;
3033 }
3034 // Place the task in the right stack if it isn't there already based on
3035 // the requested bounds.
3036 // The stack transition logic is:
3037 // - a null bounds on a freeform task moves that task to fullscreen
3038 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3039 // that task to freeform
3040 // - otherwise the task is not moved
3041 ActivityStack stack = task.getStack();
3042 if (!task.getWindowConfiguration().canResizeTask()) {
3043 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3044 }
3045 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3046 stack = stack.getDisplay().getOrCreateStack(
3047 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3048 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3049 stack = stack.getDisplay().getOrCreateStack(
3050 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3051 }
3052
3053 // Reparent the task to the right stack if necessary
3054 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3055 if (stack != task.getStack()) {
3056 // Defer resume until the task is resized below
3057 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3058 DEFER_RESUME, "resizeTask");
3059 preserveWindow = false;
3060 }
3061
3062 // After reparenting (which only resizes the task to the stack bounds), resize the
3063 // task to the actual bounds provided
3064 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3065 }
3066 } finally {
3067 Binder.restoreCallingIdentity(ident);
3068 }
3069 }
3070
3071 @Override
3072 public boolean releaseActivityInstance(IBinder token) {
3073 synchronized (mGlobalLock) {
3074 final long origId = Binder.clearCallingIdentity();
3075 try {
3076 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3077 if (r == null) {
3078 return false;
3079 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003080 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 } finally {
3082 Binder.restoreCallingIdentity(origId);
3083 }
3084 }
3085 }
3086
3087 @Override
3088 public void releaseSomeActivities(IApplicationThread appInt) {
3089 synchronized (mGlobalLock) {
3090 final long origId = Binder.clearCallingIdentity();
3091 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003092 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003093 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003094 } finally {
3095 Binder.restoreCallingIdentity(origId);
3096 }
3097 }
3098 }
3099
3100 @Override
3101 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003102 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003103 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003104 != PackageManager.PERMISSION_GRANTED) {
3105 throw new SecurityException("Requires permission "
3106 + android.Manifest.permission.DEVICE_POWER);
3107 }
3108
3109 synchronized (mGlobalLock) {
3110 long ident = Binder.clearCallingIdentity();
3111 if (mKeyguardShown != keyguardShowing) {
3112 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003113 final Message msg = PooledLambda.obtainMessage(
3114 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3115 keyguardShowing);
3116 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 }
3118 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003119 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003120 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 } finally {
3122 Binder.restoreCallingIdentity(ident);
3123 }
3124 }
3125
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003126 mH.post(() -> {
3127 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3128 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3129 }
3130 });
3131 }
3132
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003133 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003134 mH.post(() -> {
3135 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3136 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3137 }
3138 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 }
3140
3141 @Override
3142 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003143 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3144 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145
3146 final File passedIconFile = new File(filePath);
3147 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3148 passedIconFile.getName());
3149 if (!legitIconFile.getPath().equals(filePath)
3150 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3151 throw new IllegalArgumentException("Bad file path: " + filePath
3152 + " passed for userId " + userId);
3153 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003154 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003155 }
3156
3157 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003158 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3160 final ActivityOptions activityOptions = safeOptions != null
3161 ? safeOptions.getOptions(mStackSupervisor)
3162 : null;
3163 if (activityOptions == null
3164 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3165 || activityOptions.getCustomInPlaceResId() == 0) {
3166 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3167 "with valid animation");
3168 }
lumark588a3e82018-07-20 18:53:54 +08003169 // Get top display of front most application.
3170 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3171 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003172 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3173 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3174 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003175 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003176 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003177 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 }
3179
3180 @Override
3181 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003182 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003183 synchronized (mGlobalLock) {
3184 final long ident = Binder.clearCallingIdentity();
3185 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003186 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 if (stack == null) {
3188 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3189 return;
3190 }
3191 if (!stack.isActivityTypeStandardOrUndefined()) {
3192 throw new IllegalArgumentException(
3193 "Removing non-standard stack is not allowed.");
3194 }
3195 mStackSupervisor.removeStack(stack);
3196 } finally {
3197 Binder.restoreCallingIdentity(ident);
3198 }
3199 }
3200 }
3201
3202 @Override
3203 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003204 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205
3206 synchronized (mGlobalLock) {
3207 final long ident = Binder.clearCallingIdentity();
3208 try {
3209 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3210 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003211 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 } finally {
3213 Binder.restoreCallingIdentity(ident);
3214 }
3215 }
3216 }
3217
3218 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 public void exitFreeformMode(IBinder token) {
3220 synchronized (mGlobalLock) {
3221 long ident = Binder.clearCallingIdentity();
3222 try {
3223 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3224 if (r == null) {
3225 throw new IllegalArgumentException(
3226 "exitFreeformMode: No activity record matching token=" + token);
3227 }
3228
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003229 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003230 if (stack == null || !stack.inFreeformWindowingMode()) {
3231 throw new IllegalStateException(
3232 "exitFreeformMode: You can only go fullscreen from freeform.");
3233 }
3234
3235 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3236 } finally {
3237 Binder.restoreCallingIdentity(ident);
3238 }
3239 }
3240 }
3241
3242 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3243 @Override
3244 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003247 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003248 }
3249
3250 /** Unregister a task stack listener so that it stops receiving callbacks. */
3251 @Override
3252 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003253 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003255 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003256 }
3257
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 @Override
3259 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3260 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3261 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3262 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3263 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3264 }
3265
3266 @Override
3267 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3268 IBinder activityToken, int flags) {
3269 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3270 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3271 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3272 }
3273
3274 @Override
3275 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3276 Bundle args) {
3277 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3278 true /* focused */, true /* newSessionId */, userHandle, args,
3279 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3280 }
3281
3282 @Override
3283 public Bundle getAssistContextExtras(int requestType) {
3284 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3285 null, null, true /* focused */, true /* newSessionId */,
3286 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3287 if (pae == null) {
3288 return null;
3289 }
3290 synchronized (pae) {
3291 while (!pae.haveResult) {
3292 try {
3293 pae.wait();
3294 } catch (InterruptedException e) {
3295 }
3296 }
3297 }
3298 synchronized (mGlobalLock) {
3299 buildAssistBundleLocked(pae, pae.result);
3300 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003301 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 }
3303 return pae.extras;
3304 }
3305
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003306 /**
3307 * Binder IPC calls go through the public entry point.
3308 * This can be called with or without the global lock held.
3309 */
3310 private static int checkCallingPermission(String permission) {
3311 return checkPermission(
3312 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3313 }
3314
3315 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003316 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003317 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3318 mAmInternal.enforceCallingPermission(permission, func);
3319 }
3320 }
3321
3322 @VisibleForTesting
3323 int checkGetTasksPermission(String permission, int pid, int uid) {
3324 return checkPermission(permission, pid, uid);
3325 }
3326
3327 static int checkPermission(String permission, int pid, int uid) {
3328 if (permission == null) {
3329 return PackageManager.PERMISSION_DENIED;
3330 }
3331 return checkComponentPermission(permission, pid, uid, -1, true);
3332 }
3333
Wale Ogunwale214f3482018-10-04 11:00:47 -07003334 public static int checkComponentPermission(String permission, int pid, int uid,
3335 int owningUid, boolean exported) {
3336 return ActivityManagerService.checkComponentPermission(
3337 permission, pid, uid, owningUid, exported);
3338 }
3339
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003340 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3341 if (getRecentTasks().isCallerRecents(callingUid)) {
3342 // Always allow the recents component to get tasks
3343 return true;
3344 }
3345
3346 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3347 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3348 if (!allowed) {
3349 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3350 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3351 // Temporary compatibility: some existing apps on the system image may
3352 // still be requesting the old permission and not switched to the new
3353 // one; if so, we'll still allow them full access. This means we need
3354 // to see if they are holding the old permission and are a system app.
3355 try {
3356 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3357 allowed = true;
3358 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3359 + " is using old GET_TASKS but privileged; allowing");
3360 }
3361 } catch (RemoteException e) {
3362 }
3363 }
3364 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3365 + " does not hold REAL_GET_TASKS; limiting output");
3366 }
3367 return allowed;
3368 }
3369
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3371 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3372 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3373 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003374 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 "enqueueAssistContext()");
3376
3377 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003378 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 if (activity == null) {
3380 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3381 return null;
3382 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003383 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3385 return null;
3386 }
3387 if (focused) {
3388 if (activityToken != null) {
3389 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3390 if (activity != caller) {
3391 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3392 + " is not current top " + activity);
3393 return null;
3394 }
3395 }
3396 } else {
3397 activity = ActivityRecord.forTokenLocked(activityToken);
3398 if (activity == null) {
3399 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3400 + " couldn't be found");
3401 return null;
3402 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003403 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3405 return null;
3406 }
3407 }
3408
3409 PendingAssistExtras pae;
3410 Bundle extras = new Bundle();
3411 if (args != null) {
3412 extras.putAll(args);
3413 }
3414 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003415 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416
3417 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3418 userHandle);
3419 pae.isHome = activity.isActivityTypeHome();
3420
3421 // Increment the sessionId if necessary
3422 if (newSessionId) {
3423 mViSessionId++;
3424 }
3425 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003426 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3427 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003429 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 } catch (RemoteException e) {
3431 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3432 return null;
3433 }
3434 return pae;
3435 }
3436 }
3437
3438 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3439 if (result != null) {
3440 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3441 }
3442 if (pae.hint != null) {
3443 pae.extras.putBoolean(pae.hint, true);
3444 }
3445 }
3446
3447 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3448 IAssistDataReceiver receiver;
3449 synchronized (mGlobalLock) {
3450 mPendingAssistExtras.remove(pae);
3451 receiver = pae.receiver;
3452 }
3453 if (receiver != null) {
3454 // Caller wants result sent back to them.
3455 Bundle sendBundle = new Bundle();
3456 // At least return the receiver extras
3457 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3458 try {
3459 pae.receiver.onHandleAssistData(sendBundle);
3460 } catch (RemoteException e) {
3461 }
3462 }
3463 }
3464
3465 public class PendingAssistExtras extends Binder implements Runnable {
3466 public final ActivityRecord activity;
3467 public boolean isHome;
3468 public final Bundle extras;
3469 public final Intent intent;
3470 public final String hint;
3471 public final IAssistDataReceiver receiver;
3472 public final int userHandle;
3473 public boolean haveResult = false;
3474 public Bundle result = null;
3475 public AssistStructure structure = null;
3476 public AssistContent content = null;
3477 public Bundle receiverExtras;
3478
3479 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3480 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3481 int _userHandle) {
3482 activity = _activity;
3483 extras = _extras;
3484 intent = _intent;
3485 hint = _hint;
3486 receiver = _receiver;
3487 receiverExtras = _receiverExtras;
3488 userHandle = _userHandle;
3489 }
3490
3491 @Override
3492 public void run() {
3493 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3494 synchronized (this) {
3495 haveResult = true;
3496 notifyAll();
3497 }
3498 pendingAssistExtrasTimedOut(this);
3499 }
3500 }
3501
3502 @Override
3503 public boolean isAssistDataAllowedOnCurrentActivity() {
3504 int userId;
3505 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003506 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3508 return false;
3509 }
3510
3511 final ActivityRecord activity = focusedStack.getTopActivity();
3512 if (activity == null) {
3513 return false;
3514 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003515 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003516 }
3517 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3518 }
3519
3520 @Override
3521 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3522 long ident = Binder.clearCallingIdentity();
3523 try {
3524 synchronized (mGlobalLock) {
3525 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003526 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 if (top != caller) {
3528 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3529 + " is not current top " + top);
3530 return false;
3531 }
3532 if (!top.nowVisible) {
3533 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3534 + " is not visible");
3535 return false;
3536 }
3537 }
3538 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3539 token);
3540 } finally {
3541 Binder.restoreCallingIdentity(ident);
3542 }
3543 }
3544
3545 @Override
3546 public boolean isRootVoiceInteraction(IBinder token) {
3547 synchronized (mGlobalLock) {
3548 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3549 if (r == null) {
3550 return false;
3551 }
3552 return r.rootVoiceInteraction;
3553 }
3554 }
3555
Wale Ogunwalef6733932018-06-27 05:14:34 -07003556 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3557 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3558 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3559 if (activityToCallback == null) return;
3560 activityToCallback.setVoiceSessionLocked(voiceSession);
3561
3562 // Inform the activity
3563 try {
3564 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3565 voiceInteractor);
3566 long token = Binder.clearCallingIdentity();
3567 try {
3568 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3569 } finally {
3570 Binder.restoreCallingIdentity(token);
3571 }
3572 // TODO: VI Should we cache the activity so that it's easier to find later
3573 // rather than scan through all the stacks and activities?
3574 } catch (RemoteException re) {
3575 activityToCallback.clearVoiceSessionLocked();
3576 // TODO: VI Should this terminate the voice session?
3577 }
3578 }
3579
3580 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3581 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3582 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3583 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3584 boolean wasRunningVoice = mRunningVoice != null;
3585 mRunningVoice = session;
3586 if (!wasRunningVoice) {
3587 mVoiceWakeLock.acquire();
3588 updateSleepIfNeededLocked();
3589 }
3590 }
3591 }
3592
3593 void finishRunningVoiceLocked() {
3594 if (mRunningVoice != null) {
3595 mRunningVoice = null;
3596 mVoiceWakeLock.release();
3597 updateSleepIfNeededLocked();
3598 }
3599 }
3600
3601 @Override
3602 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3603 synchronized (mGlobalLock) {
3604 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3605 if (keepAwake) {
3606 mVoiceWakeLock.acquire();
3607 } else {
3608 mVoiceWakeLock.release();
3609 }
3610 }
3611 }
3612 }
3613
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 @Override
3615 public ComponentName getActivityClassForToken(IBinder token) {
3616 synchronized (mGlobalLock) {
3617 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3618 if (r == null) {
3619 return null;
3620 }
3621 return r.intent.getComponent();
3622 }
3623 }
3624
3625 @Override
3626 public String getPackageForToken(IBinder token) {
3627 synchronized (mGlobalLock) {
3628 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3629 if (r == null) {
3630 return null;
3631 }
3632 return r.packageName;
3633 }
3634 }
3635
3636 @Override
3637 public void showLockTaskEscapeMessage(IBinder token) {
3638 synchronized (mGlobalLock) {
3639 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3640 if (r == null) {
3641 return;
3642 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003643 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644 }
3645 }
3646
3647 @Override
3648 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003649 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 final long token = Binder.clearCallingIdentity();
3651 try {
3652 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003653 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 }
3655 } finally {
3656 Binder.restoreCallingIdentity(token);
3657 }
3658 }
3659
3660 /**
3661 * Try to place task to provided position. The final position might be different depending on
3662 * current user and stacks state. The task will be moved to target stack if it's currently in
3663 * different stack.
3664 */
3665 @Override
3666 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003667 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 synchronized (mGlobalLock) {
3669 long ident = Binder.clearCallingIdentity();
3670 try {
3671 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3672 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003673 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003674 if (task == null) {
3675 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3676 + taskId);
3677 }
3678
Wale Ogunwaled32da472018-11-16 07:19:28 -08003679 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680
3681 if (stack == null) {
3682 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3683 + stackId);
3684 }
3685 if (!stack.isActivityTypeStandardOrUndefined()) {
3686 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3687 + " the position of task " + taskId + " in/to non-standard stack");
3688 }
3689
3690 // TODO: Have the callers of this API call a separate reparent method if that is
3691 // what they intended to do vs. having this method also do reparenting.
3692 if (task.getStack() == stack) {
3693 // Change position in current stack.
3694 stack.positionChildAt(task, position);
3695 } else {
3696 // Reparent to new stack.
3697 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3698 !DEFER_RESUME, "positionTaskInStack");
3699 }
3700 } finally {
3701 Binder.restoreCallingIdentity(ident);
3702 }
3703 }
3704 }
3705
3706 @Override
3707 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3708 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3709 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3710 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3711 synchronized (mGlobalLock) {
3712 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3713 if (record == null) {
3714 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3715 + "found for: " + token);
3716 }
3717 record.setSizeConfigurations(horizontalSizeConfiguration,
3718 verticalSizeConfigurations, smallestSizeConfigurations);
3719 }
3720 }
3721
3722 /**
3723 * Dismisses split-screen multi-window mode.
3724 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3725 */
3726 @Override
3727 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003728 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003729 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3730 final long ident = Binder.clearCallingIdentity();
3731 try {
3732 synchronized (mGlobalLock) {
3733 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003734 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003735 if (stack == null) {
3736 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3737 return;
3738 }
3739
3740 if (toTop) {
3741 // Caller wants the current split-screen primary stack to be the top stack after
3742 // it goes fullscreen, so move it to the front.
3743 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003744 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003745 // In this case the current split-screen primary stack shouldn't be the top
3746 // stack after it goes fullscreen, but it current has focus, so we move the
3747 // focus to the top-most split-screen secondary stack next to it.
3748 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3749 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3750 if (otherStack != null) {
3751 otherStack.moveToFront("dismissSplitScreenMode_other");
3752 }
3753 }
3754
Evan Rosky10475742018-09-05 19:02:48 -07003755 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003756 }
3757 } finally {
3758 Binder.restoreCallingIdentity(ident);
3759 }
3760 }
3761
3762 /**
3763 * Dismisses Pip
3764 * @param animate True if the dismissal should be animated.
3765 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3766 * default animation duration should be used.
3767 */
3768 @Override
3769 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003770 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003771 final long ident = Binder.clearCallingIdentity();
3772 try {
3773 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003774 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003775 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003776 if (stack == null) {
3777 Slog.w(TAG, "dismissPip: pinned stack not found.");
3778 return;
3779 }
3780 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3781 throw new IllegalArgumentException("Stack: " + stack
3782 + " doesn't support animated resize.");
3783 }
3784 if (animate) {
3785 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3786 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3787 } else {
3788 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3789 }
3790 }
3791 } finally {
3792 Binder.restoreCallingIdentity(ident);
3793 }
3794 }
3795
3796 @Override
3797 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003798 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003799 synchronized (mGlobalLock) {
3800 mSuppressResizeConfigChanges = suppress;
3801 }
3802 }
3803
3804 /**
3805 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3806 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3807 * activity and clearing the task at the same time.
3808 */
3809 @Override
3810 // TODO: API should just be about changing windowing modes...
3811 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003812 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003813 "moveTasksToFullscreenStack()");
3814 synchronized (mGlobalLock) {
3815 final long origId = Binder.clearCallingIdentity();
3816 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003817 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818 if (stack != null){
3819 if (!stack.isActivityTypeStandardOrUndefined()) {
3820 throw new IllegalArgumentException(
3821 "You can't move tasks from non-standard stacks.");
3822 }
3823 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3824 }
3825 } finally {
3826 Binder.restoreCallingIdentity(origId);
3827 }
3828 }
3829 }
3830
3831 /**
3832 * Moves the top activity in the input stackId to the pinned stack.
3833 *
3834 * @param stackId Id of stack to move the top activity to pinned stack.
3835 * @param bounds Bounds to use for pinned stack.
3836 *
3837 * @return True if the top activity of the input stack was successfully moved to the pinned
3838 * stack.
3839 */
3840 @Override
3841 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003842 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 "moveTopActivityToPinnedStack()");
3844 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003845 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3847 + "Device doesn't support picture-in-picture mode");
3848 }
3849
3850 long ident = Binder.clearCallingIdentity();
3851 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003852 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003853 } finally {
3854 Binder.restoreCallingIdentity(ident);
3855 }
3856 }
3857 }
3858
3859 @Override
3860 public boolean isInMultiWindowMode(IBinder token) {
3861 final long origId = Binder.clearCallingIdentity();
3862 try {
3863 synchronized (mGlobalLock) {
3864 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3865 if (r == null) {
3866 return false;
3867 }
3868 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3869 return r.inMultiWindowMode();
3870 }
3871 } finally {
3872 Binder.restoreCallingIdentity(origId);
3873 }
3874 }
3875
3876 @Override
3877 public boolean isInPictureInPictureMode(IBinder token) {
3878 final long origId = Binder.clearCallingIdentity();
3879 try {
3880 synchronized (mGlobalLock) {
3881 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3882 }
3883 } finally {
3884 Binder.restoreCallingIdentity(origId);
3885 }
3886 }
3887
3888 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003889 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3890 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 return false;
3892 }
3893
3894 // If we are animating to fullscreen then we have already dispatched the PIP mode
3895 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003896 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3897 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 }
3899
3900 @Override
3901 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3902 final long origId = Binder.clearCallingIdentity();
3903 try {
3904 synchronized (mGlobalLock) {
3905 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3906 "enterPictureInPictureMode", token, params);
3907
3908 // If the activity is already in picture in picture mode, then just return early
3909 if (isInPictureInPictureMode(r)) {
3910 return true;
3911 }
3912
3913 // Activity supports picture-in-picture, now check that we can enter PiP at this
3914 // point, if it is
3915 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3916 false /* beforeStopping */)) {
3917 return false;
3918 }
3919
3920 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003921 synchronized (mGlobalLock) {
3922 // Only update the saved args from the args that are set
3923 r.pictureInPictureArgs.copyOnlySet(params);
3924 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3925 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3926 // Adjust the source bounds by the insets for the transition down
3927 final Rect sourceBounds = new Rect(
3928 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003929 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003930 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003931 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003932 stack.setPictureInPictureAspectRatio(aspectRatio);
3933 stack.setPictureInPictureActions(actions);
3934 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3935 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3936 logPictureInPictureArgs(params);
3937 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 };
3939
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003940 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 // If the keyguard is showing or occluded, then try and dismiss it before
3942 // entering picture-in-picture (this will prompt the user to authenticate if the
3943 // device is currently locked).
3944 dismissKeyguard(token, new KeyguardDismissCallback() {
3945 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003946 public void onDismissSucceeded() {
3947 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 }
3949 }, null /* message */);
3950 } else {
3951 // Enter picture in picture immediately otherwise
3952 enterPipRunnable.run();
3953 }
3954 return true;
3955 }
3956 } finally {
3957 Binder.restoreCallingIdentity(origId);
3958 }
3959 }
3960
3961 @Override
3962 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3963 final long origId = Binder.clearCallingIdentity();
3964 try {
3965 synchronized (mGlobalLock) {
3966 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3967 "setPictureInPictureParams", token, params);
3968
3969 // Only update the saved args from the args that are set
3970 r.pictureInPictureArgs.copyOnlySet(params);
3971 if (r.inPinnedWindowingMode()) {
3972 // If the activity is already in picture-in-picture, update the pinned stack now
3973 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3974 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003975 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 if (!stack.isAnimatingBoundsToFullscreen()) {
3977 stack.setPictureInPictureAspectRatio(
3978 r.pictureInPictureArgs.getAspectRatio());
3979 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3980 }
3981 }
3982 logPictureInPictureArgs(params);
3983 }
3984 } finally {
3985 Binder.restoreCallingIdentity(origId);
3986 }
3987 }
3988
3989 @Override
3990 public int getMaxNumPictureInPictureActions(IBinder token) {
3991 // Currently, this is a static constant, but later, we may change this to be dependent on
3992 // the context of the activity
3993 return 3;
3994 }
3995
3996 private void logPictureInPictureArgs(PictureInPictureParams params) {
3997 if (params.hasSetActions()) {
3998 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3999 params.getActions().size());
4000 }
4001 if (params.hasSetAspectRatio()) {
4002 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4003 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4004 MetricsLogger.action(lm);
4005 }
4006 }
4007
4008 /**
4009 * Checks the state of the system and the activity associated with the given {@param token} to
4010 * verify that picture-in-picture is supported for that activity.
4011 *
4012 * @return the activity record for the given {@param token} if all the checks pass.
4013 */
4014 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4015 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004016 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004017 throw new IllegalStateException(caller
4018 + ": Device doesn't support picture-in-picture mode.");
4019 }
4020
4021 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4022 if (r == null) {
4023 throw new IllegalStateException(caller
4024 + ": Can't find activity for token=" + token);
4025 }
4026
4027 if (!r.supportsPictureInPicture()) {
4028 throw new IllegalStateException(caller
4029 + ": Current activity does not support picture-in-picture.");
4030 }
4031
4032 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004033 && !mWindowManager.isValidPictureInPictureAspectRatio(
4034 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 final float minAspectRatio = mContext.getResources().getFloat(
4036 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4037 final float maxAspectRatio = mContext.getResources().getFloat(
4038 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4039 throw new IllegalArgumentException(String.format(caller
4040 + ": Aspect ratio is too extreme (must be between %f and %f).",
4041 minAspectRatio, maxAspectRatio));
4042 }
4043
4044 // Truncate the number of actions if necessary
4045 params.truncateActions(getMaxNumPictureInPictureActions(token));
4046
4047 return r;
4048 }
4049
4050 @Override
4051 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 synchronized (mGlobalLock) {
4054 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4055 if (r == null) {
4056 throw new IllegalArgumentException("Activity does not exist; token="
4057 + activityToken);
4058 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004059 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 }
4061 }
4062
4063 @Override
4064 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4065 Rect tempDockedTaskInsetBounds,
4066 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004067 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 long ident = Binder.clearCallingIdentity();
4069 try {
4070 synchronized (mGlobalLock) {
4071 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4072 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4073 PRESERVE_WINDOWS);
4074 }
4075 } finally {
4076 Binder.restoreCallingIdentity(ident);
4077 }
4078 }
4079
4080 @Override
4081 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004082 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 final long ident = Binder.clearCallingIdentity();
4084 try {
4085 synchronized (mGlobalLock) {
4086 mStackSupervisor.setSplitScreenResizing(resizing);
4087 }
4088 } finally {
4089 Binder.restoreCallingIdentity(ident);
4090 }
4091 }
4092
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004093 /**
4094 * Check that we have the features required for VR-related API calls, and throw an exception if
4095 * not.
4096 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004097 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004098 if (!mContext.getPackageManager().hasSystemFeature(
4099 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4100 throw new UnsupportedOperationException("VR mode not supported on this device!");
4101 }
4102 }
4103
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004104 @Override
4105 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004106 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107
4108 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4109
4110 ActivityRecord r;
4111 synchronized (mGlobalLock) {
4112 r = ActivityRecord.isInStackLocked(token);
4113 }
4114
4115 if (r == null) {
4116 throw new IllegalArgumentException();
4117 }
4118
4119 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004120 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 VrManagerInternal.NO_ERROR) {
4122 return err;
4123 }
4124
4125 // Clear the binder calling uid since this path may call moveToTask().
4126 final long callingId = Binder.clearCallingIdentity();
4127 try {
4128 synchronized (mGlobalLock) {
4129 r.requestedVrComponent = (enabled) ? packageName : null;
4130
4131 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004132 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004133 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004134 }
4135 return 0;
4136 }
4137 } finally {
4138 Binder.restoreCallingIdentity(callingId);
4139 }
4140 }
4141
4142 @Override
4143 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4144 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4145 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004146 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4148 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4149 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004150 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 || activity.voiceSession != null) {
4152 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4153 return;
4154 }
4155 if (activity.pendingVoiceInteractionStart) {
4156 Slog.w(TAG, "Pending start of voice interaction already.");
4157 return;
4158 }
4159 activity.pendingVoiceInteractionStart = true;
4160 }
4161 LocalServices.getService(VoiceInteractionManagerInternal.class)
4162 .startLocalVoiceInteraction(callingActivity, options);
4163 }
4164
4165 @Override
4166 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4167 LocalServices.getService(VoiceInteractionManagerInternal.class)
4168 .stopLocalVoiceInteraction(callingActivity);
4169 }
4170
4171 @Override
4172 public boolean supportsLocalVoiceInteraction() {
4173 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4174 .supportsLocalVoiceInteraction();
4175 }
4176
4177 /** Notifies all listeners when the pinned stack animation starts. */
4178 @Override
4179 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004180 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004181 }
4182
4183 /** Notifies all listeners when the pinned stack animation ends. */
4184 @Override
4185 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004186 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 }
4188
4189 @Override
4190 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 final long ident = Binder.clearCallingIdentity();
4193 try {
4194 synchronized (mGlobalLock) {
4195 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4196 }
4197 } finally {
4198 Binder.restoreCallingIdentity(ident);
4199 }
4200 }
4201
4202 @Override
4203 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004204 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205
4206 synchronized (mGlobalLock) {
4207 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004208 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 // Call might come when display is not yet added or has already been removed.
4210 if (DEBUG_CONFIGURATION) {
4211 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4212 + displayId);
4213 }
4214 return false;
4215 }
4216
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004217 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004219 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004220 }
4221
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004222 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004223 final Message msg = PooledLambda.obtainMessage(
4224 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4225 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004226 }
4227
4228 final long origId = Binder.clearCallingIdentity();
4229 try {
4230 if (values != null) {
4231 Settings.System.clearConfiguration(values);
4232 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004233 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4235 return mTmpUpdateConfigurationResult.changes != 0;
4236 } finally {
4237 Binder.restoreCallingIdentity(origId);
4238 }
4239 }
4240 }
4241
4242 @Override
4243 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245
4246 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004249 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 }
4251
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004252 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004253 final Message msg = PooledLambda.obtainMessage(
4254 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4255 DEFAULT_DISPLAY);
4256 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 }
4258
4259 final long origId = Binder.clearCallingIdentity();
4260 try {
4261 if (values != null) {
4262 Settings.System.clearConfiguration(values);
4263 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004264 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 UserHandle.USER_NULL, false /* deferResume */,
4266 mTmpUpdateConfigurationResult);
4267 return mTmpUpdateConfigurationResult.changes != 0;
4268 } finally {
4269 Binder.restoreCallingIdentity(origId);
4270 }
4271 }
4272 }
4273
4274 @Override
4275 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4276 CharSequence message) {
4277 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004278 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4280 }
4281 final long callingId = Binder.clearCallingIdentity();
4282 try {
4283 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004284 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285 }
4286 } finally {
4287 Binder.restoreCallingIdentity(callingId);
4288 }
4289 }
4290
4291 @Override
4292 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 "cancelTaskWindowTransition()");
4295 final long ident = Binder.clearCallingIdentity();
4296 try {
4297 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004298 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 MATCH_TASK_IN_STACKS_ONLY);
4300 if (task == null) {
4301 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4302 return;
4303 }
4304 task.cancelWindowTransition();
4305 }
4306 } finally {
4307 Binder.restoreCallingIdentity(ident);
4308 }
4309 }
4310
4311 @Override
4312 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004313 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 final long ident = Binder.clearCallingIdentity();
4315 try {
4316 final TaskRecord task;
4317 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004318 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4320 if (task == null) {
4321 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4322 return null;
4323 }
4324 }
4325 // Don't call this while holding the lock as this operation might hit the disk.
4326 return task.getSnapshot(reducedResolution);
4327 } finally {
4328 Binder.restoreCallingIdentity(ident);
4329 }
4330 }
4331
4332 @Override
4333 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4334 synchronized (mGlobalLock) {
4335 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4336 if (r == null) {
4337 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4338 + token);
4339 return;
4340 }
4341 final long origId = Binder.clearCallingIdentity();
4342 try {
4343 r.setDisablePreviewScreenshots(disable);
4344 } finally {
4345 Binder.restoreCallingIdentity(origId);
4346 }
4347 }
4348 }
4349
4350 /** Return the user id of the last resumed activity. */
4351 @Override
4352 public @UserIdInt
4353 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004354 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4356 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004357 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004358 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004360 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004361 }
4362 }
4363
4364 @Override
4365 public void updateLockTaskFeatures(int userId, int flags) {
4366 final int callingUid = Binder.getCallingUid();
4367 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004368 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 "updateLockTaskFeatures()");
4370 }
4371 synchronized (mGlobalLock) {
4372 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4373 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004374 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 }
4376 }
4377
4378 @Override
4379 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4380 synchronized (mGlobalLock) {
4381 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4382 if (r == null) {
4383 return;
4384 }
4385 final long origId = Binder.clearCallingIdentity();
4386 try {
4387 r.setShowWhenLocked(showWhenLocked);
4388 } finally {
4389 Binder.restoreCallingIdentity(origId);
4390 }
4391 }
4392 }
4393
4394 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004395 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4396 synchronized (mGlobalLock) {
4397 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4398 if (r == null) {
4399 return;
4400 }
4401 final long origId = Binder.clearCallingIdentity();
4402 try {
4403 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4404 } finally {
4405 Binder.restoreCallingIdentity(origId);
4406 }
4407 }
4408 }
4409
4410 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4412 synchronized (mGlobalLock) {
4413 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4414 if (r == null) {
4415 return;
4416 }
4417 final long origId = Binder.clearCallingIdentity();
4418 try {
4419 r.setTurnScreenOn(turnScreenOn);
4420 } finally {
4421 Binder.restoreCallingIdentity(origId);
4422 }
4423 }
4424 }
4425
4426 @Override
4427 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004428 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 "registerRemoteAnimations");
4430 definition.setCallingPid(Binder.getCallingPid());
4431 synchronized (mGlobalLock) {
4432 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4433 if (r == null) {
4434 return;
4435 }
4436 final long origId = Binder.clearCallingIdentity();
4437 try {
4438 r.registerRemoteAnimations(definition);
4439 } finally {
4440 Binder.restoreCallingIdentity(origId);
4441 }
4442 }
4443 }
4444
4445 @Override
4446 public void registerRemoteAnimationForNextActivityStart(String packageName,
4447 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004449 "registerRemoteAnimationForNextActivityStart");
4450 adapter.setCallingPid(Binder.getCallingPid());
4451 synchronized (mGlobalLock) {
4452 final long origId = Binder.clearCallingIdentity();
4453 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004454 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 packageName, adapter);
4456 } finally {
4457 Binder.restoreCallingIdentity(origId);
4458 }
4459 }
4460 }
4461
Evan Rosky966759f2019-01-15 10:33:58 -08004462 @Override
4463 public void registerRemoteAnimationsForDisplay(int displayId,
4464 RemoteAnimationDefinition definition) {
4465 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4466 "registerRemoteAnimations");
4467 definition.setCallingPid(Binder.getCallingPid());
4468 synchronized (mGlobalLock) {
4469 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4470 if (display == null) {
4471 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4472 return;
4473 }
4474 final long origId = Binder.clearCallingIdentity();
4475 try {
4476 display.mDisplayContent.registerRemoteAnimations(definition);
4477 } finally {
4478 Binder.restoreCallingIdentity(origId);
4479 }
4480 }
4481 }
4482
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4484 @Override
4485 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4486 synchronized (mGlobalLock) {
4487 final long origId = Binder.clearCallingIdentity();
4488 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004489 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004490 } finally {
4491 Binder.restoreCallingIdentity(origId);
4492 }
4493 }
4494 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004495
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004496 @Override
4497 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004498 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004499 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004500 final int pid = Binder.getCallingPid();
4501 final WindowProcessController wpc = mPidMap.get(pid);
4502 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004503 }
4504 }
4505
4506 @Override
4507 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004509 != PERMISSION_GRANTED) {
4510 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4511 + Binder.getCallingPid()
4512 + ", uid=" + Binder.getCallingUid()
4513 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4514 Slog.w(TAG, msg);
4515 throw new SecurityException(msg);
4516 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004517 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004518 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004519 final int pid = Binder.getCallingPid();
4520 final WindowProcessController proc = mPidMap.get(pid);
4521 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004522 }
4523 }
4524
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004525 @Override
4526 public void stopAppSwitches() {
4527 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4528 synchronized (mGlobalLock) {
4529 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4530 mDidAppSwitch = false;
4531 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4532 }
4533 }
4534
4535 @Override
4536 public void resumeAppSwitches() {
4537 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4538 synchronized (mGlobalLock) {
4539 // Note that we don't execute any pending app switches... we will
4540 // let those wait until either the timeout, or the next start
4541 // activity request.
4542 mAppSwitchesAllowedTime = 0;
4543 }
4544 }
4545
4546 void onStartActivitySetDidAppSwitch() {
4547 if (mDidAppSwitch) {
4548 // This is the second allowed switch since we stopped switches, so now just generally
4549 // allow switches. Use case:
4550 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4551 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4552 // anyone to switch again).
4553 mAppSwitchesAllowedTime = 0;
4554 } else {
4555 mDidAppSwitch = true;
4556 }
4557 }
4558
4559 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004560 boolean shouldDisableNonVrUiLocked() {
4561 return mVrController.shouldDisableNonVrUiLocked();
4562 }
4563
Wale Ogunwale53783742018-09-16 10:21:51 -07004564 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004565 // VR apps are expected to run in a main display. If an app is turning on VR for
4566 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4567 // fullscreen stack before enabling VR Mode.
4568 // TODO: The goal of this code is to keep the VR app on the main display. When the
4569 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4570 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4571 // option would be a better choice here.
4572 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4573 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4574 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004575 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004576 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004577 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004578 }
4579 mH.post(() -> {
4580 if (!mVrController.onVrModeChanged(r)) {
4581 return;
4582 }
4583 synchronized (mGlobalLock) {
4584 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4585 mWindowManager.disableNonVrUi(disableNonVrUi);
4586 if (disableNonVrUi) {
4587 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4588 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004589 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004590 }
4591 }
4592 });
4593 }
4594
Wale Ogunwale53783742018-09-16 10:21:51 -07004595 @Override
4596 public int getPackageScreenCompatMode(String packageName) {
4597 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4598 synchronized (mGlobalLock) {
4599 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4600 }
4601 }
4602
4603 @Override
4604 public void setPackageScreenCompatMode(String packageName, int mode) {
4605 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4606 "setPackageScreenCompatMode");
4607 synchronized (mGlobalLock) {
4608 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4609 }
4610 }
4611
4612 @Override
4613 public boolean getPackageAskScreenCompat(String packageName) {
4614 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4615 synchronized (mGlobalLock) {
4616 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4617 }
4618 }
4619
4620 @Override
4621 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4622 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4623 "setPackageAskScreenCompat");
4624 synchronized (mGlobalLock) {
4625 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4626 }
4627 }
4628
Wale Ogunwale64258362018-10-16 15:13:37 -07004629 public static String relaunchReasonToString(int relaunchReason) {
4630 switch (relaunchReason) {
4631 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4632 return "window_resize";
4633 case RELAUNCH_REASON_FREE_RESIZE:
4634 return "free_resize";
4635 default:
4636 return null;
4637 }
4638 }
4639
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004640 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004641 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004642 }
4643
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004644 /** Pokes the task persister. */
4645 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4646 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4647 }
4648
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004649 boolean isKeyguardLocked() {
4650 return mKeyguardController.isKeyguardLocked();
4651 }
4652
Garfield Tan01548632018-11-27 10:15:48 -08004653 /**
4654 * Clears launch params for the given package.
4655 * @param packageNames the names of the packages of which the launch params are to be cleared
4656 */
4657 @Override
4658 public void clearLaunchParamsForPackages(List<String> packageNames) {
4659 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4660 "clearLaunchParamsForPackages");
4661 synchronized (mGlobalLock) {
4662 for (int i = 0; i < packageNames.size(); ++i) {
4663 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4664 }
4665 }
4666 }
4667
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004668 /**
4669 * Makes the display with the given id a single task instance display. I.e the display can only
4670 * contain one task.
4671 */
4672 @Override
4673 public void setDisplayToSingleTaskInstance(int displayId) {
4674 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4675 "setDisplayToSingleTaskInstance");
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
4678 final ActivityDisplay display =
4679 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4680 if (display != null) {
4681 display.setDisplayToSingleTaskInstance();
4682 }
4683 } finally {
4684 Binder.restoreCallingIdentity(origId);
4685 }
4686 }
4687
Wale Ogunwale31913b52018-10-13 08:29:31 -07004688 void dumpLastANRLocked(PrintWriter pw) {
4689 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4690 if (mLastANRState == null) {
4691 pw.println(" <no ANR has occurred since boot>");
4692 } else {
4693 pw.println(mLastANRState);
4694 }
4695 }
4696
4697 void dumpLastANRTracesLocked(PrintWriter pw) {
4698 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4699
4700 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4701 if (ArrayUtils.isEmpty(files)) {
4702 pw.println(" <no ANR has occurred since boot>");
4703 return;
4704 }
4705 // Find the latest file.
4706 File latest = null;
4707 for (File f : files) {
4708 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4709 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004710 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004711 }
4712 pw.print("File: ");
4713 pw.print(latest.getName());
4714 pw.println();
4715 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4716 String line;
4717 while ((line = in.readLine()) != null) {
4718 pw.println(line);
4719 }
4720 } catch (IOException e) {
4721 pw.print("Unable to read: ");
4722 pw.print(e);
4723 pw.println();
4724 }
4725 }
4726
4727 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4728 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4729 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4730 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4731 }
4732
4733 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4734 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4735 pw.println(header);
4736
Wale Ogunwaled32da472018-11-16 07:19:28 -08004737 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004738 dumpPackage);
4739 boolean needSep = printedAnything;
4740
4741 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004742 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004743 " ResumedActivity: ");
4744 if (printed) {
4745 printedAnything = true;
4746 needSep = false;
4747 }
4748
4749 if (dumpPackage == null) {
4750 if (needSep) {
4751 pw.println();
4752 }
4753 printedAnything = true;
4754 mStackSupervisor.dump(pw, " ");
4755 }
4756
4757 if (!printedAnything) {
4758 pw.println(" (nothing)");
4759 }
4760 }
4761
4762 void dumpActivityContainersLocked(PrintWriter pw) {
4763 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004764 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004765 pw.println(" ");
4766 }
4767
4768 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4769 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4770 getActivityStartController().dump(pw, "", dumpPackage);
4771 }
4772
4773 /**
4774 * There are three things that cmd can be:
4775 * - a flattened component name that matches an existing activity
4776 * - the cmd arg isn't the flattened component name of an existing activity:
4777 * dump all activity whose component contains the cmd as a substring
4778 * - A hex number of the ActivityRecord object instance.
4779 *
4780 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4781 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4782 */
4783 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4784 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4785 ArrayList<ActivityRecord> activities;
4786
4787 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004788 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004789 dumpFocusedStackOnly);
4790 }
4791
4792 if (activities.size() <= 0) {
4793 return false;
4794 }
4795
4796 String[] newArgs = new String[args.length - opti];
4797 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4798
4799 TaskRecord lastTask = null;
4800 boolean needSep = false;
4801 for (int i = activities.size() - 1; i >= 0; i--) {
4802 ActivityRecord r = activities.get(i);
4803 if (needSep) {
4804 pw.println();
4805 }
4806 needSep = true;
4807 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004808 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004809 if (lastTask != task) {
4810 lastTask = task;
4811 pw.print("TASK "); pw.print(lastTask.affinity);
4812 pw.print(" id="); pw.print(lastTask.taskId);
4813 pw.print(" userId="); pw.println(lastTask.userId);
4814 if (dumpAll) {
4815 lastTask.dump(pw, " ");
4816 }
4817 }
4818 }
4819 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4820 }
4821 return true;
4822 }
4823
4824 /**
4825 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4826 * there is a thread associated with the activity.
4827 */
4828 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4829 final ActivityRecord r, String[] args, boolean dumpAll) {
4830 String innerPrefix = prefix + " ";
4831 synchronized (mGlobalLock) {
4832 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4833 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4834 pw.print(" pid=");
4835 if (r.hasProcess()) pw.println(r.app.getPid());
4836 else pw.println("(not running)");
4837 if (dumpAll) {
4838 r.dump(pw, innerPrefix);
4839 }
4840 }
4841 if (r.attachedToProcess()) {
4842 // flush anything that is already in the PrintWriter since the thread is going
4843 // to write to the file descriptor directly
4844 pw.flush();
4845 try {
4846 TransferPipe tp = new TransferPipe();
4847 try {
4848 r.app.getThread().dumpActivity(tp.getWriteFd(),
4849 r.appToken, innerPrefix, args);
4850 tp.go(fd);
4851 } finally {
4852 tp.kill();
4853 }
4854 } catch (IOException e) {
4855 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4856 } catch (RemoteException e) {
4857 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4858 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004859 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004860 }
4861
sanryhuang498e77e2018-12-06 14:57:01 +08004862 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4863 boolean testPssMode) {
4864 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4865 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4866 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004867 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004868 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4869 st.toString());
4870 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004871 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4872 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4873 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004874 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4875 testPssMode);
4876 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004877 }
4878
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004879 int getCurrentUserId() {
4880 return mAmInternal.getCurrentUserId();
4881 }
4882
4883 private void enforceNotIsolatedCaller(String caller) {
4884 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4885 throw new SecurityException("Isolated process not allowed to call " + caller);
4886 }
4887 }
4888
Wale Ogunwalef6733932018-06-27 05:14:34 -07004889 public Configuration getConfiguration() {
4890 Configuration ci;
4891 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004892 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004893 ci.userSetLocale = false;
4894 }
4895 return ci;
4896 }
4897
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004898 /**
4899 * Current global configuration information. Contains general settings for the entire system,
4900 * also corresponds to the merged configuration of the default display.
4901 */
4902 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004903 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004904 }
4905
4906 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4907 boolean initLocale) {
4908 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4909 }
4910
4911 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4912 boolean initLocale, boolean deferResume) {
4913 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4914 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4915 UserHandle.USER_NULL, deferResume);
4916 }
4917
Wale Ogunwale59507092018-10-29 09:00:30 -07004918 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004919 final long origId = Binder.clearCallingIdentity();
4920 try {
4921 synchronized (mGlobalLock) {
4922 updateConfigurationLocked(values, null, false, true, userId,
4923 false /* deferResume */);
4924 }
4925 } finally {
4926 Binder.restoreCallingIdentity(origId);
4927 }
4928 }
4929
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004930 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4931 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4932 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4933 deferResume, null /* result */);
4934 }
4935
4936 /**
4937 * Do either or both things: (1) change the current configuration, and (2)
4938 * make sure the given activity is running with the (now) current
4939 * configuration. Returns true if the activity has been left running, or
4940 * false if <var>starting</var> is being destroyed to match the new
4941 * configuration.
4942 *
4943 * @param userId is only used when persistent parameter is set to true to persist configuration
4944 * for that particular user
4945 */
4946 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4947 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4948 ActivityTaskManagerService.UpdateConfigurationResult result) {
4949 int changes = 0;
4950 boolean kept = true;
4951
4952 if (mWindowManager != null) {
4953 mWindowManager.deferSurfaceLayout();
4954 }
4955 try {
4956 if (values != null) {
4957 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4958 deferResume);
4959 }
4960
4961 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4962 } finally {
4963 if (mWindowManager != null) {
4964 mWindowManager.continueSurfaceLayout();
4965 }
4966 }
4967
4968 if (result != null) {
4969 result.changes = changes;
4970 result.activityRelaunched = !kept;
4971 }
4972 return kept;
4973 }
4974
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004975 /** Update default (global) configuration and notify listeners about changes. */
4976 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4977 boolean persistent, int userId, boolean deferResume) {
4978 mTempConfig.setTo(getGlobalConfiguration());
4979 final int changes = mTempConfig.updateFrom(values);
4980 if (changes == 0) {
4981 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4982 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4983 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4984 // (even if there are no actual changes) to unfreeze the window.
4985 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4986 return 0;
4987 }
4988
4989 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4990 "Updating global configuration to: " + values);
4991
4992 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4993 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4994 values.colorMode,
4995 values.densityDpi,
4996 values.fontScale,
4997 values.hardKeyboardHidden,
4998 values.keyboard,
4999 values.keyboardHidden,
5000 values.mcc,
5001 values.mnc,
5002 values.navigation,
5003 values.navigationHidden,
5004 values.orientation,
5005 values.screenHeightDp,
5006 values.screenLayout,
5007 values.screenWidthDp,
5008 values.smallestScreenWidthDp,
5009 values.touchscreen,
5010 values.uiMode);
5011
5012
5013 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5014 final LocaleList locales = values.getLocales();
5015 int bestLocaleIndex = 0;
5016 if (locales.size() > 1) {
5017 if (mSupportedSystemLocales == null) {
5018 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5019 }
5020 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5021 }
5022 SystemProperties.set("persist.sys.locale",
5023 locales.get(bestLocaleIndex).toLanguageTag());
5024 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005025
5026 final Message m = PooledLambda.obtainMessage(
5027 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5028 locales.get(bestLocaleIndex));
5029 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005030 }
5031
Yunfan Chen75157d72018-07-27 14:47:21 +09005032 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005033
5034 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005035 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005036
5037 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5038 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005039 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005040
5041 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005042 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005043
5044 AttributeCache ac = AttributeCache.instance();
5045 if (ac != null) {
5046 ac.updateConfiguration(mTempConfig);
5047 }
5048
5049 // Make sure all resources in our process are updated right now, so that anyone who is going
5050 // to retrieve resource values after we return will be sure to get the new ones. This is
5051 // especially important during boot, where the first config change needs to guarantee all
5052 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005053 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005054
5055 // We need another copy of global config because we're scheduling some calls instead of
5056 // running them in place. We need to be sure that object we send will be handled unchanged.
5057 final Configuration configCopy = new Configuration(mTempConfig);
5058 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005059 final Message msg = PooledLambda.obtainMessage(
5060 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5061 this, userId, configCopy);
5062 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005063 }
5064
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005065 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005066 final int pid = mPidMap.keyAt(i);
5067 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005068 if (DEBUG_CONFIGURATION) {
5069 Slog.v(TAG_CONFIGURATION, "Update process config of "
5070 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005071 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005072 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 }
5074
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005075 final Message msg = PooledLambda.obtainMessage(
5076 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5077 mAmInternal, changes, initLocale);
5078 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005079
5080 // Override configuration of the default display duplicates global config, so we need to
5081 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005082 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005083 DEFAULT_DISPLAY);
5084
5085 return changes;
5086 }
5087
5088 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5089 boolean deferResume, int displayId) {
5090 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5091 displayId, null /* result */);
5092 }
5093
5094 /**
5095 * Updates override configuration specific for the selected display. If no config is provided,
5096 * new one will be computed in WM based on current display info.
5097 */
5098 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5099 ActivityRecord starting, boolean deferResume, int displayId,
5100 ActivityTaskManagerService.UpdateConfigurationResult result) {
5101 int changes = 0;
5102 boolean kept = true;
5103
5104 if (mWindowManager != null) {
5105 mWindowManager.deferSurfaceLayout();
5106 }
5107 try {
5108 if (values != null) {
5109 if (displayId == DEFAULT_DISPLAY) {
5110 // Override configuration of the default display duplicates global config, so
5111 // we're calling global config update instead for default display. It will also
5112 // apply the correct override config.
5113 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5114 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5115 } else {
5116 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5117 }
5118 }
5119
5120 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5121 } finally {
5122 if (mWindowManager != null) {
5123 mWindowManager.continueSurfaceLayout();
5124 }
5125 }
5126
5127 if (result != null) {
5128 result.changes = changes;
5129 result.activityRelaunched = !kept;
5130 }
5131 return kept;
5132 }
5133
5134 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5135 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005136 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 final int changes = mTempConfig.updateFrom(values);
5138 if (changes != 0) {
5139 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5140 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005141 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005142
5143 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5144 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005145 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005146
Wale Ogunwale5c918702018-10-18 11:06:33 -07005147 // Post message to start process to avoid possible deadlock of calling into AMS with
5148 // the ATMS lock held.
5149 final Message msg = PooledLambda.obtainMessage(
5150 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5151 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5152 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005153 }
5154 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005155 return changes;
5156 }
5157
Wale Ogunwalef6733932018-06-27 05:14:34 -07005158 private void updateEventDispatchingLocked(boolean booted) {
5159 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5160 }
5161
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005162 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5163 final ContentResolver resolver = mContext.getContentResolver();
5164 Settings.System.putConfigurationForUser(resolver, config, userId);
5165 }
5166
5167 private void sendLocaleToMountDaemonMsg(Locale l) {
5168 try {
5169 IBinder service = ServiceManager.getService("mount");
5170 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5171 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5172 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5173 } catch (RemoteException e) {
5174 Log.e(TAG, "Error storing locale for decryption UI", e);
5175 }
5176 }
5177
Alison Cichowlas3e340502018-08-07 17:15:01 -04005178 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5179 mStartActivitySources.remove(permissionToken);
5180 mExpiredStartAsCallerTokens.add(permissionToken);
5181 }
5182
5183 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5184 mExpiredStartAsCallerTokens.remove(permissionToken);
5185 }
5186
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005187 boolean isActivityStartsLoggingEnabled() {
5188 return mAmInternal.isActivityStartsLoggingEnabled();
5189 }
5190
Michal Karpinski8596ded2018-11-14 14:43:48 +00005191 boolean isBackgroundActivityStartsEnabled() {
5192 return mAmInternal.isBackgroundActivityStartsEnabled();
5193 }
5194
Wale Ogunwalef6733932018-06-27 05:14:34 -07005195 void enableScreenAfterBoot(boolean booted) {
5196 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5197 SystemClock.uptimeMillis());
5198 mWindowManager.enableScreenAfterBoot();
5199
5200 synchronized (mGlobalLock) {
5201 updateEventDispatchingLocked(booted);
5202 }
5203 }
5204
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005205 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5206 if (r == null || !r.hasProcess()) {
5207 return KEY_DISPATCHING_TIMEOUT_MS;
5208 }
5209 return getInputDispatchingTimeoutLocked(r.app);
5210 }
5211
5212 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005213 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005214 }
5215
Wale Ogunwalef6733932018-06-27 05:14:34 -07005216 /**
5217 * Decide based on the configuration whether we should show the ANR,
5218 * crash, etc dialogs. The idea is that if there is no affordance to
5219 * press the on-screen buttons, or the user experience would be more
5220 * greatly impacted than the crash itself, we shouldn't show the dialog.
5221 *
5222 * A thought: SystemUI might also want to get told about this, the Power
5223 * dialog / global actions also might want different behaviors.
5224 */
5225 private void updateShouldShowDialogsLocked(Configuration config) {
5226 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5227 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5228 && config.navigation == Configuration.NAVIGATION_NONAV);
5229 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5230 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5231 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5232 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5233 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5234 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5235 HIDE_ERROR_DIALOGS, 0) != 0;
5236 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5237 }
5238
5239 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5240 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5241 FONT_SCALE, 1.0f, userId);
5242
5243 synchronized (this) {
5244 if (getGlobalConfiguration().fontScale == scaleFactor) {
5245 return;
5246 }
5247
5248 final Configuration configuration
5249 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5250 configuration.fontScale = scaleFactor;
5251 updatePersistentConfiguration(configuration, userId);
5252 }
5253 }
5254
5255 // Actually is sleeping or shutting down or whatever else in the future
5256 // is an inactive state.
5257 boolean isSleepingOrShuttingDownLocked() {
5258 return isSleepingLocked() || mShuttingDown;
5259 }
5260
5261 boolean isSleepingLocked() {
5262 return mSleeping;
5263 }
5264
Riddle Hsu16567132018-08-16 21:37:47 +08005265 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005266 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005267 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005268 if (task.isActivityTypeStandard()) {
5269 if (mCurAppTimeTracker != r.appTimeTracker) {
5270 // We are switching app tracking. Complete the current one.
5271 if (mCurAppTimeTracker != null) {
5272 mCurAppTimeTracker.stop();
5273 mH.obtainMessage(
5274 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005275 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005276 mCurAppTimeTracker = null;
5277 }
5278 if (r.appTimeTracker != null) {
5279 mCurAppTimeTracker = r.appTimeTracker;
5280 startTimeTrackingFocusedActivityLocked();
5281 }
5282 } else {
5283 startTimeTrackingFocusedActivityLocked();
5284 }
5285 } else {
5286 r.appTimeTracker = null;
5287 }
5288 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5289 // TODO: Probably not, because we don't want to resume voice on switching
5290 // back to this activity
5291 if (task.voiceInteractor != null) {
5292 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5293 } else {
5294 finishRunningVoiceLocked();
5295
5296 if (mLastResumedActivity != null) {
5297 final IVoiceInteractionSession session;
5298
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005299 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005300 if (lastResumedActivityTask != null
5301 && lastResumedActivityTask.voiceSession != null) {
5302 session = lastResumedActivityTask.voiceSession;
5303 } else {
5304 session = mLastResumedActivity.voiceSession;
5305 }
5306
5307 if (session != null) {
5308 // We had been in a voice interaction session, but now focused has
5309 // move to something different. Just finish the session, we can't
5310 // return to it and retain the proper state and synchronization with
5311 // the voice interaction service.
5312 finishVoiceTask(session);
5313 }
5314 }
5315 }
5316
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005317 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5318 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005319 }
5320 updateResumedAppTrace(r);
5321 mLastResumedActivity = r;
5322
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005323 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005324
5325 applyUpdateLockStateLocked(r);
5326 applyUpdateVrModeLocked(r);
5327
5328 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005329 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005330 r == null ? "NULL" : r.shortComponentName,
5331 reason);
5332 }
5333
5334 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5335 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005336 final ActivityTaskManagerInternal.SleepToken token =
5337 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005338 updateSleepIfNeededLocked();
5339 return token;
5340 }
5341 }
5342
5343 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005344 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005345 final boolean wasSleeping = mSleeping;
5346 boolean updateOomAdj = false;
5347
5348 if (!shouldSleep) {
5349 // If wasSleeping is true, we need to wake up activity manager state from when
5350 // we started sleeping. In either case, we need to apply the sleep tokens, which
5351 // will wake up stacks or put them to sleep as appropriate.
5352 if (wasSleeping) {
5353 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005354 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5355 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005356 startTimeTrackingFocusedActivityLocked();
5357 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5358 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5359 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005360 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005361 if (wasSleeping) {
5362 updateOomAdj = true;
5363 }
5364 } else if (!mSleeping && shouldSleep) {
5365 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005366 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5367 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005368 if (mCurAppTimeTracker != null) {
5369 mCurAppTimeTracker.stop();
5370 }
5371 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5372 mStackSupervisor.goingToSleepLocked();
5373 updateResumedAppTrace(null /* resumed */);
5374 updateOomAdj = true;
5375 }
5376 if (updateOomAdj) {
5377 mH.post(mAmInternal::updateOomAdj);
5378 }
5379 }
5380
5381 void updateOomAdj() {
5382 mH.post(mAmInternal::updateOomAdj);
5383 }
5384
Wale Ogunwale53783742018-09-16 10:21:51 -07005385 void updateCpuStats() {
5386 mH.post(mAmInternal::updateCpuStats);
5387 }
5388
Hui Yu03d12402018-12-06 18:00:37 -08005389 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5390 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005391 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5392 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005393 mH.sendMessage(m);
5394 }
5395
Hui Yu03d12402018-12-06 18:00:37 -08005396 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005397 ComponentName taskRoot = null;
5398 final TaskRecord task = activity.getTaskRecord();
5399 if (task != null) {
5400 final ActivityRecord rootActivity = task.getRootActivity();
5401 if (rootActivity != null) {
5402 taskRoot = rootActivity.mActivityComponent;
5403 }
5404 }
5405
Hui Yu03d12402018-12-06 18:00:37 -08005406 final Message m = PooledLambda.obtainMessage(
5407 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005408 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005409 mH.sendMessage(m);
5410 }
5411
Wale Ogunwale53783742018-09-16 10:21:51 -07005412 void setBooting(boolean booting) {
5413 mAmInternal.setBooting(booting);
5414 }
5415
5416 boolean isBooting() {
5417 return mAmInternal.isBooting();
5418 }
5419
5420 void setBooted(boolean booted) {
5421 mAmInternal.setBooted(booted);
5422 }
5423
5424 boolean isBooted() {
5425 return mAmInternal.isBooted();
5426 }
5427
5428 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5429 mH.post(() -> {
5430 if (finishBooting) {
5431 mAmInternal.finishBooting();
5432 }
5433 if (enableScreen) {
5434 mInternal.enableScreenAfterBoot(isBooted());
5435 }
5436 });
5437 }
5438
5439 void setHeavyWeightProcess(ActivityRecord root) {
5440 mHeavyWeightProcess = root.app;
5441 final Message m = PooledLambda.obtainMessage(
5442 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005443 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005444 mH.sendMessage(m);
5445 }
5446
5447 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5448 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5449 return;
5450 }
5451
5452 mHeavyWeightProcess = null;
5453 final Message m = PooledLambda.obtainMessage(
5454 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5455 proc.mUserId);
5456 mH.sendMessage(m);
5457 }
5458
5459 private void cancelHeavyWeightProcessNotification(int userId) {
5460 final INotificationManager inm = NotificationManager.getService();
5461 if (inm == null) {
5462 return;
5463 }
5464 try {
5465 inm.cancelNotificationWithTag("android", null,
5466 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5467 } catch (RuntimeException e) {
5468 Slog.w(TAG, "Error canceling notification for service", e);
5469 } catch (RemoteException e) {
5470 }
5471
5472 }
5473
5474 private void postHeavyWeightProcessNotification(
5475 WindowProcessController proc, Intent intent, int userId) {
5476 if (proc == null) {
5477 return;
5478 }
5479
5480 final INotificationManager inm = NotificationManager.getService();
5481 if (inm == null) {
5482 return;
5483 }
5484
5485 try {
5486 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5487 String text = mContext.getString(R.string.heavy_weight_notification,
5488 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5489 Notification notification =
5490 new Notification.Builder(context,
5491 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5492 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5493 .setWhen(0)
5494 .setOngoing(true)
5495 .setTicker(text)
5496 .setColor(mContext.getColor(
5497 com.android.internal.R.color.system_notification_accent_color))
5498 .setContentTitle(text)
5499 .setContentText(
5500 mContext.getText(R.string.heavy_weight_notification_detail))
5501 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5502 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5503 new UserHandle(userId)))
5504 .build();
5505 try {
5506 inm.enqueueNotificationWithTag("android", "android", null,
5507 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5508 } catch (RuntimeException e) {
5509 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5510 } catch (RemoteException e) {
5511 }
5512 } catch (PackageManager.NameNotFoundException e) {
5513 Slog.w(TAG, "Unable to create context for heavy notification", e);
5514 }
5515
5516 }
5517
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005518 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5519 IBinder token, String resultWho, int requestCode, Intent[] intents,
5520 String[] resolvedTypes, int flags, Bundle bOptions) {
5521
5522 ActivityRecord activity = null;
5523 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5524 activity = ActivityRecord.isInStackLocked(token);
5525 if (activity == null) {
5526 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5527 return null;
5528 }
5529 if (activity.finishing) {
5530 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5531 return null;
5532 }
5533 }
5534
5535 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5536 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5537 bOptions);
5538 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5539 if (noCreate) {
5540 return rec;
5541 }
5542 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5543 if (activity.pendingResults == null) {
5544 activity.pendingResults = new HashSet<>();
5545 }
5546 activity.pendingResults.add(rec.ref);
5547 }
5548 return rec;
5549 }
5550
Andrii Kulian52d255c2018-07-13 11:32:19 -07005551 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005552 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005553 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005554 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5555 mCurAppTimeTracker.start(resumedActivity.packageName);
5556 }
5557 }
5558
5559 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5560 if (mTracedResumedActivity != null) {
5561 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5562 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5563 }
5564 if (resumed != null) {
5565 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5566 constructResumedTraceName(resumed.packageName), 0);
5567 }
5568 mTracedResumedActivity = resumed;
5569 }
5570
5571 private String constructResumedTraceName(String packageName) {
5572 return "focused app: " + packageName;
5573 }
5574
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005575 /** Applies latest configuration and/or visibility updates if needed. */
5576 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5577 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005578 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005579 // mainStack is null during startup.
5580 if (mainStack != null) {
5581 if (changes != 0 && starting == null) {
5582 // If the configuration changed, and the caller is not already
5583 // in the process of starting an activity, then find the top
5584 // activity to check if its configuration needs to change.
5585 starting = mainStack.topRunningActivityLocked();
5586 }
5587
5588 if (starting != null) {
5589 kept = starting.ensureActivityConfiguration(changes,
5590 false /* preserveWindow */);
5591 // And we need to make sure at this point that all other activities
5592 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005593 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005594 !PRESERVE_WINDOWS);
5595 }
5596 }
5597
5598 return kept;
5599 }
5600
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005601 void scheduleAppGcsLocked() {
5602 mH.post(() -> mAmInternal.scheduleAppGcs());
5603 }
5604
Wale Ogunwale53783742018-09-16 10:21:51 -07005605 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5606 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5607 }
5608
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005609 /**
5610 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5611 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5612 * on demand.
5613 */
5614 IPackageManager getPackageManager() {
5615 return AppGlobals.getPackageManager();
5616 }
5617
5618 PackageManagerInternal getPackageManagerInternalLocked() {
5619 if (mPmInternal == null) {
5620 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5621 }
5622 return mPmInternal;
5623 }
5624
Wale Ogunwale008163e2018-07-23 23:11:08 -07005625 AppWarnings getAppWarningsLocked() {
5626 return mAppWarnings;
5627 }
5628
Wale Ogunwale214f3482018-10-04 11:00:47 -07005629 Intent getHomeIntent() {
5630 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5631 intent.setComponent(mTopComponent);
5632 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5633 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5634 intent.addCategory(Intent.CATEGORY_HOME);
5635 }
5636 return intent;
5637 }
5638
Chilun2ef71f72018-11-16 17:57:15 +08005639 /**
5640 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5641 * activities.
5642 *
5643 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5644 * component defined in config_secondaryHomeComponent.
5645 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5646 */
5647 Intent getSecondaryHomeIntent(String preferredPackage) {
5648 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5649 if (preferredPackage == null) {
5650 // Using the component stored in config if no package name.
5651 final String secondaryHomeComponent = mContext.getResources().getString(
5652 com.android.internal.R.string.config_secondaryHomeComponent);
5653 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5654 } else {
5655 intent.setPackage(preferredPackage);
5656 }
5657 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5658 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5659 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5660 }
5661 return intent;
5662 }
5663
Wale Ogunwale214f3482018-10-04 11:00:47 -07005664 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5665 if (info == null) return null;
5666 ApplicationInfo newInfo = new ApplicationInfo(info);
5667 newInfo.initForUser(userId);
5668 return newInfo;
5669 }
5670
Wale Ogunwale9c103022018-10-18 07:44:54 -07005671 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005672 if (uid == SYSTEM_UID) {
5673 // The system gets to run in any process. If there are multiple processes with the same
5674 // uid, just pick the first (this should never happen).
5675 final SparseArray<WindowProcessController> procs =
5676 mProcessNames.getMap().get(processName);
5677 if (procs == null) return null;
5678 final int procCount = procs.size();
5679 for (int i = 0; i < procCount; i++) {
5680 final int procUid = procs.keyAt(i);
5681 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5682 // Don't use an app process or different user process for system component.
5683 continue;
5684 }
5685 return procs.valueAt(i);
5686 }
5687 }
5688
5689 return mProcessNames.get(processName, uid);
5690 }
5691
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005692 WindowProcessController getProcessController(IApplicationThread thread) {
5693 if (thread == null) {
5694 return null;
5695 }
5696
5697 final IBinder threadBinder = thread.asBinder();
5698 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5699 for (int i = pmap.size()-1; i >= 0; i--) {
5700 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5701 for (int j = procs.size() - 1; j >= 0; j--) {
5702 final WindowProcessController proc = procs.valueAt(j);
5703 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5704 return proc;
5705 }
5706 }
5707 }
5708
5709 return null;
5710 }
5711
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005712 WindowProcessController getProcessController(int pid, int uid) {
5713 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5714 for (int i = pmap.size()-1; i >= 0; i--) {
5715 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5716 for (int j = procs.size() - 1; j >= 0; j--) {
5717 final WindowProcessController proc = procs.valueAt(j);
5718 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5719 return proc;
5720 }
5721 }
5722 }
5723 return null;
5724 }
5725
Riddle Hsua0536432019-02-16 00:38:59 +08005726 int getUidState(int uid) {
5727 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005728 }
5729
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005730 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005731 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005732 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5733 }
5734
Michal Karpinski4026cae2019-02-12 11:51:47 +00005735 boolean isDeviceOwner(String packageName) {
5736 if (packageName == null) {
5737 return false;
5738 }
5739 return packageName.equals(mDeviceOwnerPackageName);
5740 }
5741
5742 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5743 mDeviceOwnerPackageName = deviceOwnerPkg;
5744 }
5745
Wale Ogunwale9de19442018-10-18 19:05:03 -07005746 /**
5747 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5748 * the whitelist
5749 */
5750 String getPendingTempWhitelistTagForUidLocked(int uid) {
5751 return mPendingTempWhitelist.get(uid);
5752 }
5753
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005754 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5755 if (true || Build.IS_USER) {
5756 return;
5757 }
5758
5759 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5760 StrictMode.allowThreadDiskWrites();
5761 try {
5762 File tracesDir = new File("/data/anr");
5763 File tracesFile = null;
5764 try {
5765 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5766
5767 StringBuilder sb = new StringBuilder();
5768 Time tobj = new Time();
5769 tobj.set(System.currentTimeMillis());
5770 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5771 sb.append(": ");
5772 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5773 sb.append(" since ");
5774 sb.append(msg);
5775 FileOutputStream fos = new FileOutputStream(tracesFile);
5776 fos.write(sb.toString().getBytes());
5777 if (app == null) {
5778 fos.write("\n*** No application process!".getBytes());
5779 }
5780 fos.close();
5781 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5782 } catch (IOException e) {
5783 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5784 return;
5785 }
5786
5787 if (app != null && app.getPid() > 0) {
5788 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5789 firstPids.add(app.getPid());
5790 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5791 }
5792
5793 File lastTracesFile = null;
5794 File curTracesFile = null;
5795 for (int i=9; i>=0; i--) {
5796 String name = String.format(Locale.US, "slow%02d.txt", i);
5797 curTracesFile = new File(tracesDir, name);
5798 if (curTracesFile.exists()) {
5799 if (lastTracesFile != null) {
5800 curTracesFile.renameTo(lastTracesFile);
5801 } else {
5802 curTracesFile.delete();
5803 }
5804 }
5805 lastTracesFile = curTracesFile;
5806 }
5807 tracesFile.renameTo(curTracesFile);
5808 } finally {
5809 StrictMode.setThreadPolicy(oldPolicy);
5810 }
5811 }
5812
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005813 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005814 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005815
5816
Wale Ogunwale98875612018-10-12 07:53:02 -07005817 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5818 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005819
Riddle Hsud93a6c42018-11-29 21:50:06 +08005820 H(Looper looper) {
5821 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005822 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005823
5824 @Override
5825 public void handleMessage(Message msg) {
5826 switch (msg.what) {
5827 case REPORT_TIME_TRACKER_MSG: {
5828 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5829 tracker.deliverResult(mContext);
5830 } break;
5831 }
5832 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005833 }
5834
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005835 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005836 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005837
5838 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005839 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005840 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005841
5842 @Override
5843 public void handleMessage(Message msg) {
5844 switch (msg.what) {
5845 case DISMISS_DIALOG_UI_MSG: {
5846 final Dialog d = (Dialog) msg.obj;
5847 d.dismiss();
5848 break;
5849 }
5850 }
5851 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005852 }
5853
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005854 final class LocalService extends ActivityTaskManagerInternal {
5855 @Override
5856 public SleepToken acquireSleepToken(String tag, int displayId) {
5857 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005858 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005859 }
5860
5861 @Override
5862 public ComponentName getHomeActivityForUser(int userId) {
5863 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005864 final ActivityRecord homeActivity =
5865 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005866 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005867 }
5868 }
5869
5870 @Override
5871 public void onLocalVoiceInteractionStarted(IBinder activity,
5872 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5873 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005874 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005875 }
5876 }
5877
5878 @Override
5879 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5880 synchronized (mGlobalLock) {
5881 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5882 reasons, timestamp);
5883 }
5884 }
5885
5886 @Override
5887 public void notifyAppTransitionFinished() {
5888 synchronized (mGlobalLock) {
5889 mStackSupervisor.notifyAppTransitionDone();
5890 }
5891 }
5892
5893 @Override
5894 public void notifyAppTransitionCancelled() {
5895 synchronized (mGlobalLock) {
5896 mStackSupervisor.notifyAppTransitionDone();
5897 }
5898 }
5899
5900 @Override
5901 public List<IBinder> getTopVisibleActivities() {
5902 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005903 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005904 }
5905 }
5906
5907 @Override
5908 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5909 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005910 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005911 }
5912 }
5913
5914 @Override
5915 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5916 Bundle bOptions) {
5917 Preconditions.checkNotNull(intents, "intents");
5918 final String[] resolvedTypes = new String[intents.length];
5919
5920 // UID of the package on user userId.
5921 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5922 // packageUid may not be initialized.
5923 int packageUid = 0;
5924 final long ident = Binder.clearCallingIdentity();
5925
5926 try {
5927 for (int i = 0; i < intents.length; i++) {
5928 resolvedTypes[i] =
5929 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5930 }
5931
5932 packageUid = AppGlobals.getPackageManager().getPackageUid(
5933 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5934 } catch (RemoteException e) {
5935 // Shouldn't happen.
5936 } finally {
5937 Binder.restoreCallingIdentity(ident);
5938 }
5939
5940 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005941 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005942 packageUid, packageName,
5943 intents, resolvedTypes, null /* resultTo */,
5944 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005945 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5946 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005947 }
5948 }
5949
5950 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005951 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5952 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5953 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5954 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005955 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005956 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005957 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5958 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5959 userId, validateIncomingUser, originatingPendingIntent,
5960 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005961 }
5962 }
5963
5964 @Override
5965 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5966 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5967 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5968 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005969 PendingIntentRecord originatingPendingIntent,
5970 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005971 synchronized (mGlobalLock) {
5972 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5973 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5974 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005975 validateIncomingUser, originatingPendingIntent,
5976 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005977 }
5978 }
5979
5980 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005981 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5982 Intent intent, Bundle options, int userId) {
5983 return ActivityTaskManagerService.this.startActivityAsUser(
5984 caller, callerPacakge, intent,
5985 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5986 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5987 false /*validateIncomingUser*/);
5988 }
5989
5990 @Override
lumark588a3e82018-07-20 18:53:54 +08005991 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005992 synchronized (mGlobalLock) {
5993
5994 // We might change the visibilities here, so prepare an empty app transition which
5995 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005996 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005997 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005998 if (activityDisplay == null) {
5999 return;
6000 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006001 final DisplayContent dc = activityDisplay.mDisplayContent;
6002 final boolean wasTransitionSet =
6003 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006004 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006005 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006006 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006007 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006008
6009 // If there was a transition set already we don't want to interfere with it as we
6010 // might be starting it too early.
6011 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006012 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006013 }
6014 }
6015 if (callback != null) {
6016 callback.run();
6017 }
6018 }
6019
6020 @Override
6021 public void notifyKeyguardTrustedChanged() {
6022 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006023 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006024 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006025 }
6026 }
6027 }
6028
6029 /**
6030 * Called after virtual display Id is updated by
6031 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6032 * {@param vrVr2dDisplayId}.
6033 */
6034 @Override
6035 public void setVr2dDisplayId(int vr2dDisplayId) {
6036 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6037 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006038 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006039 }
6040 }
6041
6042 @Override
6043 public void setFocusedActivity(IBinder token) {
6044 synchronized (mGlobalLock) {
6045 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6046 if (r == null) {
6047 throw new IllegalArgumentException(
6048 "setFocusedActivity: No activity record matching token=" + token);
6049 }
Louis Chang19443452018-10-09 12:10:21 +08006050 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006051 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006052 }
6053 }
6054 }
6055
6056 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006057 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006058 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006059 }
6060
6061 @Override
6062 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006063 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006064 }
6065
6066 @Override
6067 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006068 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006069 }
6070
6071 @Override
6072 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6073 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6074 }
6075
6076 @Override
6077 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006078 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006079 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006080
6081 @Override
6082 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6083 synchronized (mGlobalLock) {
6084 mActiveVoiceInteractionServiceComponent = component;
6085 }
6086 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006087
6088 @Override
6089 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6090 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6091 return;
6092 }
6093 synchronized (mGlobalLock) {
6094 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6095 if (types == null) {
6096 if (uid < 0) {
6097 return;
6098 }
6099 types = new ArrayMap<>();
6100 mAllowAppSwitchUids.put(userId, types);
6101 }
6102 if (uid < 0) {
6103 types.remove(type);
6104 } else {
6105 types.put(type, uid);
6106 }
6107 }
6108 }
6109
6110 @Override
6111 public void onUserStopped(int userId) {
6112 synchronized (mGlobalLock) {
6113 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6114 mAllowAppSwitchUids.remove(userId);
6115 }
6116 }
6117
6118 @Override
6119 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6120 synchronized (mGlobalLock) {
6121 return ActivityTaskManagerService.this.isGetTasksAllowed(
6122 caller, callingPid, callingUid);
6123 }
6124 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006125
Riddle Hsua0536432019-02-16 00:38:59 +08006126 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006127 @Override
6128 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006129 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006130 mProcessNames.put(proc.mName, proc.mUid, proc);
6131 }
6132 }
6133
Riddle Hsua0536432019-02-16 00:38:59 +08006134 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006135 @Override
6136 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006137 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006138 mProcessNames.remove(name, uid);
6139 }
6140 }
6141
Riddle Hsua0536432019-02-16 00:38:59 +08006142 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006143 @Override
6144 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006145 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006146 if (proc == mHomeProcess) {
6147 mHomeProcess = null;
6148 }
6149 if (proc == mPreviousProcess) {
6150 mPreviousProcess = null;
6151 }
6152 }
6153 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006154
Riddle Hsua0536432019-02-16 00:38:59 +08006155 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006156 @Override
6157 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006158 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006159 return mTopProcessState;
6160 }
6161 }
6162
Riddle Hsua0536432019-02-16 00:38:59 +08006163 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006164 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006165 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006166 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006167 return proc == mHeavyWeightProcess;
6168 }
6169 }
6170
Riddle Hsua0536432019-02-16 00:38:59 +08006171 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006172 @Override
6173 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006174 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006175 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6176 }
6177 }
6178
6179 @Override
6180 public void finishHeavyWeightApp() {
6181 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006182 if (mHeavyWeightProcess != null) {
6183 mHeavyWeightProcess.finishActivities();
6184 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006185 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6186 mHeavyWeightProcess);
6187 }
6188 }
6189
Riddle Hsua0536432019-02-16 00:38:59 +08006190 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006191 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006192 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006193 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006194 return isSleepingLocked();
6195 }
6196 }
6197
6198 @Override
6199 public boolean isShuttingDown() {
6200 synchronized (mGlobalLock) {
6201 return mShuttingDown;
6202 }
6203 }
6204
6205 @Override
6206 public boolean shuttingDown(boolean booted, int timeout) {
6207 synchronized (mGlobalLock) {
6208 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006209 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006210 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006211 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006212 return mStackSupervisor.shutdownLocked(timeout);
6213 }
6214 }
6215
6216 @Override
6217 public void enableScreenAfterBoot(boolean booted) {
6218 synchronized (mGlobalLock) {
6219 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6220 SystemClock.uptimeMillis());
6221 mWindowManager.enableScreenAfterBoot();
6222 updateEventDispatchingLocked(booted);
6223 }
6224 }
6225
6226 @Override
6227 public boolean showStrictModeViolationDialog() {
6228 synchronized (mGlobalLock) {
6229 return mShowDialogs && !mSleeping && !mShuttingDown;
6230 }
6231 }
6232
6233 @Override
6234 public void showSystemReadyErrorDialogsIfNeeded() {
6235 synchronized (mGlobalLock) {
6236 try {
6237 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6238 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6239 + " data partition or your device will be unstable.");
6240 mUiHandler.post(() -> {
6241 if (mShowDialogs) {
6242 AlertDialog d = new BaseErrorDialog(mUiContext);
6243 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6244 d.setCancelable(false);
6245 d.setTitle(mUiContext.getText(R.string.android_system_label));
6246 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6247 d.setButton(DialogInterface.BUTTON_POSITIVE,
6248 mUiContext.getText(R.string.ok),
6249 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6250 d.show();
6251 }
6252 });
6253 }
6254 } catch (RemoteException e) {
6255 }
6256
6257 if (!Build.isBuildConsistent()) {
6258 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6259 mUiHandler.post(() -> {
6260 if (mShowDialogs) {
6261 AlertDialog d = new BaseErrorDialog(mUiContext);
6262 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6263 d.setCancelable(false);
6264 d.setTitle(mUiContext.getText(R.string.android_system_label));
6265 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6266 d.setButton(DialogInterface.BUTTON_POSITIVE,
6267 mUiContext.getText(R.string.ok),
6268 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6269 d.show();
6270 }
6271 });
6272 }
6273 }
6274 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006275
6276 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006277 public void onProcessMapped(int pid, WindowProcessController proc) {
6278 synchronized (mGlobalLock) {
6279 mPidMap.put(pid, proc);
6280 }
6281 }
6282
6283 @Override
6284 public void onProcessUnMapped(int pid) {
6285 synchronized (mGlobalLock) {
6286 mPidMap.remove(pid);
6287 }
6288 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006289
6290 @Override
6291 public void onPackageDataCleared(String name) {
6292 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006293 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006294 mAppWarnings.onPackageDataCleared(name);
6295 }
6296 }
6297
6298 @Override
6299 public void onPackageUninstalled(String name) {
6300 synchronized (mGlobalLock) {
6301 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006302 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006303 }
6304 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006305
6306 @Override
6307 public void onPackageAdded(String name, boolean replacing) {
6308 synchronized (mGlobalLock) {
6309 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6310 }
6311 }
6312
6313 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006314 public void onPackageReplaced(ApplicationInfo aInfo) {
6315 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006316 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006317 }
6318 }
6319
6320 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006321 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6322 synchronized (mGlobalLock) {
6323 return compatibilityInfoForPackageLocked(ai);
6324 }
6325 }
6326
Yunfan Chen75157d72018-07-27 14:47:21 +09006327 /**
6328 * Set the corresponding display information for the process global configuration. To be
6329 * called when we need to show IME on a different display.
6330 *
6331 * @param pid The process id associated with the IME window.
6332 * @param displayId The ID of the display showing the IME.
6333 */
6334 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006335 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006336 if (pid == MY_PID || pid < 0) {
6337 if (DEBUG_CONFIGURATION) {
6338 Slog.w(TAG,
6339 "Trying to update display configuration for system/invalid process.");
6340 }
6341 return;
6342 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006343 synchronized (mGlobalLock) {
6344 final ActivityDisplay activityDisplay =
6345 mRootActivityContainer.getActivityDisplay(displayId);
6346 if (activityDisplay == null) {
6347 // Call might come when display is not yet added or has been removed.
6348 if (DEBUG_CONFIGURATION) {
6349 Slog.w(TAG, "Trying to update display configuration for non-existing "
6350 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006351 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006352 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006353 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006354 final WindowProcessController process = mPidMap.get(pid);
6355 if (process == null) {
6356 if (DEBUG_CONFIGURATION) {
6357 Slog.w(TAG, "Trying to update display configuration for invalid "
6358 + "process, pid=" + pid);
6359 }
6360 return;
6361 }
6362 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6363 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006364 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006365
6366 @Override
6367 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6368 int requestCode, int resultCode, Intent data) {
6369 synchronized (mGlobalLock) {
6370 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006371 if (r != null && r.getActivityStack() != null) {
6372 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6373 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006374 }
6375 }
6376 }
6377
6378 @Override
6379 public void clearPendingResultForActivity(IBinder activityToken,
6380 WeakReference<PendingIntentRecord> pir) {
6381 synchronized (mGlobalLock) {
6382 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6383 if (r != null && r.pendingResults != null) {
6384 r.pendingResults.remove(pir);
6385 }
6386 }
6387 }
6388
6389 @Override
6390 public IIntentSender getIntentSender(int type, String packageName,
6391 int callingUid, int userId, IBinder token, String resultWho,
6392 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6393 Bundle bOptions) {
6394 synchronized (mGlobalLock) {
6395 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6396 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6397 }
6398 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006399
6400 @Override
6401 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6402 synchronized (mGlobalLock) {
6403 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6404 if (r == null) {
6405 return null;
6406 }
6407 if (r.mServiceConnectionsHolder == null) {
6408 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6409 ActivityTaskManagerService.this, r);
6410 }
6411
6412 return r.mServiceConnectionsHolder;
6413 }
6414 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006415
6416 @Override
6417 public Intent getHomeIntent() {
6418 synchronized (mGlobalLock) {
6419 return ActivityTaskManagerService.this.getHomeIntent();
6420 }
6421 }
6422
6423 @Override
6424 public boolean startHomeActivity(int userId, String reason) {
6425 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006426 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006427 }
6428 }
6429
6430 @Override
6431 public boolean startHomeOnAllDisplays(int userId, String reason) {
6432 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006433 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006434 }
6435 }
6436
Riddle Hsua0536432019-02-16 00:38:59 +08006437 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006438 @Override
6439 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006440 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006441 if (mFactoryTest == FACTORY_TEST_OFF) {
6442 return false;
6443 }
6444 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6445 && wpc.mName.equals(mTopComponent.getPackageName())) {
6446 return true;
6447 }
6448 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6449 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6450 }
6451 }
6452
6453 @Override
6454 public void updateTopComponentForFactoryTest() {
6455 synchronized (mGlobalLock) {
6456 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6457 return;
6458 }
6459 final ResolveInfo ri = mContext.getPackageManager()
6460 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6461 final CharSequence errorMsg;
6462 if (ri != null) {
6463 final ActivityInfo ai = ri.activityInfo;
6464 final ApplicationInfo app = ai.applicationInfo;
6465 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6466 mTopAction = Intent.ACTION_FACTORY_TEST;
6467 mTopData = null;
6468 mTopComponent = new ComponentName(app.packageName, ai.name);
6469 errorMsg = null;
6470 } else {
6471 errorMsg = mContext.getResources().getText(
6472 com.android.internal.R.string.factorytest_not_system);
6473 }
6474 } else {
6475 errorMsg = mContext.getResources().getText(
6476 com.android.internal.R.string.factorytest_no_action);
6477 }
6478 if (errorMsg == null) {
6479 return;
6480 }
6481
6482 mTopAction = null;
6483 mTopData = null;
6484 mTopComponent = null;
6485 mUiHandler.post(() -> {
6486 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6487 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006488 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006489 });
6490 }
6491 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006492
Riddle Hsua0536432019-02-16 00:38:59 +08006493 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006494 @Override
6495 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6496 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006497 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006498 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006499 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006500
6501 wpc.clearRecentTasks();
6502 wpc.clearActivities();
6503
6504 if (wpc.isInstrumenting()) {
6505 finishInstrumentationCallback.run();
6506 }
6507
Jorim Jaggid0752812018-10-16 16:07:20 +02006508 if (!restarting && hasVisibleActivities) {
6509 mWindowManager.deferSurfaceLayout();
6510 try {
6511 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6512 // If there was nothing to resume, and we are not already restarting
6513 // this process, but there is a visible activity that is hosted by the
6514 // process...then make sure all visible activities are running, taking
6515 // care of restarting this process.
6516 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6517 !PRESERVE_WINDOWS);
6518 }
6519 } finally {
6520 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006521 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006522 }
6523 }
6524 }
6525
6526 @Override
6527 public void closeSystemDialogs(String reason) {
6528 enforceNotIsolatedCaller("closeSystemDialogs");
6529
6530 final int pid = Binder.getCallingPid();
6531 final int uid = Binder.getCallingUid();
6532 final long origId = Binder.clearCallingIdentity();
6533 try {
6534 synchronized (mGlobalLock) {
6535 // Only allow this from foreground processes, so that background
6536 // applications can't abuse it to prevent system UI from being shown.
6537 if (uid >= FIRST_APPLICATION_UID) {
6538 final WindowProcessController proc = mPidMap.get(pid);
6539 if (!proc.isPerceptible()) {
6540 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6541 + " from background process " + proc);
6542 return;
6543 }
6544 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006545 mWindowManager.closeSystemDialogs(reason);
6546
Wale Ogunwaled32da472018-11-16 07:19:28 -08006547 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006548 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006549 // Call into AM outside the synchronized block.
6550 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006551 } finally {
6552 Binder.restoreCallingIdentity(origId);
6553 }
6554 }
6555
6556 @Override
6557 public void cleanupDisabledPackageComponents(
6558 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6559 synchronized (mGlobalLock) {
6560 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006561 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006562 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006563 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006564 mStackSupervisor.scheduleIdleLocked();
6565 }
6566
6567 // Clean-up disabled tasks
6568 getRecentTasks().cleanupDisabledPackageTasksLocked(
6569 packageName, disabledClasses, userId);
6570 }
6571 }
6572
6573 @Override
6574 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6575 int userId) {
6576 synchronized (mGlobalLock) {
6577
6578 boolean didSomething =
6579 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006580 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006581 null, doit, evenPersistent, userId);
6582 return didSomething;
6583 }
6584 }
6585
6586 @Override
6587 public void resumeTopActivities(boolean scheduleIdle) {
6588 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006589 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006590 if (scheduleIdle) {
6591 mStackSupervisor.scheduleIdleLocked();
6592 }
6593 }
6594 }
6595
Riddle Hsua0536432019-02-16 00:38:59 +08006596 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006597 @Override
6598 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006599 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006600 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6601 }
6602 }
6603
Riddle Hsua0536432019-02-16 00:38:59 +08006604 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006605 @Override
6606 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006607 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006608 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006609 }
6610 }
6611
6612 @Override
6613 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6614 try {
6615 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6616 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6617 }
6618 } catch (RemoteException ex) {
6619 throw new SecurityException("Fail to check is caller a privileged app", ex);
6620 }
6621
6622 synchronized (mGlobalLock) {
6623 final long ident = Binder.clearCallingIdentity();
6624 try {
6625 if (mAmInternal.shouldConfirmCredentials(userId)) {
6626 if (mKeyguardController.isKeyguardLocked()) {
6627 // Showing launcher to avoid user entering credential twice.
6628 startHomeActivity(currentUserId, "notifyLockedProfile");
6629 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006630 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006631 }
6632 } finally {
6633 Binder.restoreCallingIdentity(ident);
6634 }
6635 }
6636 }
6637
6638 @Override
6639 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6640 mAmInternal.enforceCallingPermission(
6641 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6642
6643 synchronized (mGlobalLock) {
6644 final long ident = Binder.clearCallingIdentity();
6645 try {
6646 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6647 FLAG_ACTIVITY_TASK_ON_HOME);
6648 ActivityOptions activityOptions = options != null
6649 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006650 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006651 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006652 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006653 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006654 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006655 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6656 UserHandle.CURRENT);
6657 } finally {
6658 Binder.restoreCallingIdentity(ident);
6659 }
6660 }
6661 }
6662
6663 @Override
6664 public void writeActivitiesToProto(ProtoOutputStream proto) {
6665 synchronized (mGlobalLock) {
6666 // The output proto of "activity --proto activities"
6667 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006668 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006669 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6670 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006671 }
6672 }
6673
6674 @Override
6675 public void saveANRState(String reason) {
6676 synchronized (mGlobalLock) {
6677 final StringWriter sw = new StringWriter();
6678 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6679 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6680 if (reason != null) {
6681 pw.println(" Reason: " + reason);
6682 }
6683 pw.println();
6684 getActivityStartController().dump(pw, " ", null);
6685 pw.println();
6686 pw.println("-------------------------------------------------------------------------------");
6687 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6688 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6689 "" /* header */);
6690 pw.println();
6691 pw.close();
6692
6693 mLastANRState = sw.toString();
6694 }
6695 }
6696
6697 @Override
6698 public void clearSavedANRState() {
6699 synchronized (mGlobalLock) {
6700 mLastANRState = null;
6701 }
6702 }
6703
6704 @Override
6705 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6706 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6707 synchronized (mGlobalLock) {
6708 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6709 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6710 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6711 dumpLastANRLocked(pw);
6712 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6713 dumpLastANRTracesLocked(pw);
6714 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6715 dumpActivityStarterLocked(pw, dumpPackage);
6716 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6717 dumpActivityContainersLocked(pw);
6718 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6719 if (getRecentTasks() != null) {
6720 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6721 }
6722 }
6723 }
6724 }
6725
6726 @Override
6727 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6728 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6729 int wakefulness) {
6730 synchronized (mGlobalLock) {
6731 if (mHomeProcess != null && (dumpPackage == null
6732 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6733 if (needSep) {
6734 pw.println();
6735 needSep = false;
6736 }
6737 pw.println(" mHomeProcess: " + mHomeProcess);
6738 }
6739 if (mPreviousProcess != null && (dumpPackage == null
6740 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6741 if (needSep) {
6742 pw.println();
6743 needSep = false;
6744 }
6745 pw.println(" mPreviousProcess: " + mPreviousProcess);
6746 }
6747 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6748 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6749 StringBuilder sb = new StringBuilder(128);
6750 sb.append(" mPreviousProcessVisibleTime: ");
6751 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6752 pw.println(sb);
6753 }
6754 if (mHeavyWeightProcess != null && (dumpPackage == null
6755 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6756 if (needSep) {
6757 pw.println();
6758 needSep = false;
6759 }
6760 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6761 }
6762 if (dumpPackage == null) {
6763 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006764 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 }
6766 if (dumpAll) {
6767 if (dumpPackage == null) {
6768 pw.println(" mConfigWillChange: "
6769 + getTopDisplayFocusedStack().mConfigWillChange);
6770 }
6771 if (mCompatModePackages.getPackages().size() > 0) {
6772 boolean printed = false;
6773 for (Map.Entry<String, Integer> entry
6774 : mCompatModePackages.getPackages().entrySet()) {
6775 String pkg = entry.getKey();
6776 int mode = entry.getValue();
6777 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6778 continue;
6779 }
6780 if (!printed) {
6781 pw.println(" mScreenCompatPackages:");
6782 printed = true;
6783 }
6784 pw.println(" " + pkg + ": " + mode);
6785 }
6786 }
6787 }
6788
6789 if (dumpPackage == null) {
6790 pw.println(" mWakefulness="
6791 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006792 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006793 if (mRunningVoice != null) {
6794 pw.println(" mRunningVoice=" + mRunningVoice);
6795 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6796 }
6797 pw.println(" mSleeping=" + mSleeping);
6798 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6799 pw.println(" mVrController=" + mVrController);
6800 }
6801 if (mCurAppTimeTracker != null) {
6802 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6803 }
6804 if (mAllowAppSwitchUids.size() > 0) {
6805 boolean printed = false;
6806 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6807 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6808 for (int j = 0; j < types.size(); j++) {
6809 if (dumpPackage == null ||
6810 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6811 if (needSep) {
6812 pw.println();
6813 needSep = false;
6814 }
6815 if (!printed) {
6816 pw.println(" mAllowAppSwitchUids:");
6817 printed = true;
6818 }
6819 pw.print(" User ");
6820 pw.print(mAllowAppSwitchUids.keyAt(i));
6821 pw.print(": Type ");
6822 pw.print(types.keyAt(j));
6823 pw.print(" = ");
6824 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6825 pw.println();
6826 }
6827 }
6828 }
6829 }
6830 if (dumpPackage == null) {
6831 if (mController != null) {
6832 pw.println(" mController=" + mController
6833 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6834 }
6835 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6836 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6837 }
6838
6839 return needSep;
6840 }
6841 }
6842
6843 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006844 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6845 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 synchronized (mGlobalLock) {
6847 if (dumpPackage == null) {
6848 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6849 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006850 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6851 if (mRunningVoice != null) {
6852 final long vrToken = proto.start(
6853 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6854 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6855 mRunningVoice.toString());
6856 mVoiceWakeLock.writeToProto(
6857 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6858 proto.end(vrToken);
6859 }
6860 mVrController.writeToProto(proto,
6861 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 if (mController != null) {
6863 final long token = proto.start(CONTROLLER);
6864 proto.write(CONTROLLER, mController.toString());
6865 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6866 proto.end(token);
6867 }
6868 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6869 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6870 }
6871
6872 if (mHomeProcess != null && (dumpPackage == null
6873 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006874 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006875 }
6876
6877 if (mPreviousProcess != null && (dumpPackage == null
6878 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006879 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6881 }
6882
6883 if (mHeavyWeightProcess != null && (dumpPackage == null
6884 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006885 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006886 }
6887
6888 for (Map.Entry<String, Integer> entry
6889 : mCompatModePackages.getPackages().entrySet()) {
6890 String pkg = entry.getKey();
6891 int mode = entry.getValue();
6892 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6893 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6894 proto.write(PACKAGE, pkg);
6895 proto.write(MODE, mode);
6896 proto.end(compatToken);
6897 }
6898 }
6899
6900 if (mCurAppTimeTracker != null) {
6901 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6902 }
6903
6904 }
6905 }
6906
6907 @Override
6908 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6909 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6910 boolean dumpFocusedStackOnly) {
6911 synchronized (mGlobalLock) {
6912 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6913 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6914 }
6915 }
6916
6917 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006918 public void dumpForOom(PrintWriter pw) {
6919 synchronized (mGlobalLock) {
6920 pw.println(" mHomeProcess: " + mHomeProcess);
6921 pw.println(" mPreviousProcess: " + mPreviousProcess);
6922 if (mHeavyWeightProcess != null) {
6923 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6924 }
6925 }
6926 }
6927
6928 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 public boolean canGcNow() {
6930 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006931 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006932 }
6933 }
6934
Riddle Hsua0536432019-02-16 00:38:59 +08006935 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 @Override
6937 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006938 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006939 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 return top != null ? top.app : null;
6941 }
6942 }
6943
Riddle Hsua0536432019-02-16 00:38:59 +08006944 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006945 @Override
6946 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006947 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006948 if (mRootActivityContainer != null) {
6949 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006950 }
6951 }
6952 }
6953
6954 @Override
6955 public void scheduleDestroyAllActivities(String reason) {
6956 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006957 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006958 }
6959 }
6960
6961 @Override
6962 public void removeUser(int userId) {
6963 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006964 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006965 }
6966 }
6967
6968 @Override
6969 public boolean switchUser(int userId, UserState userState) {
6970 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006971 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006972 }
6973 }
6974
6975 @Override
6976 public void onHandleAppCrash(WindowProcessController wpc) {
6977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006978 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006979 }
6980 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006981
6982 @Override
6983 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6984 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006985 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006986 }
6987 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006988
Riddle Hsua0536432019-02-16 00:38:59 +08006989 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006990 @Override
6991 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08006992 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006993 }
6994
Riddle Hsua0536432019-02-16 00:38:59 +08006995 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006996 @Override
6997 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006998 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006999 }
7000
Riddle Hsua0536432019-02-16 00:38:59 +08007001 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007002 @Override
7003 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007004 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007005 }
7006
Riddle Hsua0536432019-02-16 00:38:59 +08007007 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007008 @Override
7009 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007010 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007011 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007012
7013 @Override
7014 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007015 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007016 mPendingTempWhitelist.put(uid, tag);
7017 }
7018 }
7019
7020 @Override
7021 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007022 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007023 mPendingTempWhitelist.remove(uid);
7024 }
7025 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007026
7027 @Override
7028 public boolean handleAppCrashInActivityController(String processName, int pid,
7029 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7030 Runnable killCrashingAppCallback) {
7031 synchronized (mGlobalLock) {
7032 if (mController == null) {
7033 return false;
7034 }
7035
7036 try {
7037 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7038 stackTrace)) {
7039 killCrashingAppCallback.run();
7040 return true;
7041 }
7042 } catch (RemoteException e) {
7043 mController = null;
7044 Watchdog.getInstance().setActivityController(null);
7045 }
7046 return false;
7047 }
7048 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007049
7050 @Override
7051 public void removeRecentTasksByPackageName(String packageName, int userId) {
7052 synchronized (mGlobalLock) {
7053 mRecentTasks.removeTasksByPackageName(packageName, userId);
7054 }
7055 }
7056
7057 @Override
7058 public void cleanupRecentTasksForUser(int userId) {
7059 synchronized (mGlobalLock) {
7060 mRecentTasks.cleanupLocked(userId);
7061 }
7062 }
7063
7064 @Override
7065 public void loadRecentTasksForUser(int userId) {
7066 synchronized (mGlobalLock) {
7067 mRecentTasks.loadUserRecentsLocked(userId);
7068 }
7069 }
7070
7071 @Override
7072 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7073 synchronized (mGlobalLock) {
7074 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7075 }
7076 }
7077
7078 @Override
7079 public void flushRecentTasks() {
7080 mRecentTasks.flush();
7081 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007082
7083 @Override
7084 public WindowProcessController getHomeProcess() {
7085 synchronized (mGlobalLock) {
7086 return mHomeProcess;
7087 }
7088 }
7089
7090 @Override
7091 public WindowProcessController getPreviousProcess() {
7092 synchronized (mGlobalLock) {
7093 return mPreviousProcess;
7094 }
7095 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007096
7097 @Override
7098 public void clearLockedTasks(String reason) {
7099 synchronized (mGlobalLock) {
7100 getLockTaskController().clearLockedTasks(reason);
7101 }
7102 }
7103
7104 @Override
7105 public void updateUserConfiguration() {
7106 synchronized (mGlobalLock) {
7107 final Configuration configuration = new Configuration(getGlobalConfiguration());
7108 final int currentUserId = mAmInternal.getCurrentUserId();
7109 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7110 configuration, currentUserId, Settings.System.canWrite(mContext));
7111 updateConfigurationLocked(configuration, null /* starting */,
7112 false /* initLocale */, false /* persistent */, currentUserId,
7113 false /* deferResume */);
7114 }
7115 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007116
7117 @Override
7118 public boolean canShowErrorDialogs() {
7119 synchronized (mGlobalLock) {
7120 return mShowDialogs && !mSleeping && !mShuttingDown
7121 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7122 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7123 mAmInternal.getCurrentUserId())
7124 && !(UserManager.isDeviceInDemoMode(mContext)
7125 && mAmInternal.getCurrentUser().isDemo());
7126 }
7127 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007128
7129 @Override
7130 public void setProfileApp(String profileApp) {
7131 synchronized (mGlobalLock) {
7132 mProfileApp = profileApp;
7133 }
7134 }
7135
7136 @Override
7137 public void setProfileProc(WindowProcessController wpc) {
7138 synchronized (mGlobalLock) {
7139 mProfileProc = wpc;
7140 }
7141 }
7142
7143 @Override
7144 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7145 synchronized (mGlobalLock) {
7146 mProfilerInfo = profilerInfo;
7147 }
7148 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007149
7150 @Override
7151 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7152 synchronized (mGlobalLock) {
7153 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7154 }
7155 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007156
7157 @Override
7158 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7159 synchronized (mGlobalLock) {
7160 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7161 }
7162 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007163
7164 @Override
7165 public boolean isUidForeground(int uid) {
7166 synchronized (mGlobalLock) {
7167 return ActivityTaskManagerService.this.isUidForeground(uid);
7168 }
7169 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007170
7171 @Override
7172 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7173 synchronized (mGlobalLock) {
7174 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7175 }
7176 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007177 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007178}