blob: fe5bc2531f510d3c6a6b362d5d31d7e823434cab [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
88import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
210import 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;
Yunfan Chen279f5582018-12-12 15:24:50 -0800260import 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;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700274import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700276import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700277import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400279import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700280import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700281import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700282import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700283import java.util.Map;
284import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285
286/**
287 * System service for managing activities and their containers (task, stacks, displays,... ).
288 *
289 * {@hide}
290 */
291public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700292 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700294 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
295 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
296 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
297 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
298 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700299 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700301 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700302 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700303 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700304 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 /** Used to indicate that an app transition should be animated. */
307 static final boolean ANIMATE = true;
308
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700309 /** Hardware-reported OpenGLES version. */
310 final int GL_ES_VERSION;
311
Wale Ogunwale31913b52018-10-13 08:29:31 -0700312 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
313 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
314 public static final String DUMP_LASTANR_CMD = "lastanr" ;
315 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
316 public static final String DUMP_STARTER_CMD = "starter" ;
317 public static final String DUMP_CONTAINERS_CMD = "containers" ;
318 public static final String DUMP_RECENTS_CMD = "recents" ;
319 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
320
Wale Ogunwale64258362018-10-16 15:13:37 -0700321 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
322 public static final int RELAUNCH_REASON_NONE = 0;
323 /** This activity is being relaunched due to windowing mode change. */
324 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
325 /** This activity is being relaunched due to a free-resize operation. */
326 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
327
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700328 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700329
Wale Ogunwalef6733932018-06-27 05:14:34 -0700330 /**
331 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
332 * change at runtime. Use mContext for non-UI purposes.
333 */
334 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700335 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700336 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700337 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700338 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700339 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700340 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800341 @VisibleForTesting
342 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700343 PowerManagerInternal mPowerManagerInternal;
344 private UsageStatsManagerInternal mUsageStatsInternal;
345
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700346 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 IntentFirewall mIntentFirewall;
348
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700349 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800350 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700351 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800352 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700354 private UserManagerService mUserManager;
355 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700356 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700357 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
358 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700359 /** All processes currently running that might have a window organized by name. */
360 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700361 /** All processes we currently have running mapped by pid */
362 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700363 /** This is the process holding what we currently consider to be the "home" activity. */
364 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700365 /** The currently running heavy-weight process, if any. */
366 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700367 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700368 /**
369 * This is the process holding the activity the user last visited that is in a different process
370 * from the one they are currently in.
371 */
372 WindowProcessController mPreviousProcess;
373 /** The time at which the previous process was last visible. */
374 long mPreviousProcessVisibleTime;
375
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700376 /** List of intents that were used to start the most recent tasks. */
377 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700378 /** State of external calls telling us if the device is awake or asleep. */
379 private boolean mKeyguardShown = false;
380
381 // Wrapper around VoiceInteractionServiceManager
382 private AssistUtils mAssistUtils;
383
384 // VoiceInteraction session ID that changes for each new request except when
385 // being called for multi-window assist in a single session.
386 private int mViSessionId = 1000;
387
388 // How long to wait in getAssistContextExtras for the activity and foreground services
389 // to respond with the result.
390 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
391
392 // How long top wait when going through the modern assist (which doesn't need to block
393 // on getting this result before starting to launch its UI).
394 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
395
396 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
397 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
398
Alison Cichowlas3e340502018-08-07 17:15:01 -0400399 // Permission tokens are used to temporarily granted a trusted app the ability to call
400 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
401 // showing any appropriate error messages to the user.
402 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
403 10 * MINUTE_IN_MILLIS;
404
405 // How long before the service actually expires a token. This is slightly longer than
406 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
407 // expiration exception.
408 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
409 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
410
411 // How long the service will remember expired tokens, for the purpose of providing error
412 // messaging when a client uses an expired token.
413 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
414 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
415
416 // Activity tokens of system activities that are delegating their call to
417 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
418 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
419
420 // Permission tokens that have expired, but we remember for error reporting.
421 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
422
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700423 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
424
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700425 // Keeps track of the active voice interaction service component, notified from
426 // VoiceInteractionManagerService
427 ComponentName mActiveVoiceInteractionServiceComponent;
428
Wale Ogunwalee2172292018-10-25 10:11:10 -0700429 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700430 KeyguardController mKeyguardController;
431 private final ClientLifecycleManager mLifecycleManager;
432 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700433 /** The controller for all operations related to locktask. */
434 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700435 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700436
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700437 boolean mSuppressResizeConfigChanges;
438
439 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
440 new UpdateConfigurationResult();
441
442 static final class UpdateConfigurationResult {
443 // Configuration changes that were updated.
444 int changes;
445 // If the activity was relaunched to match the new configuration.
446 boolean activityRelaunched;
447
448 void reset() {
449 changes = 0;
450 activityRelaunched = false;
451 }
452 }
453
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700454 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700455 private int mConfigurationSeq;
456 // To cache the list of supported system locales
457 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700458
459 /**
460 * Temp object used when global and/or display override configuration is updated. It is also
461 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
462 * anyone...
463 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700464 private Configuration mTempConfig = new Configuration();
465
Wale Ogunwalef6733932018-06-27 05:14:34 -0700466 /** Temporary to avoid allocations. */
467 final StringBuilder mStringBuilder = new StringBuilder(256);
468
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700469 // Amount of time after a call to stopAppSwitches() during which we will
470 // prevent further untrusted switches from happening.
471 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
472
473 /**
474 * The time at which we will allow normal application switches again,
475 * after a call to {@link #stopAppSwitches()}.
476 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700477 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 /**
479 * This is set to true after the first switch after mAppSwitchesAllowedTime
480 * is set; any switches after that will clear the time.
481 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700482 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483
484 IActivityController mController = null;
485 boolean mControllerIsAMonkey = false;
486
Wale Ogunwale214f3482018-10-04 11:00:47 -0700487 final int mFactoryTest;
488
489 /** Used to control how we initialize the service. */
490 ComponentName mTopComponent;
491 String mTopAction = Intent.ACTION_MAIN;
492 String mTopData;
493
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800494 /** Profiling app information. */
495 String mProfileApp = null;
496 WindowProcessController mProfileProc = null;
497 ProfilerInfo mProfilerInfo = null;
498
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700500 * Dump of the activity state at the time of the last ANR. Cleared after
501 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
502 */
503 String mLastANRState;
504
505 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 * Used to retain an update lock when the foreground activity is in
507 * immersive mode.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
511 /**
512 * Packages that are being allowed to perform unrestricted app switches. Mapping is
513 * User -> Type -> uid.
514 */
515 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
516
517 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700518 private int mThumbnailWidth;
519 private int mThumbnailHeight;
520 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700521
522 /**
523 * Flag that indicates if multi-window is enabled.
524 *
525 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
526 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
527 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
528 * At least one of the forms of multi-window must be enabled in order for this flag to be
529 * initialized to 'true'.
530 *
531 * @see #mSupportsSplitScreenMultiWindow
532 * @see #mSupportsFreeformWindowManagement
533 * @see #mSupportsPictureInPicture
534 * @see #mSupportsMultiDisplay
535 */
536 boolean mSupportsMultiWindow;
537 boolean mSupportsSplitScreenMultiWindow;
538 boolean mSupportsFreeformWindowManagement;
539 boolean mSupportsPictureInPicture;
540 boolean mSupportsMultiDisplay;
541 boolean mForceResizableActivities;
542
543 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
544
545 // VR Vr2d Display Id.
546 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700547
Wale Ogunwalef6733932018-06-27 05:14:34 -0700548 /**
549 * Set while we are wanting to sleep, to prevent any
550 * activities from being started/resumed.
551 *
552 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
553 *
554 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
555 * while in the sleep state until there is a pending transition out of sleep, in which case
556 * mSleeping is set to false, and remains false while awake.
557 *
558 * Whether mSleeping can quickly toggled between true/false without the device actually
559 * display changing states is undefined.
560 */
561 private boolean mSleeping = false;
562
563 /**
564 * The process state used for processes that are running the top activities.
565 * This changes between TOP and TOP_SLEEPING to following mSleeping.
566 */
567 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
568
569 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
570 // automatically. Important for devices without direct input devices.
571 private boolean mShowDialogs = true;
572
573 /** Set if we are shutting down the system, similar to sleeping. */
574 boolean mShuttingDown = false;
575
576 /**
577 * We want to hold a wake lock while running a voice interaction session, since
578 * this may happen with the screen off and we need to keep the CPU running to
579 * be able to continue to interact with the user.
580 */
581 PowerManager.WakeLock mVoiceWakeLock;
582
583 /**
584 * Set while we are running a voice interaction. This overrides sleeping while it is active.
585 */
586 IVoiceInteractionSession mRunningVoice;
587
588 /**
589 * The last resumed activity. This is identical to the current resumed activity most
590 * of the time but could be different when we're pausing one activity before we resume
591 * another activity.
592 */
593 ActivityRecord mLastResumedActivity;
594
595 /**
596 * The activity that is currently being traced as the active resumed activity.
597 *
598 * @see #updateResumedAppTrace
599 */
600 private @Nullable ActivityRecord mTracedResumedActivity;
601
602 /** If non-null, we are tracking the time the user spends in the currently focused app. */
603 AppTimeTracker mCurAppTimeTracker;
604
Wale Ogunwale008163e2018-07-23 23:11:08 -0700605 private AppWarnings mAppWarnings;
606
Wale Ogunwale53783742018-09-16 10:21:51 -0700607 /**
608 * Packages that the user has asked to have run in screen size
609 * compatibility mode instead of filling the screen.
610 */
611 CompatModePackages mCompatModePackages;
612
Wale Ogunwalef6733932018-06-27 05:14:34 -0700613 private FontScaleSettingObserver mFontScaleSettingObserver;
614
615 private final class FontScaleSettingObserver extends ContentObserver {
616 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
617 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
618
619 public FontScaleSettingObserver() {
620 super(mH);
621 final ContentResolver resolver = mContext.getContentResolver();
622 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
623 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
624 UserHandle.USER_ALL);
625 }
626
627 @Override
628 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
629 if (mFontScaleUri.equals(uri)) {
630 updateFontScaleIfNeeded(userId);
631 } else if (mHideErrorDialogsUri.equals(uri)) {
632 synchronized (mGlobalLock) {
633 updateShouldShowDialogsLocked(getGlobalConfiguration());
634 }
635 }
636 }
637 }
638
Charles Chen8d98dd22018-12-26 17:36:54 +0800639 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
640 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700641 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700642 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700643 mSystemThread = ActivityThread.currentActivityThread();
644 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700645 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800646 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700647 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700648 }
649
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700650 public void onSystemReady() {
651 synchronized (mGlobalLock) {
652 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
653 PackageManager.FEATURE_CANT_SAVE_STATE);
654 mAssistUtils = new AssistUtils(mContext);
655 mVrController.onSystemReady();
656 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700657 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700658 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700659 }
660
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700661 public void onInitPowerManagement() {
662 synchronized (mGlobalLock) {
663 mStackSupervisor.initPowerManagement();
664 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
665 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
666 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
667 mVoiceWakeLock.setReferenceCounted(false);
668 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700669 }
670
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700671 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700672 mFontScaleSettingObserver = new FontScaleSettingObserver();
673 }
674
Wale Ogunwale59507092018-10-29 09:00:30 -0700675 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700676 final boolean freeformWindowManagement =
677 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
678 || Settings.Global.getInt(
679 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
680
681 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
682 final boolean supportsPictureInPicture = supportsMultiWindow &&
683 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
684 final boolean supportsSplitScreenMultiWindow =
685 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
686 final boolean supportsMultiDisplay = mContext.getPackageManager()
687 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700688 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
689 final boolean forceResizable = Settings.Global.getInt(
690 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700691 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700692
693 // Transfer any global setting for forcing RTL layout, into a System Property
694 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
695
696 final Configuration configuration = new Configuration();
697 Settings.System.getConfiguration(resolver, configuration);
698 if (forceRtl) {
699 // This will take care of setting the correct layout direction flags
700 configuration.setLayoutDirection(configuration.locale);
701 }
702
703 synchronized (mGlobalLock) {
704 mForceResizableActivities = forceResizable;
705 final boolean multiWindowFormEnabled = freeformWindowManagement
706 || supportsSplitScreenMultiWindow
707 || supportsPictureInPicture
708 || supportsMultiDisplay;
709 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
710 mSupportsMultiWindow = true;
711 mSupportsFreeformWindowManagement = freeformWindowManagement;
712 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
713 mSupportsPictureInPicture = supportsPictureInPicture;
714 mSupportsMultiDisplay = supportsMultiDisplay;
715 } else {
716 mSupportsMultiWindow = false;
717 mSupportsFreeformWindowManagement = false;
718 mSupportsSplitScreenMultiWindow = false;
719 mSupportsPictureInPicture = false;
720 mSupportsMultiDisplay = false;
721 }
722 mWindowManager.setForceResizableTasks(mForceResizableActivities);
723 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700724 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
725 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700726 // This happens before any activities are started, so we can change global configuration
727 // in-place.
728 updateConfigurationLocked(configuration, null, true);
729 final Configuration globalConfig = getGlobalConfiguration();
730 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
731
732 // Load resources only after the current configuration has been set.
733 final Resources res = mContext.getResources();
734 mThumbnailWidth = res.getDimensionPixelSize(
735 com.android.internal.R.dimen.thumbnail_width);
736 mThumbnailHeight = res.getDimensionPixelSize(
737 com.android.internal.R.dimen.thumbnail_height);
738
739 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
740 mFullscreenThumbnailScale = (float) res
741 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
742 (float) globalConfig.screenWidthDp;
743 } else {
744 mFullscreenThumbnailScale = res.getFraction(
745 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
746 }
747 }
748 }
749
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800750 public WindowManagerGlobalLock getGlobalLock() {
751 return mGlobalLock;
752 }
753
Riddle Hsud93a6c42018-11-29 21:50:06 +0800754 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
755 Looper looper) {
756 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700757 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700758 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700759 final File systemDir = SystemServiceManager.ensureSystemDir();
760 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
761 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700762 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700763
764 mTempConfig.setToDefaults();
765 mTempConfig.setLocales(LocaleList.getDefault());
766 mConfigurationSeq = mTempConfig.seq = 1;
767 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800768 mRootActivityContainer = new RootActivityContainer(this);
769 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700770
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700771 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700773 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700775 mRecentTasks = createRecentTasks();
776 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700777 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700778 mKeyguardController = mStackSupervisor.getKeyguardController();
779 }
780
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700781 public void onActivityManagerInternalAdded() {
782 synchronized (mGlobalLock) {
783 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
784 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
785 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700786 }
787
Yunfan Chen75157d72018-07-27 14:47:21 +0900788 int increaseConfigurationSeqLocked() {
789 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
790 return mConfigurationSeq;
791 }
792
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700793 protected ActivityStackSupervisor createStackSupervisor() {
794 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
795 supervisor.initialize();
796 return supervisor;
797 }
798
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700799 public void setWindowManager(WindowManagerService wm) {
800 synchronized (mGlobalLock) {
801 mWindowManager = wm;
802 mLockTaskController.setWindowManager(wm);
803 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800804 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700805 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700806 }
807
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700808 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
809 synchronized (mGlobalLock) {
810 mUsageStatsInternal = usageStatsManager;
811 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700812 }
813
Wale Ogunwalef6733932018-06-27 05:14:34 -0700814 UserManagerService getUserManager() {
815 if (mUserManager == null) {
816 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
817 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
818 }
819 return mUserManager;
820 }
821
822 AppOpsService getAppOpsService() {
823 if (mAppOpsService == null) {
824 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
825 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
826 }
827 return mAppOpsService;
828 }
829
830 boolean hasUserRestriction(String restriction, int userId) {
831 return getUserManager().hasUserRestriction(restriction, userId);
832 }
833
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700834 protected RecentTasks createRecentTasks() {
835 return new RecentTasks(this, mStackSupervisor);
836 }
837
838 RecentTasks getRecentTasks() {
839 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700840 }
841
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700842 ClientLifecycleManager getLifecycleManager() {
843 return mLifecycleManager;
844 }
845
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700846 ActivityStartController getActivityStartController() {
847 return mActivityStartController;
848 }
849
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700850 TaskChangeNotificationController getTaskChangeNotificationController() {
851 return mTaskChangeNotificationController;
852 }
853
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700854 LockTaskController getLockTaskController() {
855 return mLockTaskController;
856 }
857
Yunfan Chen75157d72018-07-27 14:47:21 +0900858 /**
859 * Return the global configuration used by the process corresponding to the input pid. This is
860 * usually the global configuration with some overrides specific to that process.
861 */
862 Configuration getGlobalConfigurationForCallingPid() {
863 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800864 return getGlobalConfigurationForPid(pid);
865 }
866
867 /**
868 * Return the global configuration used by the process corresponding to the given pid.
869 */
870 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900871 if (pid == MY_PID || pid < 0) {
872 return getGlobalConfiguration();
873 }
874 synchronized (mGlobalLock) {
875 final WindowProcessController app = mPidMap.get(pid);
876 return app != null ? app.getConfiguration() : getGlobalConfiguration();
877 }
878 }
879
880 /**
881 * Return the device configuration info used by the process corresponding to the input pid.
882 * The value is consistent with the global configuration for the process.
883 */
884 @Override
885 public ConfigurationInfo getDeviceConfigurationInfo() {
886 ConfigurationInfo config = new ConfigurationInfo();
887 synchronized (mGlobalLock) {
888 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
889 config.reqTouchScreen = globalConfig.touchscreen;
890 config.reqKeyboardType = globalConfig.keyboard;
891 config.reqNavigation = globalConfig.navigation;
892 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
893 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
894 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
895 }
896 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
897 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
898 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
899 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700900 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900901 }
902 return config;
903 }
904
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700905 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700906 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700907 }
908
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700909 public static final class Lifecycle extends SystemService {
910 private final ActivityTaskManagerService mService;
911
912 public Lifecycle(Context context) {
913 super(context);
914 mService = new ActivityTaskManagerService(context);
915 }
916
917 @Override
918 public void onStart() {
919 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700920 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700921 }
922
Garfield Tan891146c2018-10-09 12:14:00 -0700923 @Override
924 public void onUnlockUser(int userId) {
925 synchronized (mService.getGlobalLock()) {
926 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
927 }
928 }
929
930 @Override
931 public void onCleanupUser(int userId) {
932 synchronized (mService.getGlobalLock()) {
933 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
934 }
935 }
936
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700937 public ActivityTaskManagerService getService() {
938 return mService;
939 }
940 }
941
942 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700943 public final int startActivity(IApplicationThread caller, String callingPackage,
944 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
945 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
946 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
947 resultWho, requestCode, startFlags, profilerInfo, bOptions,
948 UserHandle.getCallingUserId());
949 }
950
951 @Override
952 public final int startActivities(IApplicationThread caller, String callingPackage,
953 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
954 int userId) {
955 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700956 enforceNotIsolatedCaller(reason);
957 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700958 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700959 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100960 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +0000961 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700962 }
963
964 @Override
965 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
966 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
967 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
968 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
969 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
970 true /*validateIncomingUser*/);
971 }
972
973 int startActivityAsUser(IApplicationThread caller, String callingPackage,
974 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
975 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
976 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700977 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700978
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700979 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700980 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
981
982 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700983 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700984 .setCaller(caller)
985 .setCallingPackage(callingPackage)
986 .setResolvedType(resolvedType)
987 .setResultTo(resultTo)
988 .setResultWho(resultWho)
989 .setRequestCode(requestCode)
990 .setStartFlags(startFlags)
991 .setProfilerInfo(profilerInfo)
992 .setActivityOptions(bOptions)
993 .setMayWait(userId)
994 .execute();
995
996 }
997
998 @Override
999 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1000 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001001 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1002 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001003 // Refuse possible leaked file descriptors
1004 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1005 throw new IllegalArgumentException("File descriptors passed in Intent");
1006 }
1007
1008 if (!(target instanceof PendingIntentRecord)) {
1009 throw new IllegalArgumentException("Bad PendingIntent object");
1010 }
1011
1012 PendingIntentRecord pir = (PendingIntentRecord)target;
1013
1014 synchronized (mGlobalLock) {
1015 // If this is coming from the currently resumed activity, it is
1016 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001017 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001018 if (stack.mResumedActivity != null &&
1019 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001020 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 }
1022 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001023 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001025 }
1026
1027 @Override
1028 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1029 Bundle bOptions) {
1030 // Refuse possible leaked file descriptors
1031 if (intent != null && intent.hasFileDescriptors()) {
1032 throw new IllegalArgumentException("File descriptors passed in Intent");
1033 }
1034 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1035
1036 synchronized (mGlobalLock) {
1037 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1038 if (r == null) {
1039 SafeActivityOptions.abort(options);
1040 return false;
1041 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001042 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 // The caller is not running... d'oh!
1044 SafeActivityOptions.abort(options);
1045 return false;
1046 }
1047 intent = new Intent(intent);
1048 // The caller is not allowed to change the data.
1049 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1050 // And we are resetting to find the next component...
1051 intent.setComponent(null);
1052
1053 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1054
1055 ActivityInfo aInfo = null;
1056 try {
1057 List<ResolveInfo> resolves =
1058 AppGlobals.getPackageManager().queryIntentActivities(
1059 intent, r.resolvedType,
1060 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1061 UserHandle.getCallingUserId()).getList();
1062
1063 // Look for the original activity in the list...
1064 final int N = resolves != null ? resolves.size() : 0;
1065 for (int i=0; i<N; i++) {
1066 ResolveInfo rInfo = resolves.get(i);
1067 if (rInfo.activityInfo.packageName.equals(r.packageName)
1068 && rInfo.activityInfo.name.equals(r.info.name)) {
1069 // We found the current one... the next matching is
1070 // after it.
1071 i++;
1072 if (i<N) {
1073 aInfo = resolves.get(i).activityInfo;
1074 }
1075 if (debug) {
1076 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1077 + "/" + r.info.name);
1078 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1079 ? "null" : aInfo.packageName + "/" + aInfo.name));
1080 }
1081 break;
1082 }
1083 }
1084 } catch (RemoteException e) {
1085 }
1086
1087 if (aInfo == null) {
1088 // Nobody who is next!
1089 SafeActivityOptions.abort(options);
1090 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1091 return false;
1092 }
1093
1094 intent.setComponent(new ComponentName(
1095 aInfo.applicationInfo.packageName, aInfo.name));
1096 intent.setFlags(intent.getFlags()&~(
1097 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1098 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1099 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1100 FLAG_ACTIVITY_NEW_TASK));
1101
1102 // Okay now we need to start the new activity, replacing the currently running activity.
1103 // This is a little tricky because we want to start the new one as if the current one is
1104 // finished, but not finish the current one first so that there is no flicker.
1105 // And thus...
1106 final boolean wasFinishing = r.finishing;
1107 r.finishing = true;
1108
1109 // Propagate reply information over to the new activity.
1110 final ActivityRecord resultTo = r.resultTo;
1111 final String resultWho = r.resultWho;
1112 final int requestCode = r.requestCode;
1113 r.resultTo = null;
1114 if (resultTo != null) {
1115 resultTo.removeResultsLocked(r, resultWho, requestCode);
1116 }
1117
1118 final long origId = Binder.clearCallingIdentity();
1119 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001120 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001121 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001122 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 .setResolvedType(r.resolvedType)
1124 .setActivityInfo(aInfo)
1125 .setResultTo(resultTo != null ? resultTo.appToken : null)
1126 .setResultWho(resultWho)
1127 .setRequestCode(requestCode)
1128 .setCallingPid(-1)
1129 .setCallingUid(r.launchedFromUid)
1130 .setCallingPackage(r.launchedFromPackage)
1131 .setRealCallingPid(-1)
1132 .setRealCallingUid(r.launchedFromUid)
1133 .setActivityOptions(options)
1134 .execute();
1135 Binder.restoreCallingIdentity(origId);
1136
1137 r.finishing = wasFinishing;
1138 if (res != ActivityManager.START_SUCCESS) {
1139 return false;
1140 }
1141 return true;
1142 }
1143 }
1144
1145 @Override
1146 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1147 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1148 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1149 final WaitResult res = new WaitResult();
1150 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001151 enforceNotIsolatedCaller("startActivityAndWait");
1152 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1153 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001154 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001155 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001156 .setCaller(caller)
1157 .setCallingPackage(callingPackage)
1158 .setResolvedType(resolvedType)
1159 .setResultTo(resultTo)
1160 .setResultWho(resultWho)
1161 .setRequestCode(requestCode)
1162 .setStartFlags(startFlags)
1163 .setActivityOptions(bOptions)
1164 .setMayWait(userId)
1165 .setProfilerInfo(profilerInfo)
1166 .setWaitResult(res)
1167 .execute();
1168 }
1169 return res;
1170 }
1171
1172 @Override
1173 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1174 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1175 int startFlags, Configuration config, Bundle bOptions, int userId) {
1176 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001177 enforceNotIsolatedCaller("startActivityWithConfig");
1178 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1179 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001180 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001181 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
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 .setGlobalConfiguration(config)
1190 .setActivityOptions(bOptions)
1191 .setMayWait(userId)
1192 .execute();
1193 }
1194 }
1195
Alison Cichowlas3e340502018-08-07 17:15:01 -04001196
1197 @Override
1198 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1199 int callingUid = Binder.getCallingUid();
1200 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1201 throw new SecurityException("Only the system process can request a permission token, "
1202 + "received request from uid: " + callingUid);
1203 }
1204 IBinder permissionToken = new Binder();
1205 synchronized (mGlobalLock) {
1206 mStartActivitySources.put(permissionToken, delegatorToken);
1207 }
1208
1209 Message expireMsg = PooledLambda.obtainMessage(
1210 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1211 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1212
1213 Message forgetMsg = PooledLambda.obtainMessage(
1214 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1215 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1216
1217 return permissionToken;
1218 }
1219
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 @Override
1221 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1222 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001223 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1224 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001226 // permission grants) as any app that may launch one of your own activities. So we only
1227 // allow this in two cases:
1228 // 1) The caller is an activity that is part of the core framework, and then only when it
1229 // is running as the system.
1230 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1231 // can only be requested by a system activity, which may then delegate this call to
1232 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001233 final ActivityRecord sourceRecord;
1234 final int targetUid;
1235 final String targetPackage;
1236 final boolean isResolver;
1237 synchronized (mGlobalLock) {
1238 if (resultTo == null) {
1239 throw new SecurityException("Must be called from an activity");
1240 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001241 final IBinder sourceToken;
1242 if (permissionToken != null) {
1243 // To even attempt to use a permissionToken, an app must also have this signature
1244 // permission.
1245 mAmInternal.enforceCallingPermission(
1246 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1247 "startActivityAsCaller");
1248 // If called with a permissionToken, we want the sourceRecord from the delegator
1249 // activity that requested this token.
1250 sourceToken = mStartActivitySources.remove(permissionToken);
1251 if (sourceToken == null) {
1252 // Invalid permissionToken, check if it recently expired.
1253 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1254 throw new SecurityException("Called with expired permission token: "
1255 + permissionToken);
1256 } else {
1257 throw new SecurityException("Called with invalid permission token: "
1258 + permissionToken);
1259 }
1260 }
1261 } else {
1262 // This method was called directly by the source.
1263 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001265
Wale Ogunwaled32da472018-11-16 07:19:28 -08001266 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267 if (sourceRecord == null) {
1268 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001269 }
1270 if (sourceRecord.app == null) {
1271 throw new SecurityException("Called without a process attached to activity");
1272 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001273
1274 // Whether called directly or from a delegate, the source activity must be from the
1275 // android package.
1276 if (!sourceRecord.info.packageName.equals("android")) {
1277 throw new SecurityException("Must be called from an activity that is "
1278 + "declared in the android package");
1279 }
1280
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001281 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 // This is still okay, as long as this activity is running under the
1283 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001284 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001286 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 + " must be system uid or original calling uid "
1288 + sourceRecord.launchedFromUid);
1289 }
1290 }
1291 if (ignoreTargetSecurity) {
1292 if (intent.getComponent() == null) {
1293 throw new SecurityException(
1294 "Component must be specified with ignoreTargetSecurity");
1295 }
1296 if (intent.getSelector() != null) {
1297 throw new SecurityException(
1298 "Selector not allowed with ignoreTargetSecurity");
1299 }
1300 }
1301 targetUid = sourceRecord.launchedFromUid;
1302 targetPackage = sourceRecord.launchedFromPackage;
1303 isResolver = sourceRecord.isResolverOrChildActivity();
1304 }
1305
1306 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001307 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001308 }
1309
1310 // TODO: Switch to user app stacks here.
1311 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001312 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001313 .setCallingUid(targetUid)
1314 .setCallingPackage(targetPackage)
1315 .setResolvedType(resolvedType)
1316 .setResultTo(resultTo)
1317 .setResultWho(resultWho)
1318 .setRequestCode(requestCode)
1319 .setStartFlags(startFlags)
1320 .setActivityOptions(bOptions)
1321 .setMayWait(userId)
1322 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1323 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1324 .execute();
1325 } catch (SecurityException e) {
1326 // XXX need to figure out how to propagate to original app.
1327 // A SecurityException here is generally actually a fault of the original
1328 // calling activity (such as a fairly granting permissions), so propagate it
1329 // back to them.
1330 /*
1331 StringBuilder msg = new StringBuilder();
1332 msg.append("While launching");
1333 msg.append(intent.toString());
1334 msg.append(": ");
1335 msg.append(e.getMessage());
1336 */
1337 throw e;
1338 }
1339 }
1340
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001341 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1342 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1343 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1344 }
1345
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 @Override
1347 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1348 Intent intent, String resolvedType, IVoiceInteractionSession session,
1349 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1350 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001351 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001352 if (session == null || interactor == null) {
1353 throw new NullPointerException("null session or interactor");
1354 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001355 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001356 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001357 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 .setCallingUid(callingUid)
1359 .setCallingPackage(callingPackage)
1360 .setResolvedType(resolvedType)
1361 .setVoiceSession(session)
1362 .setVoiceInteractor(interactor)
1363 .setStartFlags(startFlags)
1364 .setProfilerInfo(profilerInfo)
1365 .setActivityOptions(bOptions)
1366 .setMayWait(userId)
1367 .execute();
1368 }
1369
1370 @Override
1371 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1372 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001373 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1374 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001376 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 .setCallingUid(callingUid)
1378 .setCallingPackage(callingPackage)
1379 .setResolvedType(resolvedType)
1380 .setActivityOptions(bOptions)
1381 .setMayWait(userId)
1382 .execute();
1383 }
1384
1385 @Override
1386 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1387 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001388 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 final int callingPid = Binder.getCallingPid();
1390 final long origId = Binder.clearCallingIdentity();
1391 try {
1392 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001393 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1394 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001395
1396 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001397 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1398 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1400 recentsUid, assistDataReceiver);
1401 }
1402 } finally {
1403 Binder.restoreCallingIdentity(origId);
1404 }
1405 }
1406
1407 @Override
1408 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 "startActivityFromRecents()");
1411
1412 final int callingPid = Binder.getCallingPid();
1413 final int callingUid = Binder.getCallingUid();
1414 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1415 final long origId = Binder.clearCallingIdentity();
1416 try {
1417 synchronized (mGlobalLock) {
1418 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1419 safeOptions);
1420 }
1421 } finally {
1422 Binder.restoreCallingIdentity(origId);
1423 }
1424 }
1425
1426 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001427 * Public API to check if the client is allowed to start an activity on specified display.
1428 *
1429 * If the target display is private or virtual, some restrictions will apply.
1430 *
1431 * @param displayId Target display id.
1432 * @param intent Intent used to launch the activity.
1433 * @param resolvedType The MIME type of the intent.
1434 * @param userId The id of the user for whom the call is made.
1435 * @return {@code true} if a call to start an activity on the target display should succeed and
1436 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1437 */
1438 @Override
1439 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1440 String resolvedType, int userId) {
1441 final int callingUid = Binder.getCallingUid();
1442 final int callingPid = Binder.getCallingPid();
1443 final long origId = Binder.clearCallingIdentity();
1444
1445 try {
1446 // Collect information about the target of the Intent.
1447 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1448 0 /* startFlags */, null /* profilerInfo */, userId,
1449 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1450 UserHandle.USER_NULL));
1451 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1452
1453 synchronized (mGlobalLock) {
1454 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1455 aInfo);
1456 }
1457 } finally {
1458 Binder.restoreCallingIdentity(origId);
1459 }
1460 }
1461
1462 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 * This is the internal entry point for handling Activity.finish().
1464 *
1465 * @param token The Binder token referencing the Activity we want to finish.
1466 * @param resultCode Result code, if any, from this Activity.
1467 * @param resultData Result data (Intent), if any, from this Activity.
1468 * @param finishTask Whether to finish the task associated with this Activity.
1469 *
1470 * @return Returns true if the activity successfully finished, or false if it is still running.
1471 */
1472 @Override
1473 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1474 int finishTask) {
1475 // Refuse possible leaked file descriptors
1476 if (resultData != null && resultData.hasFileDescriptors()) {
1477 throw new IllegalArgumentException("File descriptors passed in Intent");
1478 }
1479
1480 synchronized (mGlobalLock) {
1481 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1482 if (r == null) {
1483 return true;
1484 }
1485 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001486 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001487 ActivityRecord rootR = tr.getRootActivity();
1488 if (rootR == null) {
1489 Slog.w(TAG, "Finishing task with all activities already finished");
1490 }
1491 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1492 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001493 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494 return false;
1495 }
1496
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001497 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1498 // We should consolidate.
1499 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001501 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 if (next != null) {
1503 // ask watcher if this is allowed
1504 boolean resumeOK = true;
1505 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001506 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001507 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001508 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001509 Watchdog.getInstance().setActivityController(null);
1510 }
1511
1512 if (!resumeOK) {
1513 Slog.i(TAG, "Not finishing activity because controller resumed");
1514 return false;
1515 }
1516 }
1517 }
1518 final long origId = Binder.clearCallingIdentity();
1519 try {
1520 boolean res;
1521 final boolean finishWithRootActivity =
1522 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1523 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1524 || (finishWithRootActivity && r == rootR)) {
1525 // If requested, remove the task that is associated to this activity only if it
1526 // was the root activity in the task. The result code and data is ignored
1527 // because we don't support returning them across task boundaries. Also, to
1528 // keep backwards compatibility we remove the task from recents when finishing
1529 // task with root activity.
1530 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1531 finishWithRootActivity, "finish-activity");
1532 if (!res) {
1533 Slog.i(TAG, "Removing task failed to finish activity");
1534 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001535 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001536 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001537 } else {
1538 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1539 resultData, "app-request", true);
1540 if (!res) {
1541 Slog.i(TAG, "Failed to finish by app-request");
1542 }
1543 }
1544 return res;
1545 } finally {
1546 Binder.restoreCallingIdentity(origId);
1547 }
1548 }
1549 }
1550
1551 @Override
1552 public boolean finishActivityAffinity(IBinder token) {
1553 synchronized (mGlobalLock) {
1554 final long origId = Binder.clearCallingIdentity();
1555 try {
1556 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1557 if (r == null) {
1558 return false;
1559 }
1560
1561 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1562 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001563 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001564 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 return false;
1566 }
1567 return task.getStack().finishActivityAffinityLocked(r);
1568 } finally {
1569 Binder.restoreCallingIdentity(origId);
1570 }
1571 }
1572 }
1573
1574 @Override
1575 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1576 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001577 try {
1578 WindowProcessController proc = null;
1579 synchronized (mGlobalLock) {
1580 ActivityStack stack = ActivityRecord.getStackLocked(token);
1581 if (stack == null) {
1582 return;
1583 }
1584 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1585 false /* fromTimeout */, false /* processPausingActivities */, config);
1586 if (r != null) {
1587 proc = r.app;
1588 }
1589 if (stopProfiling && proc != null) {
1590 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 }
1592 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001593 } finally {
1594 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 }
1597
1598 @Override
1599 public final void activityResumed(IBinder token) {
1600 final long origId = Binder.clearCallingIdentity();
1601 synchronized (mGlobalLock) {
1602 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001603 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001604 }
1605 Binder.restoreCallingIdentity(origId);
1606 }
1607
1608 @Override
1609 public final void activityPaused(IBinder token) {
1610 final long origId = Binder.clearCallingIdentity();
1611 synchronized (mGlobalLock) {
1612 ActivityStack stack = ActivityRecord.getStackLocked(token);
1613 if (stack != null) {
1614 stack.activityPausedLocked(token, false);
1615 }
1616 }
1617 Binder.restoreCallingIdentity(origId);
1618 }
1619
1620 @Override
1621 public final void activityStopped(IBinder token, Bundle icicle,
1622 PersistableBundle persistentState, CharSequence description) {
1623 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1624
1625 // Refuse possible leaked file descriptors
1626 if (icicle != null && icicle.hasFileDescriptors()) {
1627 throw new IllegalArgumentException("File descriptors passed in Bundle");
1628 }
1629
1630 final long origId = Binder.clearCallingIdentity();
1631
1632 synchronized (mGlobalLock) {
1633 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1634 if (r != null) {
1635 r.activityStoppedLocked(icicle, persistentState, description);
1636 }
1637 }
1638
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001639 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001640
1641 Binder.restoreCallingIdentity(origId);
1642 }
1643
1644 @Override
1645 public final void activityDestroyed(IBinder token) {
1646 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1647 synchronized (mGlobalLock) {
1648 ActivityStack stack = ActivityRecord.getStackLocked(token);
1649 if (stack != null) {
1650 stack.activityDestroyedLocked(token, "activityDestroyed");
1651 }
1652 }
1653 }
1654
1655 @Override
1656 public final void activityRelaunched(IBinder token) {
1657 final long origId = Binder.clearCallingIdentity();
1658 synchronized (mGlobalLock) {
1659 mStackSupervisor.activityRelaunchedLocked(token);
1660 }
1661 Binder.restoreCallingIdentity(origId);
1662 }
1663
1664 public final void activitySlept(IBinder token) {
1665 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1666
1667 final long origId = Binder.clearCallingIdentity();
1668
1669 synchronized (mGlobalLock) {
1670 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1671 if (r != null) {
1672 mStackSupervisor.activitySleptLocked(r);
1673 }
1674 }
1675
1676 Binder.restoreCallingIdentity(origId);
1677 }
1678
1679 @Override
1680 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1681 synchronized (mGlobalLock) {
1682 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1683 if (r == null) {
1684 return;
1685 }
1686 final long origId = Binder.clearCallingIdentity();
1687 try {
1688 r.setRequestedOrientation(requestedOrientation);
1689 } finally {
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692 }
1693 }
1694
1695 @Override
1696 public int getRequestedOrientation(IBinder token) {
1697 synchronized (mGlobalLock) {
1698 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1699 if (r == null) {
1700 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1701 }
1702 return r.getRequestedOrientation();
1703 }
1704 }
1705
1706 @Override
1707 public void setImmersive(IBinder token, boolean immersive) {
1708 synchronized (mGlobalLock) {
1709 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1710 if (r == null) {
1711 throw new IllegalArgumentException();
1712 }
1713 r.immersive = immersive;
1714
1715 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001716 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001718 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 }
1720 }
1721 }
1722
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001723 void applyUpdateLockStateLocked(ActivityRecord r) {
1724 // Modifications to the UpdateLock state are done on our handler, outside
1725 // the activity manager's locks. The new state is determined based on the
1726 // state *now* of the relevant activity record. The object is passed to
1727 // the handler solely for logging detail, not to be consulted/modified.
1728 final boolean nextState = r != null && r.immersive;
1729 mH.post(() -> {
1730 if (mUpdateLock.isHeld() != nextState) {
1731 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1732 "Applying new update lock state '" + nextState + "' for " + r);
1733 if (nextState) {
1734 mUpdateLock.acquire();
1735 } else {
1736 mUpdateLock.release();
1737 }
1738 }
1739 });
1740 }
1741
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 @Override
1743 public boolean isImmersive(IBinder token) {
1744 synchronized (mGlobalLock) {
1745 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1746 if (r == null) {
1747 throw new IllegalArgumentException();
1748 }
1749 return r.immersive;
1750 }
1751 }
1752
1753 @Override
1754 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001755 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001757 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 return (r != null) ? r.immersive : false;
1759 }
1760 }
1761
1762 @Override
1763 public void overridePendingTransition(IBinder token, String packageName,
1764 int enterAnim, int exitAnim) {
1765 synchronized (mGlobalLock) {
1766 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1767 if (self == null) {
1768 return;
1769 }
1770
1771 final long origId = Binder.clearCallingIdentity();
1772
1773 if (self.isState(
1774 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001775 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001776 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 }
1778
1779 Binder.restoreCallingIdentity(origId);
1780 }
1781 }
1782
1783 @Override
1784 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001785 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001786 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001787 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001788 if (r == null) {
1789 return ActivityManager.COMPAT_MODE_UNKNOWN;
1790 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001791 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001792 }
1793 }
1794
1795 @Override
1796 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001797 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001798 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001801 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 if (r == null) {
1803 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1804 return;
1805 }
1806 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001807 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 }
1809 }
1810
1811 @Override
1812 public int getLaunchedFromUid(IBinder activityToken) {
1813 ActivityRecord srec;
1814 synchronized (mGlobalLock) {
1815 srec = ActivityRecord.forTokenLocked(activityToken);
1816 }
1817 if (srec == null) {
1818 return -1;
1819 }
1820 return srec.launchedFromUid;
1821 }
1822
1823 @Override
1824 public String getLaunchedFromPackage(IBinder activityToken) {
1825 ActivityRecord srec;
1826 synchronized (mGlobalLock) {
1827 srec = ActivityRecord.forTokenLocked(activityToken);
1828 }
1829 if (srec == null) {
1830 return null;
1831 }
1832 return srec.launchedFromPackage;
1833 }
1834
1835 @Override
1836 public boolean convertFromTranslucent(IBinder token) {
1837 final long origId = Binder.clearCallingIdentity();
1838 try {
1839 synchronized (mGlobalLock) {
1840 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1841 if (r == null) {
1842 return false;
1843 }
1844 final boolean translucentChanged = r.changeWindowTranslucency(true);
1845 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001846 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001847 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001848 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 return translucentChanged;
1850 }
1851 } finally {
1852 Binder.restoreCallingIdentity(origId);
1853 }
1854 }
1855
1856 @Override
1857 public boolean convertToTranslucent(IBinder token, Bundle options) {
1858 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1859 final long origId = Binder.clearCallingIdentity();
1860 try {
1861 synchronized (mGlobalLock) {
1862 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1863 if (r == null) {
1864 return false;
1865 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001866 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 int index = task.mActivities.lastIndexOf(r);
1868 if (index > 0) {
1869 ActivityRecord under = task.mActivities.get(index - 1);
1870 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1871 }
1872 final boolean translucentChanged = r.changeWindowTranslucency(false);
1873 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001874 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001876 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001877 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 return translucentChanged;
1879 }
1880 } finally {
1881 Binder.restoreCallingIdentity(origId);
1882 }
1883 }
1884
1885 @Override
1886 public void notifyActivityDrawn(IBinder token) {
1887 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1888 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001889 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001891 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 }
1893 }
1894 }
1895
1896 @Override
1897 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1898 synchronized (mGlobalLock) {
1899 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1900 if (r == null) {
1901 return;
1902 }
1903 r.reportFullyDrawnLocked(restoredFromBundle);
1904 }
1905 }
1906
1907 @Override
1908 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1909 synchronized (mGlobalLock) {
1910 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1911 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1912 return stack.mDisplayId;
1913 }
1914 return DEFAULT_DISPLAY;
1915 }
1916 }
1917
1918 @Override
1919 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 long ident = Binder.clearCallingIdentity();
1922 try {
1923 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001924 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001926 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 }
1928 return null;
1929 }
1930 } finally {
1931 Binder.restoreCallingIdentity(ident);
1932 }
1933 }
1934
1935 @Override
1936 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1939 final long callingId = Binder.clearCallingIdentity();
1940 try {
1941 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001942 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001943 if (stack == null) {
1944 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1945 return;
1946 }
1947 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001948 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001949 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 }
1951 }
1952 } finally {
1953 Binder.restoreCallingIdentity(callingId);
1954 }
1955 }
1956
1957 @Override
1958 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001959 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1961 final long callingId = Binder.clearCallingIdentity();
1962 try {
1963 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001964 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001965 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 if (task == null) {
1967 return;
1968 }
1969 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001970 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001971 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001972 }
1973 }
1974 } finally {
1975 Binder.restoreCallingIdentity(callingId);
1976 }
1977 }
1978
1979 @Override
1980 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001981 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 synchronized (mGlobalLock) {
1983 final long ident = Binder.clearCallingIdentity();
1984 try {
1985 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1986 "remove-task");
1987 } finally {
1988 Binder.restoreCallingIdentity(ident);
1989 }
1990 }
1991 }
1992
1993 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001994 public void removeAllVisibleRecentTasks() {
1995 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1996 synchronized (mGlobalLock) {
1997 final long ident = Binder.clearCallingIdentity();
1998 try {
1999 getRecentTasks().removeAllVisibleTasks();
2000 } finally {
2001 Binder.restoreCallingIdentity(ident);
2002 }
2003 }
2004 }
2005
2006 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2008 synchronized (mGlobalLock) {
2009 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2010 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002011 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 }
2013 }
2014 return false;
2015 }
2016
2017 @Override
2018 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2019 Intent resultData) {
2020
2021 synchronized (mGlobalLock) {
2022 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2023 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002024 return r.getActivityStack().navigateUpToLocked(
2025 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 }
2027 return false;
2028 }
2029 }
2030
2031 /**
2032 * Attempts to move a task backwards in z-order (the order of activities within the task is
2033 * unchanged).
2034 *
2035 * There are several possible results of this call:
2036 * - if the task is locked, then we will show the lock toast
2037 * - if there is a task behind the provided task, then that task is made visible and resumed as
2038 * this task is moved to the back
2039 * - otherwise, if there are no other tasks in the stack:
2040 * - if this task is in the pinned stack, then we remove the stack completely, which will
2041 * have the effect of moving the task to the top or bottom of the fullscreen stack
2042 * (depending on whether it is visible)
2043 * - otherwise, we simply return home and hide this task
2044 *
2045 * @param token A reference to the activity we wish to move
2046 * @param nonRoot If false then this only works if the activity is the root
2047 * of a task; if true it will work for any activity in a task.
2048 * @return Returns true if the move completed, false if not.
2049 */
2050 @Override
2051 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002052 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002053 synchronized (mGlobalLock) {
2054 final long origId = Binder.clearCallingIdentity();
2055 try {
2056 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002057 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 if (task != null) {
2059 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2060 }
2061 } finally {
2062 Binder.restoreCallingIdentity(origId);
2063 }
2064 }
2065 return false;
2066 }
2067
2068 @Override
2069 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002070 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 long ident = Binder.clearCallingIdentity();
2072 Rect rect = new Rect();
2073 try {
2074 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2077 if (task == null) {
2078 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2079 return rect;
2080 }
2081 if (task.getStack() != null) {
2082 // Return the bounds from window manager since it will be adjusted for various
2083 // things like the presense of a docked stack for tasks that aren't resizeable.
2084 task.getWindowContainerBounds(rect);
2085 } else {
2086 // Task isn't in window manager yet since it isn't associated with a stack.
2087 // Return the persist value from activity manager
2088 if (!task.matchParentBounds()) {
2089 rect.set(task.getBounds());
2090 } else if (task.mLastNonFullscreenBounds != null) {
2091 rect.set(task.mLastNonFullscreenBounds);
2092 }
2093 }
2094 }
2095 } finally {
2096 Binder.restoreCallingIdentity(ident);
2097 }
2098 return rect;
2099 }
2100
2101 @Override
2102 public ActivityManager.TaskDescription getTaskDescription(int id) {
2103 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002104 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002105 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002106 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2108 if (tr != null) {
2109 return tr.lastTaskDescription;
2110 }
2111 }
2112 return null;
2113 }
2114
2115 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002116 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2117 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2118 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2119 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2120 return;
2121 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002122 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002123 synchronized (mGlobalLock) {
2124 final long ident = Binder.clearCallingIdentity();
2125 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002126 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002127 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002128 if (task == null) {
2129 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2130 return;
2131 }
2132
2133 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2134 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2135
2136 if (!task.isActivityTypeStandardOrUndefined()) {
2137 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2138 + " non-standard task " + taskId + " to windowing mode="
2139 + windowingMode);
2140 }
2141
2142 final ActivityStack stack = task.getStack();
2143 if (toTop) {
2144 stack.moveToFront("setTaskWindowingMode", task);
2145 }
2146 stack.setWindowingMode(windowingMode);
2147 } finally {
2148 Binder.restoreCallingIdentity(ident);
2149 }
2150 }
2151 }
2152
2153 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002155 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156 ActivityRecord r = getCallingRecordLocked(token);
2157 return r != null ? r.info.packageName : null;
2158 }
2159 }
2160
2161 @Override
2162 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002163 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 ActivityRecord r = getCallingRecordLocked(token);
2165 return r != null ? r.intent.getComponent() : null;
2166 }
2167 }
2168
2169 private ActivityRecord getCallingRecordLocked(IBinder token) {
2170 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2171 if (r == null) {
2172 return null;
2173 }
2174 return r.resultTo;
2175 }
2176
2177 @Override
2178 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002179 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180
2181 synchronized (mGlobalLock) {
2182 final long origId = Binder.clearCallingIdentity();
2183 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002184 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 } finally {
2186 Binder.restoreCallingIdentity(origId);
2187 }
2188 }
2189 }
2190
2191 /**
2192 * TODO: Add mController hook
2193 */
2194 @Override
2195 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002196 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197
2198 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2199 synchronized (mGlobalLock) {
2200 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2201 false /* fromRecents */);
2202 }
2203 }
2204
2205 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2206 boolean fromRecents) {
2207
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002208 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 Binder.getCallingUid(), -1, -1, "Task to front")) {
2210 SafeActivityOptions.abort(options);
2211 return;
2212 }
2213 final long origId = Binder.clearCallingIdentity();
2214 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002215 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002216 if (task == null) {
2217 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002218 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 return;
2220 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002221 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002223 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 return;
2225 }
2226 ActivityOptions realOptions = options != null
2227 ? options.getOptions(mStackSupervisor)
2228 : null;
2229 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2230 false /* forceNonResizable */);
2231
2232 final ActivityRecord topActivity = task.getTopActivity();
2233 if (topActivity != null) {
2234
2235 // We are reshowing a task, use a starting window to hide the initial draw delay
2236 // so the transition can start earlier.
2237 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2238 true /* taskSwitch */, fromRecents);
2239 }
2240 } finally {
2241 Binder.restoreCallingIdentity(origId);
2242 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 }
2244
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002245 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2246 int callingPid, int callingUid, String name) {
2247 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2248 return true;
2249 }
2250
2251 if (getRecentTasks().isCallerRecents(sourceUid)) {
2252 return true;
2253 }
2254
2255 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2256 if (perm == PackageManager.PERMISSION_GRANTED) {
2257 return true;
2258 }
2259 if (checkAllowAppSwitchUid(sourceUid)) {
2260 return true;
2261 }
2262
2263 // If the actual IPC caller is different from the logical source, then
2264 // also see if they are allowed to control app switches.
2265 if (callingUid != -1 && callingUid != sourceUid) {
2266 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2267 if (perm == PackageManager.PERMISSION_GRANTED) {
2268 return true;
2269 }
2270 if (checkAllowAppSwitchUid(callingUid)) {
2271 return true;
2272 }
2273 }
2274
2275 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2276 return false;
2277 }
2278
2279 private boolean checkAllowAppSwitchUid(int uid) {
2280 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2281 if (types != null) {
2282 for (int i = types.size() - 1; i >= 0; i--) {
2283 if (types.valueAt(i).intValue() == uid) {
2284 return true;
2285 }
2286 }
2287 }
2288 return false;
2289 }
2290
2291 @Override
2292 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2293 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2294 "setActivityController()");
2295 synchronized (mGlobalLock) {
2296 mController = controller;
2297 mControllerIsAMonkey = imAMonkey;
2298 Watchdog.getInstance().setActivityController(controller);
2299 }
2300 }
2301
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002302 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002303 synchronized (mGlobalLock) {
2304 return mController != null && mControllerIsAMonkey;
2305 }
2306 }
2307
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 @Override
2309 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2310 synchronized (mGlobalLock) {
2311 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2312 }
2313 }
2314
2315 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002316 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2317 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2318 }
2319
2320 @Override
2321 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2322 @WindowConfiguration.ActivityType int ignoreActivityType,
2323 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2324 final int callingUid = Binder.getCallingUid();
2325 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2326
2327 synchronized (mGlobalLock) {
2328 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2329
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002330 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002331 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002332 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 ignoreWindowingMode, callingUid, allowed);
2334 }
2335
2336 return list;
2337 }
2338
2339 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002340 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2341 synchronized (mGlobalLock) {
2342 final long origId = Binder.clearCallingIdentity();
2343 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2344 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002345 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002346 }
2347 Binder.restoreCallingIdentity(origId);
2348 }
2349 }
2350
2351 @Override
2352 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002353 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354 ActivityStack stack = ActivityRecord.getStackLocked(token);
2355 if (stack != null) {
2356 return stack.willActivityBeVisibleLocked(token);
2357 }
2358 return false;
2359 }
2360 }
2361
2362 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002363 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002364 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002365 synchronized (mGlobalLock) {
2366 final long ident = Binder.clearCallingIdentity();
2367 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002368 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002369 if (task == null) {
2370 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2371 return;
2372 }
2373
2374 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2375 + " to stackId=" + stackId + " toTop=" + toTop);
2376
Wale Ogunwaled32da472018-11-16 07:19:28 -08002377 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002378 if (stack == null) {
2379 throw new IllegalStateException(
2380 "moveTaskToStack: No stack for stackId=" + stackId);
2381 }
2382 if (!stack.isActivityTypeStandardOrUndefined()) {
2383 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2384 + taskId + " to stack " + stackId);
2385 }
2386 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002387 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002388 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2389 }
2390 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2391 "moveTaskToStack");
2392 } finally {
2393 Binder.restoreCallingIdentity(ident);
2394 }
2395 }
2396 }
2397
2398 @Override
2399 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2400 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002401 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002402
2403 final long ident = Binder.clearCallingIdentity();
2404 try {
2405 synchronized (mGlobalLock) {
2406 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002407 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002408 if (stack == null) {
2409 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2410 return;
2411 }
2412 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2413 throw new IllegalArgumentException("Stack: " + stackId
2414 + " doesn't support animated resize.");
2415 }
2416 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2417 animationDuration, false /* fromFullscreen */);
2418 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002419 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002420 if (stack == null) {
2421 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2422 return;
2423 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002424 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002425 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2426 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2427 }
2428 }
2429 } finally {
2430 Binder.restoreCallingIdentity(ident);
2431 }
2432 }
2433
2434 /**
2435 * Moves the specified task to the primary-split-screen stack.
2436 *
2437 * @param taskId Id of task to move.
2438 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2439 * exist already. See
2440 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2441 * and
2442 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2443 * @param toTop If the task and stack should be moved to the top.
2444 * @param animate Whether we should play an animation for the moving the task.
2445 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2446 * stack. Pass {@code null} to use default bounds.
2447 * @param showRecents If the recents activity should be shown on the other side of the task
2448 * going into split-screen mode.
2449 */
2450 @Override
2451 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2452 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002453 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002454 "setTaskWindowingModeSplitScreenPrimary()");
2455 synchronized (mGlobalLock) {
2456 final long ident = Binder.clearCallingIdentity();
2457 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002458 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002459 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002460 if (task == null) {
2461 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2462 return false;
2463 }
2464 if (DEBUG_STACK) Slog.d(TAG_STACK,
2465 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2466 + " to createMode=" + createMode + " toTop=" + toTop);
2467 if (!task.isActivityTypeStandardOrUndefined()) {
2468 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2469 + " non-standard task " + taskId + " to split-screen windowing mode");
2470 }
2471
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002472 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002473 final int windowingMode = task.getWindowingMode();
2474 final ActivityStack stack = task.getStack();
2475 if (toTop) {
2476 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2477 }
2478 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002479 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2480 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002481 return windowingMode != task.getWindowingMode();
2482 } finally {
2483 Binder.restoreCallingIdentity(ident);
2484 }
2485 }
2486 }
2487
2488 /**
2489 * Removes stacks in the input windowing modes from the system if they are of activity type
2490 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2491 */
2492 @Override
2493 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002494 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002495 "removeStacksInWindowingModes()");
2496
2497 synchronized (mGlobalLock) {
2498 final long ident = Binder.clearCallingIdentity();
2499 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002500 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002501 } finally {
2502 Binder.restoreCallingIdentity(ident);
2503 }
2504 }
2505 }
2506
2507 @Override
2508 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002509 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002510 "removeStacksWithActivityTypes()");
2511
2512 synchronized (mGlobalLock) {
2513 final long ident = Binder.clearCallingIdentity();
2514 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002515 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002516 } finally {
2517 Binder.restoreCallingIdentity(ident);
2518 }
2519 }
2520 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002521
2522 @Override
2523 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2524 int userId) {
2525 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002526 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2527 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 final boolean detailed = checkGetTasksPermission(
2530 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2531 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002532 == PackageManager.PERMISSION_GRANTED;
2533
2534 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002535 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002536 callingUid);
2537 }
2538 }
2539
2540 @Override
2541 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002542 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002543 long ident = Binder.clearCallingIdentity();
2544 try {
2545 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002546 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002547 }
2548 } finally {
2549 Binder.restoreCallingIdentity(ident);
2550 }
2551 }
2552
2553 @Override
2554 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002555 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002556 long ident = Binder.clearCallingIdentity();
2557 try {
2558 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002559 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002560 }
2561 } finally {
2562 Binder.restoreCallingIdentity(ident);
2563 }
2564 }
2565
2566 @Override
2567 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002568 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002569 final long callingUid = Binder.getCallingUid();
2570 final long origId = Binder.clearCallingIdentity();
2571 try {
2572 synchronized (mGlobalLock) {
2573 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2576 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2577 }
2578 } finally {
2579 Binder.restoreCallingIdentity(origId);
2580 }
2581 }
2582
2583 @Override
2584 public void startLockTaskModeByToken(IBinder token) {
2585 synchronized (mGlobalLock) {
2586 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2587 if (r == null) {
2588 return;
2589 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002590 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 }
2592 }
2593
2594 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002595 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002596 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002597 // This makes inner call to look as if it was initiated by system.
2598 long ident = Binder.clearCallingIdentity();
2599 try {
2600 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002601 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002602 MATCH_TASK_IN_STACKS_ONLY);
2603 if (task == null) {
2604 return;
2605 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002606
2607 // When starting lock task mode the stack must be in front and focused
2608 task.getStack().moveToFront("startSystemLockTaskMode");
2609 startLockTaskModeLocked(task, true /* isSystemCaller */);
2610 }
2611 } finally {
2612 Binder.restoreCallingIdentity(ident);
2613 }
2614 }
2615
2616 @Override
2617 public void stopLockTaskModeByToken(IBinder token) {
2618 synchronized (mGlobalLock) {
2619 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2620 if (r == null) {
2621 return;
2622 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002623 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002624 }
2625 }
2626
2627 /**
2628 * This API should be called by SystemUI only when user perform certain action to dismiss
2629 * lock task mode. We should only dismiss pinned lock task mode in this case.
2630 */
2631 @Override
2632 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002633 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002634 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2635 }
2636
2637 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2638 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2639 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2640 return;
2641 }
2642
Wale Ogunwaled32da472018-11-16 07:19:28 -08002643 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002644 if (stack == null || task != stack.topTask()) {
2645 throw new IllegalArgumentException("Invalid task, not in foreground");
2646 }
2647
2648 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2649 // system or a specific app.
2650 // * System-initiated requests will only start the pinned mode (screen pinning)
2651 // * App-initiated requests
2652 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2653 // - will start the pinned mode, otherwise
2654 final int callingUid = Binder.getCallingUid();
2655 long ident = Binder.clearCallingIdentity();
2656 try {
2657 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002658 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002659
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002660 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661 } finally {
2662 Binder.restoreCallingIdentity(ident);
2663 }
2664 }
2665
2666 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2667 final int callingUid = Binder.getCallingUid();
2668 long ident = Binder.clearCallingIdentity();
2669 try {
2670 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002671 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002672 }
2673 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2674 // task and jumping straight into a call in the case of emergency call back.
2675 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2676 if (tm != null) {
2677 tm.showInCallScreen(false);
2678 }
2679 } finally {
2680 Binder.restoreCallingIdentity(ident);
2681 }
2682 }
2683
2684 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002685 public void updateLockTaskPackages(int userId, String[] packages) {
2686 final int callingUid = Binder.getCallingUid();
2687 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2688 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2689 "updateLockTaskPackages()");
2690 }
2691 synchronized (this) {
2692 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2693 + Arrays.toString(packages));
2694 getLockTaskController().updateLockTaskPackages(userId, packages);
2695 }
2696 }
2697
2698 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002699 public boolean isInLockTaskMode() {
2700 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2701 }
2702
2703 @Override
2704 public int getLockTaskModeState() {
2705 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002706 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002707 }
2708 }
2709
2710 @Override
2711 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2712 synchronized (mGlobalLock) {
2713 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2714 if (r != null) {
2715 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002716 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002717 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002718 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002719 }
2720 }
2721 }
2722
2723 @Override
2724 public Bundle getActivityOptions(IBinder token) {
2725 final long origId = Binder.clearCallingIdentity();
2726 try {
2727 synchronized (mGlobalLock) {
2728 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2729 if (r != null) {
2730 final ActivityOptions activityOptions = r.takeOptionsLocked();
2731 return activityOptions == null ? null : activityOptions.toBundle();
2732 }
2733 return null;
2734 }
2735 } finally {
2736 Binder.restoreCallingIdentity(origId);
2737 }
2738 }
2739
2740 @Override
2741 public List<IBinder> getAppTasks(String callingPackage) {
2742 int callingUid = Binder.getCallingUid();
2743 long ident = Binder.clearCallingIdentity();
2744 try {
2745 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002746 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 }
2748 } finally {
2749 Binder.restoreCallingIdentity(ident);
2750 }
2751 }
2752
2753 @Override
2754 public void finishVoiceTask(IVoiceInteractionSession session) {
2755 synchronized (mGlobalLock) {
2756 final long origId = Binder.clearCallingIdentity();
2757 try {
2758 // TODO: VI Consider treating local voice interactions and voice tasks
2759 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002760 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 } finally {
2762 Binder.restoreCallingIdentity(origId);
2763 }
2764 }
2765
2766 }
2767
2768 @Override
2769 public boolean isTopOfTask(IBinder token) {
2770 synchronized (mGlobalLock) {
2771 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002772 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 }
2774 }
2775
2776 @Override
2777 public void notifyLaunchTaskBehindComplete(IBinder token) {
2778 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2779 }
2780
2781 @Override
2782 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002783 mH.post(() -> {
2784 synchronized (mGlobalLock) {
2785 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002786 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002787 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002788 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002789 } catch (RemoteException e) {
2790 }
2791 }
2792 }
2793
2794 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796
2797 /** Called from an app when assist data is ready. */
2798 @Override
2799 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2800 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002801 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 synchronized (pae) {
2803 pae.result = extras;
2804 pae.structure = structure;
2805 pae.content = content;
2806 if (referrer != null) {
2807 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2808 }
2809 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002810 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002811 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2812 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 structure.setHomeActivity(pae.isHome);
2814 }
2815 pae.haveResult = true;
2816 pae.notifyAll();
2817 if (pae.intent == null && pae.receiver == null) {
2818 // Caller is just waiting for the result.
2819 return;
2820 }
2821 }
2822 // We are now ready to launch the assist activity.
2823 IAssistDataReceiver sendReceiver = null;
2824 Bundle sendBundle = null;
2825 synchronized (mGlobalLock) {
2826 buildAssistBundleLocked(pae, extras);
2827 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002828 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 if (!exists) {
2830 // Timed out.
2831 return;
2832 }
2833
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002834 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835 // Caller wants result sent back to them.
2836 sendBundle = new Bundle();
2837 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2838 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2839 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2840 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2841 }
2842 }
2843 if (sendReceiver != null) {
2844 try {
2845 sendReceiver.onHandleAssistData(sendBundle);
2846 } catch (RemoteException e) {
2847 }
2848 return;
2849 }
2850
2851 final long ident = Binder.clearCallingIdentity();
2852 try {
2853 if (TextUtils.equals(pae.intent.getAction(),
2854 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2855 pae.intent.putExtras(pae.extras);
2856 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2857 } else {
2858 pae.intent.replaceExtras(pae.extras);
2859 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2860 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2861 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002862 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863
2864 try {
2865 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2866 } catch (ActivityNotFoundException e) {
2867 Slog.w(TAG, "No activity to handle assist action.", e);
2868 }
2869 }
2870 } finally {
2871 Binder.restoreCallingIdentity(ident);
2872 }
2873 }
2874
2875 @Override
2876 public int addAppTask(IBinder activityToken, Intent intent,
2877 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2878 final int callingUid = Binder.getCallingUid();
2879 final long callingIdent = Binder.clearCallingIdentity();
2880
2881 try {
2882 synchronized (mGlobalLock) {
2883 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2884 if (r == null) {
2885 throw new IllegalArgumentException("Activity does not exist; token="
2886 + activityToken);
2887 }
2888 ComponentName comp = intent.getComponent();
2889 if (comp == null) {
2890 throw new IllegalArgumentException("Intent " + intent
2891 + " must specify explicit component");
2892 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002893 if (thumbnail.getWidth() != mThumbnailWidth
2894 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895 throw new IllegalArgumentException("Bad thumbnail size: got "
2896 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002897 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 }
2899 if (intent.getSelector() != null) {
2900 intent.setSelector(null);
2901 }
2902 if (intent.getSourceBounds() != null) {
2903 intent.setSourceBounds(null);
2904 }
2905 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2906 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2907 // The caller has added this as an auto-remove task... that makes no
2908 // sense, so turn off auto-remove.
2909 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2910 }
2911 }
2912 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2913 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2914 if (ainfo.applicationInfo.uid != callingUid) {
2915 throw new SecurityException(
2916 "Can't add task for another application: target uid="
2917 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2918 }
2919
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002920 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002922 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002924 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 // The app has too many tasks already and we can't add any more
2926 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2927 return INVALID_TASK_ID;
2928 }
2929 task.lastTaskDescription.copyFrom(description);
2930
2931 // TODO: Send the thumbnail to WM to store it.
2932
2933 return task.taskId;
2934 }
2935 } finally {
2936 Binder.restoreCallingIdentity(callingIdent);
2937 }
2938 }
2939
2940 @Override
2941 public Point getAppTaskThumbnailSize() {
2942 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002943 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 }
2945 }
2946
2947 @Override
2948 public void setTaskResizeable(int taskId, int resizeableMode) {
2949 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002950 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2952 if (task == null) {
2953 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2954 return;
2955 }
2956 task.setResizeMode(resizeableMode);
2957 }
2958 }
2959
2960 @Override
2961 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002962 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002963 long ident = Binder.clearCallingIdentity();
2964 try {
2965 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002966 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002967 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 if (task == null) {
2969 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2970 return;
2971 }
2972 // Place the task in the right stack if it isn't there already based on
2973 // the requested bounds.
2974 // The stack transition logic is:
2975 // - a null bounds on a freeform task moves that task to fullscreen
2976 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2977 // that task to freeform
2978 // - otherwise the task is not moved
2979 ActivityStack stack = task.getStack();
2980 if (!task.getWindowConfiguration().canResizeTask()) {
2981 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2982 }
2983 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2984 stack = stack.getDisplay().getOrCreateStack(
2985 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2986 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2987 stack = stack.getDisplay().getOrCreateStack(
2988 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2989 }
2990
2991 // Reparent the task to the right stack if necessary
2992 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2993 if (stack != task.getStack()) {
2994 // Defer resume until the task is resized below
2995 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2996 DEFER_RESUME, "resizeTask");
2997 preserveWindow = false;
2998 }
2999
3000 // After reparenting (which only resizes the task to the stack bounds), resize the
3001 // task to the actual bounds provided
3002 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3003 }
3004 } finally {
3005 Binder.restoreCallingIdentity(ident);
3006 }
3007 }
3008
3009 @Override
3010 public boolean releaseActivityInstance(IBinder token) {
3011 synchronized (mGlobalLock) {
3012 final long origId = Binder.clearCallingIdentity();
3013 try {
3014 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3015 if (r == null) {
3016 return false;
3017 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003018 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003019 } finally {
3020 Binder.restoreCallingIdentity(origId);
3021 }
3022 }
3023 }
3024
3025 @Override
3026 public void releaseSomeActivities(IApplicationThread appInt) {
3027 synchronized (mGlobalLock) {
3028 final long origId = Binder.clearCallingIdentity();
3029 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003030 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003031 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 } finally {
3033 Binder.restoreCallingIdentity(origId);
3034 }
3035 }
3036 }
3037
3038 @Override
3039 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003040 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003041 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 != PackageManager.PERMISSION_GRANTED) {
3043 throw new SecurityException("Requires permission "
3044 + android.Manifest.permission.DEVICE_POWER);
3045 }
3046
3047 synchronized (mGlobalLock) {
3048 long ident = Binder.clearCallingIdentity();
3049 if (mKeyguardShown != keyguardShowing) {
3050 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003051 final Message msg = PooledLambda.obtainMessage(
3052 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3053 keyguardShowing);
3054 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 }
3056 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003057 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003058 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 } finally {
3060 Binder.restoreCallingIdentity(ident);
3061 }
3062 }
3063
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003064 mH.post(() -> {
3065 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3066 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3067 }
3068 });
3069 }
3070
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003071 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003072 mH.post(() -> {
3073 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3074 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3075 }
3076 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077 }
3078
3079 @Override
3080 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003081 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3082 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083
3084 final File passedIconFile = new File(filePath);
3085 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3086 passedIconFile.getName());
3087 if (!legitIconFile.getPath().equals(filePath)
3088 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3089 throw new IllegalArgumentException("Bad file path: " + filePath
3090 + " passed for userId " + userId);
3091 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003092 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093 }
3094
3095 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003096 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3098 final ActivityOptions activityOptions = safeOptions != null
3099 ? safeOptions.getOptions(mStackSupervisor)
3100 : null;
3101 if (activityOptions == null
3102 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3103 || activityOptions.getCustomInPlaceResId() == 0) {
3104 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3105 "with valid animation");
3106 }
lumark588a3e82018-07-20 18:53:54 +08003107 // Get top display of front most application.
3108 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3109 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003110 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3111 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3112 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003113 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003114 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003115 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 }
3117
3118 @Override
3119 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003120 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 synchronized (mGlobalLock) {
3122 final long ident = Binder.clearCallingIdentity();
3123 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003124 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 if (stack == null) {
3126 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3127 return;
3128 }
3129 if (!stack.isActivityTypeStandardOrUndefined()) {
3130 throw new IllegalArgumentException(
3131 "Removing non-standard stack is not allowed.");
3132 }
3133 mStackSupervisor.removeStack(stack);
3134 } finally {
3135 Binder.restoreCallingIdentity(ident);
3136 }
3137 }
3138 }
3139
3140 @Override
3141 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003142 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143
3144 synchronized (mGlobalLock) {
3145 final long ident = Binder.clearCallingIdentity();
3146 try {
3147 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3148 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003149 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 } finally {
3151 Binder.restoreCallingIdentity(ident);
3152 }
3153 }
3154 }
3155
3156 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 public void exitFreeformMode(IBinder token) {
3158 synchronized (mGlobalLock) {
3159 long ident = Binder.clearCallingIdentity();
3160 try {
3161 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3162 if (r == null) {
3163 throw new IllegalArgumentException(
3164 "exitFreeformMode: No activity record matching token=" + token);
3165 }
3166
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003167 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 if (stack == null || !stack.inFreeformWindowingMode()) {
3169 throw new IllegalStateException(
3170 "exitFreeformMode: You can only go fullscreen from freeform.");
3171 }
3172
3173 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3174 } finally {
3175 Binder.restoreCallingIdentity(ident);
3176 }
3177 }
3178 }
3179
3180 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3181 @Override
3182 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003183 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003184 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003185 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 }
3187
3188 /** Unregister a task stack listener so that it stops receiving callbacks. */
3189 @Override
3190 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003191 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003193 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 }
3195
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 @Override
3197 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3198 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3199 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3200 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3201 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3202 }
3203
3204 @Override
3205 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3206 IBinder activityToken, int flags) {
3207 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3208 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3209 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3210 }
3211
3212 @Override
3213 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3214 Bundle args) {
3215 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3216 true /* focused */, true /* newSessionId */, userHandle, args,
3217 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3218 }
3219
3220 @Override
3221 public Bundle getAssistContextExtras(int requestType) {
3222 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3223 null, null, true /* focused */, true /* newSessionId */,
3224 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3225 if (pae == null) {
3226 return null;
3227 }
3228 synchronized (pae) {
3229 while (!pae.haveResult) {
3230 try {
3231 pae.wait();
3232 } catch (InterruptedException e) {
3233 }
3234 }
3235 }
3236 synchronized (mGlobalLock) {
3237 buildAssistBundleLocked(pae, pae.result);
3238 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003239 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 }
3241 return pae.extras;
3242 }
3243
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003244 /**
3245 * Binder IPC calls go through the public entry point.
3246 * This can be called with or without the global lock held.
3247 */
3248 private static int checkCallingPermission(String permission) {
3249 return checkPermission(
3250 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3251 }
3252
3253 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003254 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003255 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3256 mAmInternal.enforceCallingPermission(permission, func);
3257 }
3258 }
3259
3260 @VisibleForTesting
3261 int checkGetTasksPermission(String permission, int pid, int uid) {
3262 return checkPermission(permission, pid, uid);
3263 }
3264
3265 static int checkPermission(String permission, int pid, int uid) {
3266 if (permission == null) {
3267 return PackageManager.PERMISSION_DENIED;
3268 }
3269 return checkComponentPermission(permission, pid, uid, -1, true);
3270 }
3271
Wale Ogunwale214f3482018-10-04 11:00:47 -07003272 public static int checkComponentPermission(String permission, int pid, int uid,
3273 int owningUid, boolean exported) {
3274 return ActivityManagerService.checkComponentPermission(
3275 permission, pid, uid, owningUid, exported);
3276 }
3277
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003278 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3279 if (getRecentTasks().isCallerRecents(callingUid)) {
3280 // Always allow the recents component to get tasks
3281 return true;
3282 }
3283
3284 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3285 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3286 if (!allowed) {
3287 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3288 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3289 // Temporary compatibility: some existing apps on the system image may
3290 // still be requesting the old permission and not switched to the new
3291 // one; if so, we'll still allow them full access. This means we need
3292 // to see if they are holding the old permission and are a system app.
3293 try {
3294 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3295 allowed = true;
3296 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3297 + " is using old GET_TASKS but privileged; allowing");
3298 }
3299 } catch (RemoteException e) {
3300 }
3301 }
3302 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3303 + " does not hold REAL_GET_TASKS; limiting output");
3304 }
3305 return allowed;
3306 }
3307
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3309 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3310 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3311 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003312 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313 "enqueueAssistContext()");
3314
3315 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003316 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 if (activity == null) {
3318 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3319 return null;
3320 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003321 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3323 return null;
3324 }
3325 if (focused) {
3326 if (activityToken != null) {
3327 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3328 if (activity != caller) {
3329 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3330 + " is not current top " + activity);
3331 return null;
3332 }
3333 }
3334 } else {
3335 activity = ActivityRecord.forTokenLocked(activityToken);
3336 if (activity == null) {
3337 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3338 + " couldn't be found");
3339 return null;
3340 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003341 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003342 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3343 return null;
3344 }
3345 }
3346
3347 PendingAssistExtras pae;
3348 Bundle extras = new Bundle();
3349 if (args != null) {
3350 extras.putAll(args);
3351 }
3352 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003353 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354
3355 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3356 userHandle);
3357 pae.isHome = activity.isActivityTypeHome();
3358
3359 // Increment the sessionId if necessary
3360 if (newSessionId) {
3361 mViSessionId++;
3362 }
3363 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003364 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3365 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003367 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 } catch (RemoteException e) {
3369 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3370 return null;
3371 }
3372 return pae;
3373 }
3374 }
3375
3376 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3377 if (result != null) {
3378 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3379 }
3380 if (pae.hint != null) {
3381 pae.extras.putBoolean(pae.hint, true);
3382 }
3383 }
3384
3385 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3386 IAssistDataReceiver receiver;
3387 synchronized (mGlobalLock) {
3388 mPendingAssistExtras.remove(pae);
3389 receiver = pae.receiver;
3390 }
3391 if (receiver != null) {
3392 // Caller wants result sent back to them.
3393 Bundle sendBundle = new Bundle();
3394 // At least return the receiver extras
3395 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3396 try {
3397 pae.receiver.onHandleAssistData(sendBundle);
3398 } catch (RemoteException e) {
3399 }
3400 }
3401 }
3402
3403 public class PendingAssistExtras extends Binder implements Runnable {
3404 public final ActivityRecord activity;
3405 public boolean isHome;
3406 public final Bundle extras;
3407 public final Intent intent;
3408 public final String hint;
3409 public final IAssistDataReceiver receiver;
3410 public final int userHandle;
3411 public boolean haveResult = false;
3412 public Bundle result = null;
3413 public AssistStructure structure = null;
3414 public AssistContent content = null;
3415 public Bundle receiverExtras;
3416
3417 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3418 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3419 int _userHandle) {
3420 activity = _activity;
3421 extras = _extras;
3422 intent = _intent;
3423 hint = _hint;
3424 receiver = _receiver;
3425 receiverExtras = _receiverExtras;
3426 userHandle = _userHandle;
3427 }
3428
3429 @Override
3430 public void run() {
3431 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3432 synchronized (this) {
3433 haveResult = true;
3434 notifyAll();
3435 }
3436 pendingAssistExtrasTimedOut(this);
3437 }
3438 }
3439
3440 @Override
3441 public boolean isAssistDataAllowedOnCurrentActivity() {
3442 int userId;
3443 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003444 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3446 return false;
3447 }
3448
3449 final ActivityRecord activity = focusedStack.getTopActivity();
3450 if (activity == null) {
3451 return false;
3452 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003453 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 }
3455 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3456 }
3457
3458 @Override
3459 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3460 long ident = Binder.clearCallingIdentity();
3461 try {
3462 synchronized (mGlobalLock) {
3463 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003464 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 if (top != caller) {
3466 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3467 + " is not current top " + top);
3468 return false;
3469 }
3470 if (!top.nowVisible) {
3471 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3472 + " is not visible");
3473 return false;
3474 }
3475 }
3476 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3477 token);
3478 } finally {
3479 Binder.restoreCallingIdentity(ident);
3480 }
3481 }
3482
3483 @Override
3484 public boolean isRootVoiceInteraction(IBinder token) {
3485 synchronized (mGlobalLock) {
3486 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3487 if (r == null) {
3488 return false;
3489 }
3490 return r.rootVoiceInteraction;
3491 }
3492 }
3493
Wale Ogunwalef6733932018-06-27 05:14:34 -07003494 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3495 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3496 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3497 if (activityToCallback == null) return;
3498 activityToCallback.setVoiceSessionLocked(voiceSession);
3499
3500 // Inform the activity
3501 try {
3502 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3503 voiceInteractor);
3504 long token = Binder.clearCallingIdentity();
3505 try {
3506 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3507 } finally {
3508 Binder.restoreCallingIdentity(token);
3509 }
3510 // TODO: VI Should we cache the activity so that it's easier to find later
3511 // rather than scan through all the stacks and activities?
3512 } catch (RemoteException re) {
3513 activityToCallback.clearVoiceSessionLocked();
3514 // TODO: VI Should this terminate the voice session?
3515 }
3516 }
3517
3518 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3519 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3520 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3521 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3522 boolean wasRunningVoice = mRunningVoice != null;
3523 mRunningVoice = session;
3524 if (!wasRunningVoice) {
3525 mVoiceWakeLock.acquire();
3526 updateSleepIfNeededLocked();
3527 }
3528 }
3529 }
3530
3531 void finishRunningVoiceLocked() {
3532 if (mRunningVoice != null) {
3533 mRunningVoice = null;
3534 mVoiceWakeLock.release();
3535 updateSleepIfNeededLocked();
3536 }
3537 }
3538
3539 @Override
3540 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3541 synchronized (mGlobalLock) {
3542 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3543 if (keepAwake) {
3544 mVoiceWakeLock.acquire();
3545 } else {
3546 mVoiceWakeLock.release();
3547 }
3548 }
3549 }
3550 }
3551
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 @Override
3553 public ComponentName getActivityClassForToken(IBinder token) {
3554 synchronized (mGlobalLock) {
3555 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3556 if (r == null) {
3557 return null;
3558 }
3559 return r.intent.getComponent();
3560 }
3561 }
3562
3563 @Override
3564 public String getPackageForToken(IBinder token) {
3565 synchronized (mGlobalLock) {
3566 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3567 if (r == null) {
3568 return null;
3569 }
3570 return r.packageName;
3571 }
3572 }
3573
3574 @Override
3575 public void showLockTaskEscapeMessage(IBinder token) {
3576 synchronized (mGlobalLock) {
3577 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3578 if (r == null) {
3579 return;
3580 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003581 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003582 }
3583 }
3584
3585 @Override
3586 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003587 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003588 final long token = Binder.clearCallingIdentity();
3589 try {
3590 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003591 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003592 }
3593 } finally {
3594 Binder.restoreCallingIdentity(token);
3595 }
3596 }
3597
3598 /**
3599 * Try to place task to provided position. The final position might be different depending on
3600 * current user and stacks state. The task will be moved to target stack if it's currently in
3601 * different stack.
3602 */
3603 @Override
3604 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003605 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 synchronized (mGlobalLock) {
3607 long ident = Binder.clearCallingIdentity();
3608 try {
3609 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3610 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003611 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 if (task == null) {
3613 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3614 + taskId);
3615 }
3616
Wale Ogunwaled32da472018-11-16 07:19:28 -08003617 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003618
3619 if (stack == null) {
3620 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3621 + stackId);
3622 }
3623 if (!stack.isActivityTypeStandardOrUndefined()) {
3624 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3625 + " the position of task " + taskId + " in/to non-standard stack");
3626 }
3627
3628 // TODO: Have the callers of this API call a separate reparent method if that is
3629 // what they intended to do vs. having this method also do reparenting.
3630 if (task.getStack() == stack) {
3631 // Change position in current stack.
3632 stack.positionChildAt(task, position);
3633 } else {
3634 // Reparent to new stack.
3635 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3636 !DEFER_RESUME, "positionTaskInStack");
3637 }
3638 } finally {
3639 Binder.restoreCallingIdentity(ident);
3640 }
3641 }
3642 }
3643
3644 @Override
3645 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3646 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3647 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3648 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3649 synchronized (mGlobalLock) {
3650 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3651 if (record == null) {
3652 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3653 + "found for: " + token);
3654 }
3655 record.setSizeConfigurations(horizontalSizeConfiguration,
3656 verticalSizeConfigurations, smallestSizeConfigurations);
3657 }
3658 }
3659
3660 /**
3661 * Dismisses split-screen multi-window mode.
3662 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3663 */
3664 @Override
3665 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003666 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003667 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3668 final long ident = Binder.clearCallingIdentity();
3669 try {
3670 synchronized (mGlobalLock) {
3671 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003672 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003673 if (stack == null) {
3674 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3675 return;
3676 }
3677
3678 if (toTop) {
3679 // Caller wants the current split-screen primary stack to be the top stack after
3680 // it goes fullscreen, so move it to the front.
3681 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003682 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683 // In this case the current split-screen primary stack shouldn't be the top
3684 // stack after it goes fullscreen, but it current has focus, so we move the
3685 // focus to the top-most split-screen secondary stack next to it.
3686 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3687 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3688 if (otherStack != null) {
3689 otherStack.moveToFront("dismissSplitScreenMode_other");
3690 }
3691 }
3692
Evan Rosky10475742018-09-05 19:02:48 -07003693 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 }
3695 } finally {
3696 Binder.restoreCallingIdentity(ident);
3697 }
3698 }
3699
3700 /**
3701 * Dismisses Pip
3702 * @param animate True if the dismissal should be animated.
3703 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3704 * default animation duration should be used.
3705 */
3706 @Override
3707 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003708 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003709 final long ident = Binder.clearCallingIdentity();
3710 try {
3711 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003712 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003713 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003714 if (stack == null) {
3715 Slog.w(TAG, "dismissPip: pinned stack not found.");
3716 return;
3717 }
3718 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3719 throw new IllegalArgumentException("Stack: " + stack
3720 + " doesn't support animated resize.");
3721 }
3722 if (animate) {
3723 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3724 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3725 } else {
3726 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3727 }
3728 }
3729 } finally {
3730 Binder.restoreCallingIdentity(ident);
3731 }
3732 }
3733
3734 @Override
3735 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003736 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003737 synchronized (mGlobalLock) {
3738 mSuppressResizeConfigChanges = suppress;
3739 }
3740 }
3741
3742 /**
3743 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3744 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3745 * activity and clearing the task at the same time.
3746 */
3747 @Override
3748 // TODO: API should just be about changing windowing modes...
3749 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003750 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 "moveTasksToFullscreenStack()");
3752 synchronized (mGlobalLock) {
3753 final long origId = Binder.clearCallingIdentity();
3754 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003755 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003756 if (stack != null){
3757 if (!stack.isActivityTypeStandardOrUndefined()) {
3758 throw new IllegalArgumentException(
3759 "You can't move tasks from non-standard stacks.");
3760 }
3761 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3762 }
3763 } finally {
3764 Binder.restoreCallingIdentity(origId);
3765 }
3766 }
3767 }
3768
3769 /**
3770 * Moves the top activity in the input stackId to the pinned stack.
3771 *
3772 * @param stackId Id of stack to move the top activity to pinned stack.
3773 * @param bounds Bounds to use for pinned stack.
3774 *
3775 * @return True if the top activity of the input stack was successfully moved to the pinned
3776 * stack.
3777 */
3778 @Override
3779 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003780 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003781 "moveTopActivityToPinnedStack()");
3782 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003783 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003784 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3785 + "Device doesn't support picture-in-picture mode");
3786 }
3787
3788 long ident = Binder.clearCallingIdentity();
3789 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003790 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 } finally {
3792 Binder.restoreCallingIdentity(ident);
3793 }
3794 }
3795 }
3796
3797 @Override
3798 public boolean isInMultiWindowMode(IBinder token) {
3799 final long origId = Binder.clearCallingIdentity();
3800 try {
3801 synchronized (mGlobalLock) {
3802 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3803 if (r == null) {
3804 return false;
3805 }
3806 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3807 return r.inMultiWindowMode();
3808 }
3809 } finally {
3810 Binder.restoreCallingIdentity(origId);
3811 }
3812 }
3813
3814 @Override
3815 public boolean isInPictureInPictureMode(IBinder token) {
3816 final long origId = Binder.clearCallingIdentity();
3817 try {
3818 synchronized (mGlobalLock) {
3819 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3820 }
3821 } finally {
3822 Binder.restoreCallingIdentity(origId);
3823 }
3824 }
3825
3826 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003827 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3828 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 return false;
3830 }
3831
3832 // If we are animating to fullscreen then we have already dispatched the PIP mode
3833 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003834 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3835 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 }
3837
3838 @Override
3839 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3840 final long origId = Binder.clearCallingIdentity();
3841 try {
3842 synchronized (mGlobalLock) {
3843 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3844 "enterPictureInPictureMode", token, params);
3845
3846 // If the activity is already in picture in picture mode, then just return early
3847 if (isInPictureInPictureMode(r)) {
3848 return true;
3849 }
3850
3851 // Activity supports picture-in-picture, now check that we can enter PiP at this
3852 // point, if it is
3853 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3854 false /* beforeStopping */)) {
3855 return false;
3856 }
3857
3858 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003859 synchronized (mGlobalLock) {
3860 // Only update the saved args from the args that are set
3861 r.pictureInPictureArgs.copyOnlySet(params);
3862 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3863 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3864 // Adjust the source bounds by the insets for the transition down
3865 final Rect sourceBounds = new Rect(
3866 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003867 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003868 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003869 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003870 stack.setPictureInPictureAspectRatio(aspectRatio);
3871 stack.setPictureInPictureActions(actions);
3872 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3873 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3874 logPictureInPictureArgs(params);
3875 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876 };
3877
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003878 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003879 // If the keyguard is showing or occluded, then try and dismiss it before
3880 // entering picture-in-picture (this will prompt the user to authenticate if the
3881 // device is currently locked).
3882 dismissKeyguard(token, new KeyguardDismissCallback() {
3883 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003884 public void onDismissSucceeded() {
3885 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003886 }
3887 }, null /* message */);
3888 } else {
3889 // Enter picture in picture immediately otherwise
3890 enterPipRunnable.run();
3891 }
3892 return true;
3893 }
3894 } finally {
3895 Binder.restoreCallingIdentity(origId);
3896 }
3897 }
3898
3899 @Override
3900 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3901 final long origId = Binder.clearCallingIdentity();
3902 try {
3903 synchronized (mGlobalLock) {
3904 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3905 "setPictureInPictureParams", token, params);
3906
3907 // Only update the saved args from the args that are set
3908 r.pictureInPictureArgs.copyOnlySet(params);
3909 if (r.inPinnedWindowingMode()) {
3910 // If the activity is already in picture-in-picture, update the pinned stack now
3911 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3912 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003913 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003914 if (!stack.isAnimatingBoundsToFullscreen()) {
3915 stack.setPictureInPictureAspectRatio(
3916 r.pictureInPictureArgs.getAspectRatio());
3917 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3918 }
3919 }
3920 logPictureInPictureArgs(params);
3921 }
3922 } finally {
3923 Binder.restoreCallingIdentity(origId);
3924 }
3925 }
3926
3927 @Override
3928 public int getMaxNumPictureInPictureActions(IBinder token) {
3929 // Currently, this is a static constant, but later, we may change this to be dependent on
3930 // the context of the activity
3931 return 3;
3932 }
3933
3934 private void logPictureInPictureArgs(PictureInPictureParams params) {
3935 if (params.hasSetActions()) {
3936 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3937 params.getActions().size());
3938 }
3939 if (params.hasSetAspectRatio()) {
3940 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3941 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3942 MetricsLogger.action(lm);
3943 }
3944 }
3945
3946 /**
3947 * Checks the state of the system and the activity associated with the given {@param token} to
3948 * verify that picture-in-picture is supported for that activity.
3949 *
3950 * @return the activity record for the given {@param token} if all the checks pass.
3951 */
3952 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3953 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003954 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 throw new IllegalStateException(caller
3956 + ": Device doesn't support picture-in-picture mode.");
3957 }
3958
3959 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3960 if (r == null) {
3961 throw new IllegalStateException(caller
3962 + ": Can't find activity for token=" + token);
3963 }
3964
3965 if (!r.supportsPictureInPicture()) {
3966 throw new IllegalStateException(caller
3967 + ": Current activity does not support picture-in-picture.");
3968 }
3969
3970 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003971 && !mWindowManager.isValidPictureInPictureAspectRatio(
3972 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 final float minAspectRatio = mContext.getResources().getFloat(
3974 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3975 final float maxAspectRatio = mContext.getResources().getFloat(
3976 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3977 throw new IllegalArgumentException(String.format(caller
3978 + ": Aspect ratio is too extreme (must be between %f and %f).",
3979 minAspectRatio, maxAspectRatio));
3980 }
3981
3982 // Truncate the number of actions if necessary
3983 params.truncateActions(getMaxNumPictureInPictureActions(token));
3984
3985 return r;
3986 }
3987
3988 @Override
3989 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003990 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 synchronized (mGlobalLock) {
3992 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3993 if (r == null) {
3994 throw new IllegalArgumentException("Activity does not exist; token="
3995 + activityToken);
3996 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003997 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 }
3999 }
4000
4001 @Override
4002 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4003 Rect tempDockedTaskInsetBounds,
4004 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004005 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 long ident = Binder.clearCallingIdentity();
4007 try {
4008 synchronized (mGlobalLock) {
4009 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4010 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4011 PRESERVE_WINDOWS);
4012 }
4013 } finally {
4014 Binder.restoreCallingIdentity(ident);
4015 }
4016 }
4017
4018 @Override
4019 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004020 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 final long ident = Binder.clearCallingIdentity();
4022 try {
4023 synchronized (mGlobalLock) {
4024 mStackSupervisor.setSplitScreenResizing(resizing);
4025 }
4026 } finally {
4027 Binder.restoreCallingIdentity(ident);
4028 }
4029 }
4030
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004031 /**
4032 * Check that we have the features required for VR-related API calls, and throw an exception if
4033 * not.
4034 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004035 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004036 if (!mContext.getPackageManager().hasSystemFeature(
4037 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4038 throw new UnsupportedOperationException("VR mode not supported on this device!");
4039 }
4040 }
4041
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 @Override
4043 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004044 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045
4046 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4047
4048 ActivityRecord r;
4049 synchronized (mGlobalLock) {
4050 r = ActivityRecord.isInStackLocked(token);
4051 }
4052
4053 if (r == null) {
4054 throw new IllegalArgumentException();
4055 }
4056
4057 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004058 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 VrManagerInternal.NO_ERROR) {
4060 return err;
4061 }
4062
4063 // Clear the binder calling uid since this path may call moveToTask().
4064 final long callingId = Binder.clearCallingIdentity();
4065 try {
4066 synchronized (mGlobalLock) {
4067 r.requestedVrComponent = (enabled) ? packageName : null;
4068
4069 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004070 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004071 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004072 }
4073 return 0;
4074 }
4075 } finally {
4076 Binder.restoreCallingIdentity(callingId);
4077 }
4078 }
4079
4080 @Override
4081 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4082 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4083 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004084 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4086 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4087 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004088 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004089 || activity.voiceSession != null) {
4090 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4091 return;
4092 }
4093 if (activity.pendingVoiceInteractionStart) {
4094 Slog.w(TAG, "Pending start of voice interaction already.");
4095 return;
4096 }
4097 activity.pendingVoiceInteractionStart = true;
4098 }
4099 LocalServices.getService(VoiceInteractionManagerInternal.class)
4100 .startLocalVoiceInteraction(callingActivity, options);
4101 }
4102
4103 @Override
4104 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4105 LocalServices.getService(VoiceInteractionManagerInternal.class)
4106 .stopLocalVoiceInteraction(callingActivity);
4107 }
4108
4109 @Override
4110 public boolean supportsLocalVoiceInteraction() {
4111 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4112 .supportsLocalVoiceInteraction();
4113 }
4114
4115 /** Notifies all listeners when the pinned stack animation starts. */
4116 @Override
4117 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004118 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 }
4120
4121 /** Notifies all listeners when the pinned stack animation ends. */
4122 @Override
4123 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004124 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 }
4126
4127 @Override
4128 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004129 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 final long ident = Binder.clearCallingIdentity();
4131 try {
4132 synchronized (mGlobalLock) {
4133 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4134 }
4135 } finally {
4136 Binder.restoreCallingIdentity(ident);
4137 }
4138 }
4139
4140 @Override
4141 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004142 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143
4144 synchronized (mGlobalLock) {
4145 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004146 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 // Call might come when display is not yet added or has already been removed.
4148 if (DEBUG_CONFIGURATION) {
4149 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4150 + displayId);
4151 }
4152 return false;
4153 }
4154
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004155 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004157 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 }
4159
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004160 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004161 final Message msg = PooledLambda.obtainMessage(
4162 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4163 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 }
4165
4166 final long origId = Binder.clearCallingIdentity();
4167 try {
4168 if (values != null) {
4169 Settings.System.clearConfiguration(values);
4170 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004171 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4173 return mTmpUpdateConfigurationResult.changes != 0;
4174 } finally {
4175 Binder.restoreCallingIdentity(origId);
4176 }
4177 }
4178 }
4179
4180 @Override
4181 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004182 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004183
4184 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004185 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004186 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004187 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188 }
4189
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004190 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004191 final Message msg = PooledLambda.obtainMessage(
4192 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4193 DEFAULT_DISPLAY);
4194 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004195 }
4196
4197 final long origId = Binder.clearCallingIdentity();
4198 try {
4199 if (values != null) {
4200 Settings.System.clearConfiguration(values);
4201 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004202 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004203 UserHandle.USER_NULL, false /* deferResume */,
4204 mTmpUpdateConfigurationResult);
4205 return mTmpUpdateConfigurationResult.changes != 0;
4206 } finally {
4207 Binder.restoreCallingIdentity(origId);
4208 }
4209 }
4210 }
4211
4212 @Override
4213 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4214 CharSequence message) {
4215 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004216 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004217 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4218 }
4219 final long callingId = Binder.clearCallingIdentity();
4220 try {
4221 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004222 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004223 }
4224 } finally {
4225 Binder.restoreCallingIdentity(callingId);
4226 }
4227 }
4228
4229 @Override
4230 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004231 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004232 "cancelTaskWindowTransition()");
4233 final long ident = Binder.clearCallingIdentity();
4234 try {
4235 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004236 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 MATCH_TASK_IN_STACKS_ONLY);
4238 if (task == null) {
4239 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4240 return;
4241 }
4242 task.cancelWindowTransition();
4243 }
4244 } finally {
4245 Binder.restoreCallingIdentity(ident);
4246 }
4247 }
4248
4249 @Override
4250 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004251 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 final long ident = Binder.clearCallingIdentity();
4253 try {
4254 final TaskRecord task;
4255 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004256 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4258 if (task == null) {
4259 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4260 return null;
4261 }
4262 }
4263 // Don't call this while holding the lock as this operation might hit the disk.
4264 return task.getSnapshot(reducedResolution);
4265 } finally {
4266 Binder.restoreCallingIdentity(ident);
4267 }
4268 }
4269
4270 @Override
4271 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4272 synchronized (mGlobalLock) {
4273 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4274 if (r == null) {
4275 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4276 + token);
4277 return;
4278 }
4279 final long origId = Binder.clearCallingIdentity();
4280 try {
4281 r.setDisablePreviewScreenshots(disable);
4282 } finally {
4283 Binder.restoreCallingIdentity(origId);
4284 }
4285 }
4286 }
4287
4288 /** Return the user id of the last resumed activity. */
4289 @Override
4290 public @UserIdInt
4291 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004292 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4294 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004295 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004296 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004297 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004298 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 }
4300 }
4301
4302 @Override
4303 public void updateLockTaskFeatures(int userId, int flags) {
4304 final int callingUid = Binder.getCallingUid();
4305 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 "updateLockTaskFeatures()");
4308 }
4309 synchronized (mGlobalLock) {
4310 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4311 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004312 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313 }
4314 }
4315
4316 @Override
4317 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4318 synchronized (mGlobalLock) {
4319 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4320 if (r == null) {
4321 return;
4322 }
4323 final long origId = Binder.clearCallingIdentity();
4324 try {
4325 r.setShowWhenLocked(showWhenLocked);
4326 } finally {
4327 Binder.restoreCallingIdentity(origId);
4328 }
4329 }
4330 }
4331
4332 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004333 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4334 synchronized (mGlobalLock) {
4335 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4336 if (r == null) {
4337 return;
4338 }
4339 final long origId = Binder.clearCallingIdentity();
4340 try {
4341 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4342 } finally {
4343 Binder.restoreCallingIdentity(origId);
4344 }
4345 }
4346 }
4347
4348 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4350 synchronized (mGlobalLock) {
4351 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4352 if (r == null) {
4353 return;
4354 }
4355 final long origId = Binder.clearCallingIdentity();
4356 try {
4357 r.setTurnScreenOn(turnScreenOn);
4358 } finally {
4359 Binder.restoreCallingIdentity(origId);
4360 }
4361 }
4362 }
4363
4364 @Override
4365 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 "registerRemoteAnimations");
4368 definition.setCallingPid(Binder.getCallingPid());
4369 synchronized (mGlobalLock) {
4370 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4371 if (r == null) {
4372 return;
4373 }
4374 final long origId = Binder.clearCallingIdentity();
4375 try {
4376 r.registerRemoteAnimations(definition);
4377 } finally {
4378 Binder.restoreCallingIdentity(origId);
4379 }
4380 }
4381 }
4382
4383 @Override
4384 public void registerRemoteAnimationForNextActivityStart(String packageName,
4385 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 "registerRemoteAnimationForNextActivityStart");
4388 adapter.setCallingPid(Binder.getCallingPid());
4389 synchronized (mGlobalLock) {
4390 final long origId = Binder.clearCallingIdentity();
4391 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004392 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 packageName, adapter);
4394 } finally {
4395 Binder.restoreCallingIdentity(origId);
4396 }
4397 }
4398 }
4399
4400 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4401 @Override
4402 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4403 synchronized (mGlobalLock) {
4404 final long origId = Binder.clearCallingIdentity();
4405 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004406 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 } finally {
4408 Binder.restoreCallingIdentity(origId);
4409 }
4410 }
4411 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004412
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004413 @Override
4414 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004415 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004416 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004417 final int pid = Binder.getCallingPid();
4418 final WindowProcessController wpc = mPidMap.get(pid);
4419 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004420 }
4421 }
4422
4423 @Override
4424 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004425 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004426 != PERMISSION_GRANTED) {
4427 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4428 + Binder.getCallingPid()
4429 + ", uid=" + Binder.getCallingUid()
4430 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4431 Slog.w(TAG, msg);
4432 throw new SecurityException(msg);
4433 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004435 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004436 final int pid = Binder.getCallingPid();
4437 final WindowProcessController proc = mPidMap.get(pid);
4438 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004439 }
4440 }
4441
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 @Override
4443 public void stopAppSwitches() {
4444 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4445 synchronized (mGlobalLock) {
4446 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4447 mDidAppSwitch = false;
4448 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4449 }
4450 }
4451
4452 @Override
4453 public void resumeAppSwitches() {
4454 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4455 synchronized (mGlobalLock) {
4456 // Note that we don't execute any pending app switches... we will
4457 // let those wait until either the timeout, or the next start
4458 // activity request.
4459 mAppSwitchesAllowedTime = 0;
4460 }
4461 }
4462
4463 void onStartActivitySetDidAppSwitch() {
4464 if (mDidAppSwitch) {
4465 // This is the second allowed switch since we stopped switches, so now just generally
4466 // allow switches. Use case:
4467 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4468 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4469 // anyone to switch again).
4470 mAppSwitchesAllowedTime = 0;
4471 } else {
4472 mDidAppSwitch = true;
4473 }
4474 }
4475
4476 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004477 boolean shouldDisableNonVrUiLocked() {
4478 return mVrController.shouldDisableNonVrUiLocked();
4479 }
4480
Wale Ogunwale53783742018-09-16 10:21:51 -07004481 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004482 // VR apps are expected to run in a main display. If an app is turning on VR for
4483 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4484 // fullscreen stack before enabling VR Mode.
4485 // TODO: The goal of this code is to keep the VR app on the main display. When the
4486 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4487 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4488 // option would be a better choice here.
4489 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4490 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4491 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004492 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004493 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004494 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004495 }
4496 mH.post(() -> {
4497 if (!mVrController.onVrModeChanged(r)) {
4498 return;
4499 }
4500 synchronized (mGlobalLock) {
4501 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4502 mWindowManager.disableNonVrUi(disableNonVrUi);
4503 if (disableNonVrUi) {
4504 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4505 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004506 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004507 }
4508 }
4509 });
4510 }
4511
Wale Ogunwale53783742018-09-16 10:21:51 -07004512 @Override
4513 public int getPackageScreenCompatMode(String packageName) {
4514 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4515 synchronized (mGlobalLock) {
4516 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4517 }
4518 }
4519
4520 @Override
4521 public void setPackageScreenCompatMode(String packageName, int mode) {
4522 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4523 "setPackageScreenCompatMode");
4524 synchronized (mGlobalLock) {
4525 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4526 }
4527 }
4528
4529 @Override
4530 public boolean getPackageAskScreenCompat(String packageName) {
4531 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4532 synchronized (mGlobalLock) {
4533 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4534 }
4535 }
4536
4537 @Override
4538 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4539 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4540 "setPackageAskScreenCompat");
4541 synchronized (mGlobalLock) {
4542 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4543 }
4544 }
4545
Wale Ogunwale64258362018-10-16 15:13:37 -07004546 public static String relaunchReasonToString(int relaunchReason) {
4547 switch (relaunchReason) {
4548 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4549 return "window_resize";
4550 case RELAUNCH_REASON_FREE_RESIZE:
4551 return "free_resize";
4552 default:
4553 return null;
4554 }
4555 }
4556
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004557 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004558 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004559 }
4560
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004561 /** Pokes the task persister. */
4562 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4563 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4564 }
4565
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004566 boolean isKeyguardLocked() {
4567 return mKeyguardController.isKeyguardLocked();
4568 }
4569
Garfield Tan01548632018-11-27 10:15:48 -08004570 /**
4571 * Clears launch params for the given package.
4572 * @param packageNames the names of the packages of which the launch params are to be cleared
4573 */
4574 @Override
4575 public void clearLaunchParamsForPackages(List<String> packageNames) {
4576 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4577 "clearLaunchParamsForPackages");
4578 synchronized (mGlobalLock) {
4579 for (int i = 0; i < packageNames.size(); ++i) {
4580 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4581 }
4582 }
4583 }
4584
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004585 /**
4586 * Makes the display with the given id a single task instance display. I.e the display can only
4587 * contain one task.
4588 */
4589 @Override
4590 public void setDisplayToSingleTaskInstance(int displayId) {
4591 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4592 "setDisplayToSingleTaskInstance");
4593 final long origId = Binder.clearCallingIdentity();
4594 try {
4595 final ActivityDisplay display =
4596 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4597 if (display != null) {
4598 display.setDisplayToSingleTaskInstance();
4599 }
4600 } finally {
4601 Binder.restoreCallingIdentity(origId);
4602 }
4603 }
4604
Wale Ogunwale31913b52018-10-13 08:29:31 -07004605 void dumpLastANRLocked(PrintWriter pw) {
4606 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4607 if (mLastANRState == null) {
4608 pw.println(" <no ANR has occurred since boot>");
4609 } else {
4610 pw.println(mLastANRState);
4611 }
4612 }
4613
4614 void dumpLastANRTracesLocked(PrintWriter pw) {
4615 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4616
4617 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4618 if (ArrayUtils.isEmpty(files)) {
4619 pw.println(" <no ANR has occurred since boot>");
4620 return;
4621 }
4622 // Find the latest file.
4623 File latest = null;
4624 for (File f : files) {
4625 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4626 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004627 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004628 }
4629 pw.print("File: ");
4630 pw.print(latest.getName());
4631 pw.println();
4632 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4633 String line;
4634 while ((line = in.readLine()) != null) {
4635 pw.println(line);
4636 }
4637 } catch (IOException e) {
4638 pw.print("Unable to read: ");
4639 pw.print(e);
4640 pw.println();
4641 }
4642 }
4643
4644 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4645 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4646 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4647 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4648 }
4649
4650 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4651 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4652 pw.println(header);
4653
Wale Ogunwaled32da472018-11-16 07:19:28 -08004654 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004655 dumpPackage);
4656 boolean needSep = printedAnything;
4657
4658 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004659 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004660 " ResumedActivity: ");
4661 if (printed) {
4662 printedAnything = true;
4663 needSep = false;
4664 }
4665
4666 if (dumpPackage == null) {
4667 if (needSep) {
4668 pw.println();
4669 }
4670 printedAnything = true;
4671 mStackSupervisor.dump(pw, " ");
4672 }
4673
4674 if (!printedAnything) {
4675 pw.println(" (nothing)");
4676 }
4677 }
4678
4679 void dumpActivityContainersLocked(PrintWriter pw) {
4680 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004681 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004682 pw.println(" ");
4683 }
4684
4685 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4686 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4687 getActivityStartController().dump(pw, "", dumpPackage);
4688 }
4689
4690 /**
4691 * There are three things that cmd can be:
4692 * - a flattened component name that matches an existing activity
4693 * - the cmd arg isn't the flattened component name of an existing activity:
4694 * dump all activity whose component contains the cmd as a substring
4695 * - A hex number of the ActivityRecord object instance.
4696 *
4697 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4698 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4699 */
4700 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4701 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4702 ArrayList<ActivityRecord> activities;
4703
4704 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004705 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004706 dumpFocusedStackOnly);
4707 }
4708
4709 if (activities.size() <= 0) {
4710 return false;
4711 }
4712
4713 String[] newArgs = new String[args.length - opti];
4714 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4715
4716 TaskRecord lastTask = null;
4717 boolean needSep = false;
4718 for (int i = activities.size() - 1; i >= 0; i--) {
4719 ActivityRecord r = activities.get(i);
4720 if (needSep) {
4721 pw.println();
4722 }
4723 needSep = true;
4724 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004725 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004726 if (lastTask != task) {
4727 lastTask = task;
4728 pw.print("TASK "); pw.print(lastTask.affinity);
4729 pw.print(" id="); pw.print(lastTask.taskId);
4730 pw.print(" userId="); pw.println(lastTask.userId);
4731 if (dumpAll) {
4732 lastTask.dump(pw, " ");
4733 }
4734 }
4735 }
4736 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4737 }
4738 return true;
4739 }
4740
4741 /**
4742 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4743 * there is a thread associated with the activity.
4744 */
4745 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4746 final ActivityRecord r, String[] args, boolean dumpAll) {
4747 String innerPrefix = prefix + " ";
4748 synchronized (mGlobalLock) {
4749 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4750 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4751 pw.print(" pid=");
4752 if (r.hasProcess()) pw.println(r.app.getPid());
4753 else pw.println("(not running)");
4754 if (dumpAll) {
4755 r.dump(pw, innerPrefix);
4756 }
4757 }
4758 if (r.attachedToProcess()) {
4759 // flush anything that is already in the PrintWriter since the thread is going
4760 // to write to the file descriptor directly
4761 pw.flush();
4762 try {
4763 TransferPipe tp = new TransferPipe();
4764 try {
4765 r.app.getThread().dumpActivity(tp.getWriteFd(),
4766 r.appToken, innerPrefix, args);
4767 tp.go(fd);
4768 } finally {
4769 tp.kill();
4770 }
4771 } catch (IOException e) {
4772 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4773 } catch (RemoteException e) {
4774 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4775 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004776 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004777 }
4778
sanryhuang498e77e2018-12-06 14:57:01 +08004779 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4780 boolean testPssMode) {
4781 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4782 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4783 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004784 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004785 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4786 st.toString());
4787 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004788 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4789 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4790 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004791 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4792 testPssMode);
4793 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 }
4795
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004796 int getCurrentUserId() {
4797 return mAmInternal.getCurrentUserId();
4798 }
4799
4800 private void enforceNotIsolatedCaller(String caller) {
4801 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4802 throw new SecurityException("Isolated process not allowed to call " + caller);
4803 }
4804 }
4805
Wale Ogunwalef6733932018-06-27 05:14:34 -07004806 public Configuration getConfiguration() {
4807 Configuration ci;
4808 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004809 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004810 ci.userSetLocale = false;
4811 }
4812 return ci;
4813 }
4814
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004815 /**
4816 * Current global configuration information. Contains general settings for the entire system,
4817 * also corresponds to the merged configuration of the default display.
4818 */
4819 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004820 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004821 }
4822
4823 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4824 boolean initLocale) {
4825 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4826 }
4827
4828 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4829 boolean initLocale, boolean deferResume) {
4830 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4831 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4832 UserHandle.USER_NULL, deferResume);
4833 }
4834
Wale Ogunwale59507092018-10-29 09:00:30 -07004835 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004836 final long origId = Binder.clearCallingIdentity();
4837 try {
4838 synchronized (mGlobalLock) {
4839 updateConfigurationLocked(values, null, false, true, userId,
4840 false /* deferResume */);
4841 }
4842 } finally {
4843 Binder.restoreCallingIdentity(origId);
4844 }
4845 }
4846
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004847 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4848 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4849 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4850 deferResume, null /* result */);
4851 }
4852
4853 /**
4854 * Do either or both things: (1) change the current configuration, and (2)
4855 * make sure the given activity is running with the (now) current
4856 * configuration. Returns true if the activity has been left running, or
4857 * false if <var>starting</var> is being destroyed to match the new
4858 * configuration.
4859 *
4860 * @param userId is only used when persistent parameter is set to true to persist configuration
4861 * for that particular user
4862 */
4863 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4864 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4865 ActivityTaskManagerService.UpdateConfigurationResult result) {
4866 int changes = 0;
4867 boolean kept = true;
4868
4869 if (mWindowManager != null) {
4870 mWindowManager.deferSurfaceLayout();
4871 }
4872 try {
4873 if (values != null) {
4874 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4875 deferResume);
4876 }
4877
4878 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4879 } finally {
4880 if (mWindowManager != null) {
4881 mWindowManager.continueSurfaceLayout();
4882 }
4883 }
4884
4885 if (result != null) {
4886 result.changes = changes;
4887 result.activityRelaunched = !kept;
4888 }
4889 return kept;
4890 }
4891
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004892 /** Update default (global) configuration and notify listeners about changes. */
4893 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4894 boolean persistent, int userId, boolean deferResume) {
4895 mTempConfig.setTo(getGlobalConfiguration());
4896 final int changes = mTempConfig.updateFrom(values);
4897 if (changes == 0) {
4898 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4899 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4900 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4901 // (even if there are no actual changes) to unfreeze the window.
4902 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4903 return 0;
4904 }
4905
4906 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4907 "Updating global configuration to: " + values);
4908
4909 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4910 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4911 values.colorMode,
4912 values.densityDpi,
4913 values.fontScale,
4914 values.hardKeyboardHidden,
4915 values.keyboard,
4916 values.keyboardHidden,
4917 values.mcc,
4918 values.mnc,
4919 values.navigation,
4920 values.navigationHidden,
4921 values.orientation,
4922 values.screenHeightDp,
4923 values.screenLayout,
4924 values.screenWidthDp,
4925 values.smallestScreenWidthDp,
4926 values.touchscreen,
4927 values.uiMode);
4928
4929
4930 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4931 final LocaleList locales = values.getLocales();
4932 int bestLocaleIndex = 0;
4933 if (locales.size() > 1) {
4934 if (mSupportedSystemLocales == null) {
4935 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4936 }
4937 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4938 }
4939 SystemProperties.set("persist.sys.locale",
4940 locales.get(bestLocaleIndex).toLanguageTag());
4941 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004942
4943 final Message m = PooledLambda.obtainMessage(
4944 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4945 locales.get(bestLocaleIndex));
4946 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004947 }
4948
Yunfan Chen75157d72018-07-27 14:47:21 +09004949 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004950
4951 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004952 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004953
4954 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4955 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004956 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004957
4958 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004959 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004960
4961 AttributeCache ac = AttributeCache.instance();
4962 if (ac != null) {
4963 ac.updateConfiguration(mTempConfig);
4964 }
4965
4966 // Make sure all resources in our process are updated right now, so that anyone who is going
4967 // to retrieve resource values after we return will be sure to get the new ones. This is
4968 // especially important during boot, where the first config change needs to guarantee all
4969 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004970 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004971
4972 // We need another copy of global config because we're scheduling some calls instead of
4973 // running them in place. We need to be sure that object we send will be handled unchanged.
4974 final Configuration configCopy = new Configuration(mTempConfig);
4975 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004976 final Message msg = PooledLambda.obtainMessage(
4977 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4978 this, userId, configCopy);
4979 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004980 }
4981
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004982 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004983 final int pid = mPidMap.keyAt(i);
4984 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004985 if (DEBUG_CONFIGURATION) {
4986 Slog.v(TAG_CONFIGURATION, "Update process config of "
4987 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004988 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004989 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004990 }
4991
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004992 final Message msg = PooledLambda.obtainMessage(
4993 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4994 mAmInternal, changes, initLocale);
4995 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004996
4997 // Override configuration of the default display duplicates global config, so we need to
4998 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004999 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005000 DEFAULT_DISPLAY);
5001
5002 return changes;
5003 }
5004
5005 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5006 boolean deferResume, int displayId) {
5007 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5008 displayId, null /* result */);
5009 }
5010
5011 /**
5012 * Updates override configuration specific for the selected display. If no config is provided,
5013 * new one will be computed in WM based on current display info.
5014 */
5015 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5016 ActivityRecord starting, boolean deferResume, int displayId,
5017 ActivityTaskManagerService.UpdateConfigurationResult result) {
5018 int changes = 0;
5019 boolean kept = true;
5020
5021 if (mWindowManager != null) {
5022 mWindowManager.deferSurfaceLayout();
5023 }
5024 try {
5025 if (values != null) {
5026 if (displayId == DEFAULT_DISPLAY) {
5027 // Override configuration of the default display duplicates global config, so
5028 // we're calling global config update instead for default display. It will also
5029 // apply the correct override config.
5030 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5031 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5032 } else {
5033 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5034 }
5035 }
5036
5037 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5038 } finally {
5039 if (mWindowManager != null) {
5040 mWindowManager.continueSurfaceLayout();
5041 }
5042 }
5043
5044 if (result != null) {
5045 result.changes = changes;
5046 result.activityRelaunched = !kept;
5047 }
5048 return kept;
5049 }
5050
5051 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5052 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005053 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005054 final int changes = mTempConfig.updateFrom(values);
5055 if (changes != 0) {
5056 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5057 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005058 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005059
5060 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5061 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005062 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005063
Wale Ogunwale5c918702018-10-18 11:06:33 -07005064 // Post message to start process to avoid possible deadlock of calling into AMS with
5065 // the ATMS lock held.
5066 final Message msg = PooledLambda.obtainMessage(
5067 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5068 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5069 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005070 }
5071 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072 return changes;
5073 }
5074
Wale Ogunwalef6733932018-06-27 05:14:34 -07005075 private void updateEventDispatchingLocked(boolean booted) {
5076 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5077 }
5078
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005079 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5080 final ContentResolver resolver = mContext.getContentResolver();
5081 Settings.System.putConfigurationForUser(resolver, config, userId);
5082 }
5083
5084 private void sendLocaleToMountDaemonMsg(Locale l) {
5085 try {
5086 IBinder service = ServiceManager.getService("mount");
5087 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5088 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5089 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5090 } catch (RemoteException e) {
5091 Log.e(TAG, "Error storing locale for decryption UI", e);
5092 }
5093 }
5094
Alison Cichowlas3e340502018-08-07 17:15:01 -04005095 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5096 mStartActivitySources.remove(permissionToken);
5097 mExpiredStartAsCallerTokens.add(permissionToken);
5098 }
5099
5100 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5101 mExpiredStartAsCallerTokens.remove(permissionToken);
5102 }
5103
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005104 boolean isActivityStartsLoggingEnabled() {
5105 return mAmInternal.isActivityStartsLoggingEnabled();
5106 }
5107
Michal Karpinski8596ded2018-11-14 14:43:48 +00005108 boolean isBackgroundActivityStartsEnabled() {
5109 return mAmInternal.isBackgroundActivityStartsEnabled();
5110 }
5111
Wale Ogunwalef6733932018-06-27 05:14:34 -07005112 void enableScreenAfterBoot(boolean booted) {
5113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5114 SystemClock.uptimeMillis());
5115 mWindowManager.enableScreenAfterBoot();
5116
5117 synchronized (mGlobalLock) {
5118 updateEventDispatchingLocked(booted);
5119 }
5120 }
5121
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005122 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5123 if (r == null || !r.hasProcess()) {
5124 return KEY_DISPATCHING_TIMEOUT_MS;
5125 }
5126 return getInputDispatchingTimeoutLocked(r.app);
5127 }
5128
5129 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005130 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005131 }
5132
Wale Ogunwalef6733932018-06-27 05:14:34 -07005133 /**
5134 * Decide based on the configuration whether we should show the ANR,
5135 * crash, etc dialogs. The idea is that if there is no affordance to
5136 * press the on-screen buttons, or the user experience would be more
5137 * greatly impacted than the crash itself, we shouldn't show the dialog.
5138 *
5139 * A thought: SystemUI might also want to get told about this, the Power
5140 * dialog / global actions also might want different behaviors.
5141 */
5142 private void updateShouldShowDialogsLocked(Configuration config) {
5143 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5144 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5145 && config.navigation == Configuration.NAVIGATION_NONAV);
5146 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5147 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5148 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5149 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5150 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5151 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5152 HIDE_ERROR_DIALOGS, 0) != 0;
5153 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5154 }
5155
5156 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5157 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5158 FONT_SCALE, 1.0f, userId);
5159
5160 synchronized (this) {
5161 if (getGlobalConfiguration().fontScale == scaleFactor) {
5162 return;
5163 }
5164
5165 final Configuration configuration
5166 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5167 configuration.fontScale = scaleFactor;
5168 updatePersistentConfiguration(configuration, userId);
5169 }
5170 }
5171
5172 // Actually is sleeping or shutting down or whatever else in the future
5173 // is an inactive state.
5174 boolean isSleepingOrShuttingDownLocked() {
5175 return isSleepingLocked() || mShuttingDown;
5176 }
5177
5178 boolean isSleepingLocked() {
5179 return mSleeping;
5180 }
5181
Riddle Hsu16567132018-08-16 21:37:47 +08005182 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005183 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005184 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005185 if (task.isActivityTypeStandard()) {
5186 if (mCurAppTimeTracker != r.appTimeTracker) {
5187 // We are switching app tracking. Complete the current one.
5188 if (mCurAppTimeTracker != null) {
5189 mCurAppTimeTracker.stop();
5190 mH.obtainMessage(
5191 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005192 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005193 mCurAppTimeTracker = null;
5194 }
5195 if (r.appTimeTracker != null) {
5196 mCurAppTimeTracker = r.appTimeTracker;
5197 startTimeTrackingFocusedActivityLocked();
5198 }
5199 } else {
5200 startTimeTrackingFocusedActivityLocked();
5201 }
5202 } else {
5203 r.appTimeTracker = null;
5204 }
5205 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5206 // TODO: Probably not, because we don't want to resume voice on switching
5207 // back to this activity
5208 if (task.voiceInteractor != null) {
5209 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5210 } else {
5211 finishRunningVoiceLocked();
5212
5213 if (mLastResumedActivity != null) {
5214 final IVoiceInteractionSession session;
5215
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005216 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005217 if (lastResumedActivityTask != null
5218 && lastResumedActivityTask.voiceSession != null) {
5219 session = lastResumedActivityTask.voiceSession;
5220 } else {
5221 session = mLastResumedActivity.voiceSession;
5222 }
5223
5224 if (session != null) {
5225 // We had been in a voice interaction session, but now focused has
5226 // move to something different. Just finish the session, we can't
5227 // return to it and retain the proper state and synchronization with
5228 // the voice interaction service.
5229 finishVoiceTask(session);
5230 }
5231 }
5232 }
5233
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005234 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5235 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005236 }
5237 updateResumedAppTrace(r);
5238 mLastResumedActivity = r;
5239
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005240 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005241
5242 applyUpdateLockStateLocked(r);
5243 applyUpdateVrModeLocked(r);
5244
5245 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005246 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005247 r == null ? "NULL" : r.shortComponentName,
5248 reason);
5249 }
5250
5251 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5252 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005253 final ActivityTaskManagerInternal.SleepToken token =
5254 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005255 updateSleepIfNeededLocked();
5256 return token;
5257 }
5258 }
5259
5260 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005261 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005262 final boolean wasSleeping = mSleeping;
5263 boolean updateOomAdj = false;
5264
5265 if (!shouldSleep) {
5266 // If wasSleeping is true, we need to wake up activity manager state from when
5267 // we started sleeping. In either case, we need to apply the sleep tokens, which
5268 // will wake up stacks or put them to sleep as appropriate.
5269 if (wasSleeping) {
5270 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005271 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5272 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005273 startTimeTrackingFocusedActivityLocked();
5274 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5275 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5276 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005277 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005278 if (wasSleeping) {
5279 updateOomAdj = true;
5280 }
5281 } else if (!mSleeping && shouldSleep) {
5282 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005283 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5284 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005285 if (mCurAppTimeTracker != null) {
5286 mCurAppTimeTracker.stop();
5287 }
5288 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5289 mStackSupervisor.goingToSleepLocked();
5290 updateResumedAppTrace(null /* resumed */);
5291 updateOomAdj = true;
5292 }
5293 if (updateOomAdj) {
5294 mH.post(mAmInternal::updateOomAdj);
5295 }
5296 }
5297
5298 void updateOomAdj() {
5299 mH.post(mAmInternal::updateOomAdj);
5300 }
5301
Wale Ogunwale53783742018-09-16 10:21:51 -07005302 void updateCpuStats() {
5303 mH.post(mAmInternal::updateCpuStats);
5304 }
5305
Hui Yu03d12402018-12-06 18:00:37 -08005306 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5307 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005308 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5309 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005310 mH.sendMessage(m);
5311 }
5312
Hui Yu03d12402018-12-06 18:00:37 -08005313 void updateActivityUsageStats(ActivityRecord activity, int event) {
5314 final Message m = PooledLambda.obtainMessage(
5315 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
5316 activity.mActivityComponent, activity.mUserId, event, activity.appToken);
5317 mH.sendMessage(m);
5318 }
5319
Wale Ogunwale53783742018-09-16 10:21:51 -07005320 void setBooting(boolean booting) {
5321 mAmInternal.setBooting(booting);
5322 }
5323
5324 boolean isBooting() {
5325 return mAmInternal.isBooting();
5326 }
5327
5328 void setBooted(boolean booted) {
5329 mAmInternal.setBooted(booted);
5330 }
5331
5332 boolean isBooted() {
5333 return mAmInternal.isBooted();
5334 }
5335
5336 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5337 mH.post(() -> {
5338 if (finishBooting) {
5339 mAmInternal.finishBooting();
5340 }
5341 if (enableScreen) {
5342 mInternal.enableScreenAfterBoot(isBooted());
5343 }
5344 });
5345 }
5346
5347 void setHeavyWeightProcess(ActivityRecord root) {
5348 mHeavyWeightProcess = root.app;
5349 final Message m = PooledLambda.obtainMessage(
5350 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005351 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005352 mH.sendMessage(m);
5353 }
5354
5355 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5356 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5357 return;
5358 }
5359
5360 mHeavyWeightProcess = null;
5361 final Message m = PooledLambda.obtainMessage(
5362 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5363 proc.mUserId);
5364 mH.sendMessage(m);
5365 }
5366
5367 private void cancelHeavyWeightProcessNotification(int userId) {
5368 final INotificationManager inm = NotificationManager.getService();
5369 if (inm == null) {
5370 return;
5371 }
5372 try {
5373 inm.cancelNotificationWithTag("android", null,
5374 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5375 } catch (RuntimeException e) {
5376 Slog.w(TAG, "Error canceling notification for service", e);
5377 } catch (RemoteException e) {
5378 }
5379
5380 }
5381
5382 private void postHeavyWeightProcessNotification(
5383 WindowProcessController proc, Intent intent, int userId) {
5384 if (proc == null) {
5385 return;
5386 }
5387
5388 final INotificationManager inm = NotificationManager.getService();
5389 if (inm == null) {
5390 return;
5391 }
5392
5393 try {
5394 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5395 String text = mContext.getString(R.string.heavy_weight_notification,
5396 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5397 Notification notification =
5398 new Notification.Builder(context,
5399 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5400 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5401 .setWhen(0)
5402 .setOngoing(true)
5403 .setTicker(text)
5404 .setColor(mContext.getColor(
5405 com.android.internal.R.color.system_notification_accent_color))
5406 .setContentTitle(text)
5407 .setContentText(
5408 mContext.getText(R.string.heavy_weight_notification_detail))
5409 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5410 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5411 new UserHandle(userId)))
5412 .build();
5413 try {
5414 inm.enqueueNotificationWithTag("android", "android", null,
5415 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5416 } catch (RuntimeException e) {
5417 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5418 } catch (RemoteException e) {
5419 }
5420 } catch (PackageManager.NameNotFoundException e) {
5421 Slog.w(TAG, "Unable to create context for heavy notification", e);
5422 }
5423
5424 }
5425
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005426 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5427 IBinder token, String resultWho, int requestCode, Intent[] intents,
5428 String[] resolvedTypes, int flags, Bundle bOptions) {
5429
5430 ActivityRecord activity = null;
5431 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5432 activity = ActivityRecord.isInStackLocked(token);
5433 if (activity == null) {
5434 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5435 return null;
5436 }
5437 if (activity.finishing) {
5438 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5439 return null;
5440 }
5441 }
5442
5443 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5444 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5445 bOptions);
5446 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5447 if (noCreate) {
5448 return rec;
5449 }
5450 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5451 if (activity.pendingResults == null) {
5452 activity.pendingResults = new HashSet<>();
5453 }
5454 activity.pendingResults.add(rec.ref);
5455 }
5456 return rec;
5457 }
5458
Andrii Kulian52d255c2018-07-13 11:32:19 -07005459 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005460 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005461 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005462 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5463 mCurAppTimeTracker.start(resumedActivity.packageName);
5464 }
5465 }
5466
5467 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5468 if (mTracedResumedActivity != null) {
5469 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5470 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5471 }
5472 if (resumed != null) {
5473 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5474 constructResumedTraceName(resumed.packageName), 0);
5475 }
5476 mTracedResumedActivity = resumed;
5477 }
5478
5479 private String constructResumedTraceName(String packageName) {
5480 return "focused app: " + packageName;
5481 }
5482
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005483 /** Applies latest configuration and/or visibility updates if needed. */
5484 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5485 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005486 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005487 // mainStack is null during startup.
5488 if (mainStack != null) {
5489 if (changes != 0 && starting == null) {
5490 // If the configuration changed, and the caller is not already
5491 // in the process of starting an activity, then find the top
5492 // activity to check if its configuration needs to change.
5493 starting = mainStack.topRunningActivityLocked();
5494 }
5495
5496 if (starting != null) {
5497 kept = starting.ensureActivityConfiguration(changes,
5498 false /* preserveWindow */);
5499 // And we need to make sure at this point that all other activities
5500 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005501 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005502 !PRESERVE_WINDOWS);
5503 }
5504 }
5505
5506 return kept;
5507 }
5508
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005509 void scheduleAppGcsLocked() {
5510 mH.post(() -> mAmInternal.scheduleAppGcs());
5511 }
5512
Wale Ogunwale53783742018-09-16 10:21:51 -07005513 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5514 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5515 }
5516
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005517 /**
5518 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5519 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5520 * on demand.
5521 */
5522 IPackageManager getPackageManager() {
5523 return AppGlobals.getPackageManager();
5524 }
5525
5526 PackageManagerInternal getPackageManagerInternalLocked() {
5527 if (mPmInternal == null) {
5528 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5529 }
5530 return mPmInternal;
5531 }
5532
Wale Ogunwale008163e2018-07-23 23:11:08 -07005533 AppWarnings getAppWarningsLocked() {
5534 return mAppWarnings;
5535 }
5536
Wale Ogunwale214f3482018-10-04 11:00:47 -07005537 Intent getHomeIntent() {
5538 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5539 intent.setComponent(mTopComponent);
5540 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5541 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5542 intent.addCategory(Intent.CATEGORY_HOME);
5543 }
5544 return intent;
5545 }
5546
Chilun2ef71f72018-11-16 17:57:15 +08005547 /**
5548 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5549 * activities.
5550 *
5551 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5552 * component defined in config_secondaryHomeComponent.
5553 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5554 */
5555 Intent getSecondaryHomeIntent(String preferredPackage) {
5556 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5557 if (preferredPackage == null) {
5558 // Using the component stored in config if no package name.
5559 final String secondaryHomeComponent = mContext.getResources().getString(
5560 com.android.internal.R.string.config_secondaryHomeComponent);
5561 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5562 } else {
5563 intent.setPackage(preferredPackage);
5564 }
5565 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5566 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5567 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5568 }
5569 return intent;
5570 }
5571
Wale Ogunwale214f3482018-10-04 11:00:47 -07005572 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5573 if (info == null) return null;
5574 ApplicationInfo newInfo = new ApplicationInfo(info);
5575 newInfo.initForUser(userId);
5576 return newInfo;
5577 }
5578
Wale Ogunwale9c103022018-10-18 07:44:54 -07005579 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005580 if (uid == SYSTEM_UID) {
5581 // The system gets to run in any process. If there are multiple processes with the same
5582 // uid, just pick the first (this should never happen).
5583 final SparseArray<WindowProcessController> procs =
5584 mProcessNames.getMap().get(processName);
5585 if (procs == null) return null;
5586 final int procCount = procs.size();
5587 for (int i = 0; i < procCount; i++) {
5588 final int procUid = procs.keyAt(i);
5589 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5590 // Don't use an app process or different user process for system component.
5591 continue;
5592 }
5593 return procs.valueAt(i);
5594 }
5595 }
5596
5597 return mProcessNames.get(processName, uid);
5598 }
5599
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005600 WindowProcessController getProcessController(IApplicationThread thread) {
5601 if (thread == null) {
5602 return null;
5603 }
5604
5605 final IBinder threadBinder = thread.asBinder();
5606 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5607 for (int i = pmap.size()-1; i >= 0; i--) {
5608 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5609 for (int j = procs.size() - 1; j >= 0; j--) {
5610 final WindowProcessController proc = procs.valueAt(j);
5611 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5612 return proc;
5613 }
5614 }
5615 }
5616
5617 return null;
5618 }
5619
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005620 int getUidStateLocked(int uid) {
5621 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5622 }
5623
Wale Ogunwale9de19442018-10-18 19:05:03 -07005624 /**
5625 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5626 * the whitelist
5627 */
5628 String getPendingTempWhitelistTagForUidLocked(int uid) {
5629 return mPendingTempWhitelist.get(uid);
5630 }
5631
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005632 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5633 if (true || Build.IS_USER) {
5634 return;
5635 }
5636
5637 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5638 StrictMode.allowThreadDiskWrites();
5639 try {
5640 File tracesDir = new File("/data/anr");
5641 File tracesFile = null;
5642 try {
5643 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5644
5645 StringBuilder sb = new StringBuilder();
5646 Time tobj = new Time();
5647 tobj.set(System.currentTimeMillis());
5648 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5649 sb.append(": ");
5650 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5651 sb.append(" since ");
5652 sb.append(msg);
5653 FileOutputStream fos = new FileOutputStream(tracesFile);
5654 fos.write(sb.toString().getBytes());
5655 if (app == null) {
5656 fos.write("\n*** No application process!".getBytes());
5657 }
5658 fos.close();
5659 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5660 } catch (IOException e) {
5661 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5662 return;
5663 }
5664
5665 if (app != null && app.getPid() > 0) {
5666 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5667 firstPids.add(app.getPid());
5668 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5669 }
5670
5671 File lastTracesFile = null;
5672 File curTracesFile = null;
5673 for (int i=9; i>=0; i--) {
5674 String name = String.format(Locale.US, "slow%02d.txt", i);
5675 curTracesFile = new File(tracesDir, name);
5676 if (curTracesFile.exists()) {
5677 if (lastTracesFile != null) {
5678 curTracesFile.renameTo(lastTracesFile);
5679 } else {
5680 curTracesFile.delete();
5681 }
5682 }
5683 lastTracesFile = curTracesFile;
5684 }
5685 tracesFile.renameTo(curTracesFile);
5686 } finally {
5687 StrictMode.setThreadPolicy(oldPolicy);
5688 }
5689 }
5690
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005691 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005692 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005693
5694
Wale Ogunwale98875612018-10-12 07:53:02 -07005695 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5696 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005697
Riddle Hsud93a6c42018-11-29 21:50:06 +08005698 H(Looper looper) {
5699 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005700 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005701
5702 @Override
5703 public void handleMessage(Message msg) {
5704 switch (msg.what) {
5705 case REPORT_TIME_TRACKER_MSG: {
5706 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5707 tracker.deliverResult(mContext);
5708 } break;
5709 }
5710 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005711 }
5712
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005713 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005714 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005715
5716 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005717 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005718 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005719
5720 @Override
5721 public void handleMessage(Message msg) {
5722 switch (msg.what) {
5723 case DISMISS_DIALOG_UI_MSG: {
5724 final Dialog d = (Dialog) msg.obj;
5725 d.dismiss();
5726 break;
5727 }
5728 }
5729 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005730 }
5731
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005732 final class LocalService extends ActivityTaskManagerInternal {
5733 @Override
5734 public SleepToken acquireSleepToken(String tag, int displayId) {
5735 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005736 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005737 }
5738
5739 @Override
5740 public ComponentName getHomeActivityForUser(int userId) {
5741 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005742 final ActivityRecord homeActivity =
5743 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005744 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005745 }
5746 }
5747
5748 @Override
5749 public void onLocalVoiceInteractionStarted(IBinder activity,
5750 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5751 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005752 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005753 }
5754 }
5755
5756 @Override
5757 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5758 synchronized (mGlobalLock) {
5759 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5760 reasons, timestamp);
5761 }
5762 }
5763
5764 @Override
5765 public void notifyAppTransitionFinished() {
5766 synchronized (mGlobalLock) {
5767 mStackSupervisor.notifyAppTransitionDone();
5768 }
5769 }
5770
5771 @Override
5772 public void notifyAppTransitionCancelled() {
5773 synchronized (mGlobalLock) {
5774 mStackSupervisor.notifyAppTransitionDone();
5775 }
5776 }
5777
5778 @Override
5779 public List<IBinder> getTopVisibleActivities() {
5780 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005781 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005782 }
5783 }
5784
5785 @Override
5786 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5787 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005788 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005789 }
5790 }
5791
5792 @Override
5793 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5794 Bundle bOptions) {
5795 Preconditions.checkNotNull(intents, "intents");
5796 final String[] resolvedTypes = new String[intents.length];
5797
5798 // UID of the package on user userId.
5799 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5800 // packageUid may not be initialized.
5801 int packageUid = 0;
5802 final long ident = Binder.clearCallingIdentity();
5803
5804 try {
5805 for (int i = 0; i < intents.length; i++) {
5806 resolvedTypes[i] =
5807 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5808 }
5809
5810 packageUid = AppGlobals.getPackageManager().getPackageUid(
5811 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5812 } catch (RemoteException e) {
5813 // Shouldn't happen.
5814 } finally {
5815 Binder.restoreCallingIdentity(ident);
5816 }
5817
5818 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005819 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005820 packageUid, packageName,
5821 intents, resolvedTypes, null /* resultTo */,
5822 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005823 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5824 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005825 }
5826 }
5827
5828 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005829 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5830 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005831 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
5832 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005833 synchronized (mGlobalLock) {
5834 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5835 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005836 originatingPendingIntent, allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005837 }
5838 }
5839
5840 @Override
5841 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5842 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5843 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5844 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005845 PendingIntentRecord originatingPendingIntent,
5846 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005847 synchronized (mGlobalLock) {
5848 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5849 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5850 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005851 validateIncomingUser, originatingPendingIntent,
5852 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005853 }
5854 }
5855
5856 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005857 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5858 Intent intent, Bundle options, int userId) {
5859 return ActivityTaskManagerService.this.startActivityAsUser(
5860 caller, callerPacakge, intent,
5861 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5862 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5863 false /*validateIncomingUser*/);
5864 }
5865
5866 @Override
lumark588a3e82018-07-20 18:53:54 +08005867 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005868 synchronized (mGlobalLock) {
5869
5870 // We might change the visibilities here, so prepare an empty app transition which
5871 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005872 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005873 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005874 if (activityDisplay == null) {
5875 return;
5876 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005877 final DisplayContent dc = activityDisplay.mDisplayContent;
5878 final boolean wasTransitionSet =
5879 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005880 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005881 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005882 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005883 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005884
5885 // If there was a transition set already we don't want to interfere with it as we
5886 // might be starting it too early.
5887 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005888 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005889 }
5890 }
5891 if (callback != null) {
5892 callback.run();
5893 }
5894 }
5895
5896 @Override
5897 public void notifyKeyguardTrustedChanged() {
5898 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005899 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005900 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005901 }
5902 }
5903 }
5904
5905 /**
5906 * Called after virtual display Id is updated by
5907 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5908 * {@param vrVr2dDisplayId}.
5909 */
5910 @Override
5911 public void setVr2dDisplayId(int vr2dDisplayId) {
5912 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5913 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005914 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005915 }
5916 }
5917
5918 @Override
5919 public void setFocusedActivity(IBinder token) {
5920 synchronized (mGlobalLock) {
5921 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5922 if (r == null) {
5923 throw new IllegalArgumentException(
5924 "setFocusedActivity: No activity record matching token=" + token);
5925 }
Louis Chang19443452018-10-09 12:10:21 +08005926 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005927 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005928 }
5929 }
5930 }
5931
5932 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005933 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005934 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005935 }
5936
5937 @Override
5938 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005939 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005940 }
5941
5942 @Override
5943 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005944 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005945 }
5946
5947 @Override
5948 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5949 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5950 }
5951
5952 @Override
5953 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005954 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005955 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005956
5957 @Override
5958 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5959 synchronized (mGlobalLock) {
5960 mActiveVoiceInteractionServiceComponent = component;
5961 }
5962 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005963
5964 @Override
5965 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5966 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5967 return;
5968 }
5969 synchronized (mGlobalLock) {
5970 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5971 if (types == null) {
5972 if (uid < 0) {
5973 return;
5974 }
5975 types = new ArrayMap<>();
5976 mAllowAppSwitchUids.put(userId, types);
5977 }
5978 if (uid < 0) {
5979 types.remove(type);
5980 } else {
5981 types.put(type, uid);
5982 }
5983 }
5984 }
5985
5986 @Override
5987 public void onUserStopped(int userId) {
5988 synchronized (mGlobalLock) {
5989 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5990 mAllowAppSwitchUids.remove(userId);
5991 }
5992 }
5993
5994 @Override
5995 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5996 synchronized (mGlobalLock) {
5997 return ActivityTaskManagerService.this.isGetTasksAllowed(
5998 caller, callingPid, callingUid);
5999 }
6000 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006001
6002 @Override
6003 public void onProcessAdded(WindowProcessController proc) {
6004 synchronized (mGlobalLock) {
6005 mProcessNames.put(proc.mName, proc.mUid, proc);
6006 }
6007 }
6008
6009 @Override
6010 public void onProcessRemoved(String name, int uid) {
6011 synchronized (mGlobalLock) {
6012 mProcessNames.remove(name, uid);
6013 }
6014 }
6015
6016 @Override
6017 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6018 synchronized (mGlobalLock) {
6019 if (proc == mHomeProcess) {
6020 mHomeProcess = null;
6021 }
6022 if (proc == mPreviousProcess) {
6023 mPreviousProcess = null;
6024 }
6025 }
6026 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006027
6028 @Override
6029 public int getTopProcessState() {
6030 synchronized (mGlobalLock) {
6031 return mTopProcessState;
6032 }
6033 }
6034
6035 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006036 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6037 synchronized (mGlobalLock) {
6038 return proc == mHeavyWeightProcess;
6039 }
6040 }
6041
6042 @Override
6043 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6044 synchronized (mGlobalLock) {
6045 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6046 }
6047 }
6048
6049 @Override
6050 public void finishHeavyWeightApp() {
6051 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006052 if (mHeavyWeightProcess != null) {
6053 mHeavyWeightProcess.finishActivities();
6054 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006055 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6056 mHeavyWeightProcess);
6057 }
6058 }
6059
6060 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006061 public boolean isSleeping() {
6062 synchronized (mGlobalLock) {
6063 return isSleepingLocked();
6064 }
6065 }
6066
6067 @Override
6068 public boolean isShuttingDown() {
6069 synchronized (mGlobalLock) {
6070 return mShuttingDown;
6071 }
6072 }
6073
6074 @Override
6075 public boolean shuttingDown(boolean booted, int timeout) {
6076 synchronized (mGlobalLock) {
6077 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006078 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006079 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006080 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006081 return mStackSupervisor.shutdownLocked(timeout);
6082 }
6083 }
6084
6085 @Override
6086 public void enableScreenAfterBoot(boolean booted) {
6087 synchronized (mGlobalLock) {
6088 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6089 SystemClock.uptimeMillis());
6090 mWindowManager.enableScreenAfterBoot();
6091 updateEventDispatchingLocked(booted);
6092 }
6093 }
6094
6095 @Override
6096 public boolean showStrictModeViolationDialog() {
6097 synchronized (mGlobalLock) {
6098 return mShowDialogs && !mSleeping && !mShuttingDown;
6099 }
6100 }
6101
6102 @Override
6103 public void showSystemReadyErrorDialogsIfNeeded() {
6104 synchronized (mGlobalLock) {
6105 try {
6106 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6107 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6108 + " data partition or your device will be unstable.");
6109 mUiHandler.post(() -> {
6110 if (mShowDialogs) {
6111 AlertDialog d = new BaseErrorDialog(mUiContext);
6112 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6113 d.setCancelable(false);
6114 d.setTitle(mUiContext.getText(R.string.android_system_label));
6115 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6116 d.setButton(DialogInterface.BUTTON_POSITIVE,
6117 mUiContext.getText(R.string.ok),
6118 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6119 d.show();
6120 }
6121 });
6122 }
6123 } catch (RemoteException e) {
6124 }
6125
6126 if (!Build.isBuildConsistent()) {
6127 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6128 mUiHandler.post(() -> {
6129 if (mShowDialogs) {
6130 AlertDialog d = new BaseErrorDialog(mUiContext);
6131 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6132 d.setCancelable(false);
6133 d.setTitle(mUiContext.getText(R.string.android_system_label));
6134 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6135 d.setButton(DialogInterface.BUTTON_POSITIVE,
6136 mUiContext.getText(R.string.ok),
6137 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6138 d.show();
6139 }
6140 });
6141 }
6142 }
6143 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006144
6145 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006146 public void onProcessMapped(int pid, WindowProcessController proc) {
6147 synchronized (mGlobalLock) {
6148 mPidMap.put(pid, proc);
6149 }
6150 }
6151
6152 @Override
6153 public void onProcessUnMapped(int pid) {
6154 synchronized (mGlobalLock) {
6155 mPidMap.remove(pid);
6156 }
6157 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006158
6159 @Override
6160 public void onPackageDataCleared(String name) {
6161 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006162 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006163 mAppWarnings.onPackageDataCleared(name);
6164 }
6165 }
6166
6167 @Override
6168 public void onPackageUninstalled(String name) {
6169 synchronized (mGlobalLock) {
6170 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006171 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006172 }
6173 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006174
6175 @Override
6176 public void onPackageAdded(String name, boolean replacing) {
6177 synchronized (mGlobalLock) {
6178 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6179 }
6180 }
6181
6182 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006183 public void onPackageReplaced(ApplicationInfo aInfo) {
6184 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006185 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006186 }
6187 }
6188
6189 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006190 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6191 synchronized (mGlobalLock) {
6192 return compatibilityInfoForPackageLocked(ai);
6193 }
6194 }
6195
Yunfan Chen75157d72018-07-27 14:47:21 +09006196 /**
6197 * Set the corresponding display information for the process global configuration. To be
6198 * called when we need to show IME on a different display.
6199 *
6200 * @param pid The process id associated with the IME window.
6201 * @param displayId The ID of the display showing the IME.
6202 */
6203 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006204 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006205 if (pid == MY_PID || pid < 0) {
6206 if (DEBUG_CONFIGURATION) {
6207 Slog.w(TAG,
6208 "Trying to update display configuration for system/invalid process.");
6209 }
6210 return;
6211 }
6212 mH.post(() -> {
6213 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006214 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006215 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006216 if (activityDisplay == null) {
6217 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006218 if (DEBUG_CONFIGURATION) {
6219 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006220 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006221 }
6222 return;
6223 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006224 final WindowProcessController process = mPidMap.get(pid);
6225 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006226 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006227 Slog.w(TAG, "Trying to update display configuration for invalid "
6228 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006229 }
6230 return;
6231 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006232 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006233 }
6234 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006235
Yunfan Chen75157d72018-07-27 14:47:21 +09006236 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006237
6238 @Override
6239 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6240 int requestCode, int resultCode, Intent data) {
6241 synchronized (mGlobalLock) {
6242 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006243 if (r != null && r.getActivityStack() != null) {
6244 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6245 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006246 }
6247 }
6248 }
6249
6250 @Override
6251 public void clearPendingResultForActivity(IBinder activityToken,
6252 WeakReference<PendingIntentRecord> pir) {
6253 synchronized (mGlobalLock) {
6254 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6255 if (r != null && r.pendingResults != null) {
6256 r.pendingResults.remove(pir);
6257 }
6258 }
6259 }
6260
6261 @Override
6262 public IIntentSender getIntentSender(int type, String packageName,
6263 int callingUid, int userId, IBinder token, String resultWho,
6264 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6265 Bundle bOptions) {
6266 synchronized (mGlobalLock) {
6267 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6268 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6269 }
6270 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006271
6272 @Override
6273 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6274 synchronized (mGlobalLock) {
6275 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6276 if (r == null) {
6277 return null;
6278 }
6279 if (r.mServiceConnectionsHolder == null) {
6280 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6281 ActivityTaskManagerService.this, r);
6282 }
6283
6284 return r.mServiceConnectionsHolder;
6285 }
6286 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006287
6288 @Override
6289 public Intent getHomeIntent() {
6290 synchronized (mGlobalLock) {
6291 return ActivityTaskManagerService.this.getHomeIntent();
6292 }
6293 }
6294
6295 @Override
6296 public boolean startHomeActivity(int userId, String reason) {
6297 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006298 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006299 }
6300 }
6301
6302 @Override
6303 public boolean startHomeOnAllDisplays(int userId, String reason) {
6304 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006305 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006306 }
6307 }
6308
6309 @Override
6310 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6311 synchronized (mGlobalLock) {
6312 if (mFactoryTest == FACTORY_TEST_OFF) {
6313 return false;
6314 }
6315 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6316 && wpc.mName.equals(mTopComponent.getPackageName())) {
6317 return true;
6318 }
6319 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6320 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6321 }
6322 }
6323
6324 @Override
6325 public void updateTopComponentForFactoryTest() {
6326 synchronized (mGlobalLock) {
6327 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6328 return;
6329 }
6330 final ResolveInfo ri = mContext.getPackageManager()
6331 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6332 final CharSequence errorMsg;
6333 if (ri != null) {
6334 final ActivityInfo ai = ri.activityInfo;
6335 final ApplicationInfo app = ai.applicationInfo;
6336 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6337 mTopAction = Intent.ACTION_FACTORY_TEST;
6338 mTopData = null;
6339 mTopComponent = new ComponentName(app.packageName, ai.name);
6340 errorMsg = null;
6341 } else {
6342 errorMsg = mContext.getResources().getText(
6343 com.android.internal.R.string.factorytest_not_system);
6344 }
6345 } else {
6346 errorMsg = mContext.getResources().getText(
6347 com.android.internal.R.string.factorytest_no_action);
6348 }
6349 if (errorMsg == null) {
6350 return;
6351 }
6352
6353 mTopAction = null;
6354 mTopData = null;
6355 mTopComponent = null;
6356 mUiHandler.post(() -> {
6357 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6358 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006359 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006360 });
6361 }
6362 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006363
6364 @Override
6365 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6366 Runnable finishInstrumentationCallback) {
6367 synchronized (mGlobalLock) {
6368 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006369 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006370
6371 wpc.clearRecentTasks();
6372 wpc.clearActivities();
6373
6374 if (wpc.isInstrumenting()) {
6375 finishInstrumentationCallback.run();
6376 }
6377
Jorim Jaggid0752812018-10-16 16:07:20 +02006378 if (!restarting && hasVisibleActivities) {
6379 mWindowManager.deferSurfaceLayout();
6380 try {
6381 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6382 // If there was nothing to resume, and we are not already restarting
6383 // this process, but there is a visible activity that is hosted by the
6384 // process...then make sure all visible activities are running, taking
6385 // care of restarting this process.
6386 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6387 !PRESERVE_WINDOWS);
6388 }
6389 } finally {
6390 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006391 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006392 }
6393 }
6394 }
6395
6396 @Override
6397 public void closeSystemDialogs(String reason) {
6398 enforceNotIsolatedCaller("closeSystemDialogs");
6399
6400 final int pid = Binder.getCallingPid();
6401 final int uid = Binder.getCallingUid();
6402 final long origId = Binder.clearCallingIdentity();
6403 try {
6404 synchronized (mGlobalLock) {
6405 // Only allow this from foreground processes, so that background
6406 // applications can't abuse it to prevent system UI from being shown.
6407 if (uid >= FIRST_APPLICATION_UID) {
6408 final WindowProcessController proc = mPidMap.get(pid);
6409 if (!proc.isPerceptible()) {
6410 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6411 + " from background process " + proc);
6412 return;
6413 }
6414 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006415 mWindowManager.closeSystemDialogs(reason);
6416
Wale Ogunwaled32da472018-11-16 07:19:28 -08006417 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006418 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006419 // Call into AM outside the synchronized block.
6420 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006421 } finally {
6422 Binder.restoreCallingIdentity(origId);
6423 }
6424 }
6425
6426 @Override
6427 public void cleanupDisabledPackageComponents(
6428 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6429 synchronized (mGlobalLock) {
6430 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006431 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006432 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006433 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006434 mStackSupervisor.scheduleIdleLocked();
6435 }
6436
6437 // Clean-up disabled tasks
6438 getRecentTasks().cleanupDisabledPackageTasksLocked(
6439 packageName, disabledClasses, userId);
6440 }
6441 }
6442
6443 @Override
6444 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6445 int userId) {
6446 synchronized (mGlobalLock) {
6447
6448 boolean didSomething =
6449 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006450 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006451 null, doit, evenPersistent, userId);
6452 return didSomething;
6453 }
6454 }
6455
6456 @Override
6457 public void resumeTopActivities(boolean scheduleIdle) {
6458 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006459 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006460 if (scheduleIdle) {
6461 mStackSupervisor.scheduleIdleLocked();
6462 }
6463 }
6464 }
6465
6466 @Override
6467 public void preBindApplication(WindowProcessController wpc) {
6468 synchronized (mGlobalLock) {
6469 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6470 }
6471 }
6472
6473 @Override
6474 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6475 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006476 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006477 }
6478 }
6479
6480 @Override
6481 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6482 try {
6483 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6484 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6485 }
6486 } catch (RemoteException ex) {
6487 throw new SecurityException("Fail to check is caller a privileged app", ex);
6488 }
6489
6490 synchronized (mGlobalLock) {
6491 final long ident = Binder.clearCallingIdentity();
6492 try {
6493 if (mAmInternal.shouldConfirmCredentials(userId)) {
6494 if (mKeyguardController.isKeyguardLocked()) {
6495 // Showing launcher to avoid user entering credential twice.
6496 startHomeActivity(currentUserId, "notifyLockedProfile");
6497 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006498 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006499 }
6500 } finally {
6501 Binder.restoreCallingIdentity(ident);
6502 }
6503 }
6504 }
6505
6506 @Override
6507 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6508 mAmInternal.enforceCallingPermission(
6509 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6510
6511 synchronized (mGlobalLock) {
6512 final long ident = Binder.clearCallingIdentity();
6513 try {
6514 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6515 FLAG_ACTIVITY_TASK_ON_HOME);
6516 ActivityOptions activityOptions = options != null
6517 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006518 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006519 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006520 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006521 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006522 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006523 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6524 UserHandle.CURRENT);
6525 } finally {
6526 Binder.restoreCallingIdentity(ident);
6527 }
6528 }
6529 }
6530
6531 @Override
6532 public void writeActivitiesToProto(ProtoOutputStream proto) {
6533 synchronized (mGlobalLock) {
6534 // The output proto of "activity --proto activities"
6535 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006536 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006537 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6538 }
6539 }
6540
6541 @Override
6542 public void saveANRState(String reason) {
6543 synchronized (mGlobalLock) {
6544 final StringWriter sw = new StringWriter();
6545 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6546 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6547 if (reason != null) {
6548 pw.println(" Reason: " + reason);
6549 }
6550 pw.println();
6551 getActivityStartController().dump(pw, " ", null);
6552 pw.println();
6553 pw.println("-------------------------------------------------------------------------------");
6554 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6555 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6556 "" /* header */);
6557 pw.println();
6558 pw.close();
6559
6560 mLastANRState = sw.toString();
6561 }
6562 }
6563
6564 @Override
6565 public void clearSavedANRState() {
6566 synchronized (mGlobalLock) {
6567 mLastANRState = null;
6568 }
6569 }
6570
6571 @Override
6572 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6573 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6574 synchronized (mGlobalLock) {
6575 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6576 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6577 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6578 dumpLastANRLocked(pw);
6579 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6580 dumpLastANRTracesLocked(pw);
6581 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6582 dumpActivityStarterLocked(pw, dumpPackage);
6583 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6584 dumpActivityContainersLocked(pw);
6585 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6586 if (getRecentTasks() != null) {
6587 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6588 }
6589 }
6590 }
6591 }
6592
6593 @Override
6594 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6595 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6596 int wakefulness) {
6597 synchronized (mGlobalLock) {
6598 if (mHomeProcess != null && (dumpPackage == null
6599 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6600 if (needSep) {
6601 pw.println();
6602 needSep = false;
6603 }
6604 pw.println(" mHomeProcess: " + mHomeProcess);
6605 }
6606 if (mPreviousProcess != null && (dumpPackage == null
6607 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6608 if (needSep) {
6609 pw.println();
6610 needSep = false;
6611 }
6612 pw.println(" mPreviousProcess: " + mPreviousProcess);
6613 }
6614 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6615 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6616 StringBuilder sb = new StringBuilder(128);
6617 sb.append(" mPreviousProcessVisibleTime: ");
6618 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6619 pw.println(sb);
6620 }
6621 if (mHeavyWeightProcess != null && (dumpPackage == null
6622 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6623 if (needSep) {
6624 pw.println();
6625 needSep = false;
6626 }
6627 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6628 }
6629 if (dumpPackage == null) {
6630 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006631 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006632 }
6633 if (dumpAll) {
6634 if (dumpPackage == null) {
6635 pw.println(" mConfigWillChange: "
6636 + getTopDisplayFocusedStack().mConfigWillChange);
6637 }
6638 if (mCompatModePackages.getPackages().size() > 0) {
6639 boolean printed = false;
6640 for (Map.Entry<String, Integer> entry
6641 : mCompatModePackages.getPackages().entrySet()) {
6642 String pkg = entry.getKey();
6643 int mode = entry.getValue();
6644 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6645 continue;
6646 }
6647 if (!printed) {
6648 pw.println(" mScreenCompatPackages:");
6649 printed = true;
6650 }
6651 pw.println(" " + pkg + ": " + mode);
6652 }
6653 }
6654 }
6655
6656 if (dumpPackage == null) {
6657 pw.println(" mWakefulness="
6658 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006659 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006660 if (mRunningVoice != null) {
6661 pw.println(" mRunningVoice=" + mRunningVoice);
6662 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6663 }
6664 pw.println(" mSleeping=" + mSleeping);
6665 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6666 pw.println(" mVrController=" + mVrController);
6667 }
6668 if (mCurAppTimeTracker != null) {
6669 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6670 }
6671 if (mAllowAppSwitchUids.size() > 0) {
6672 boolean printed = false;
6673 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6674 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6675 for (int j = 0; j < types.size(); j++) {
6676 if (dumpPackage == null ||
6677 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6678 if (needSep) {
6679 pw.println();
6680 needSep = false;
6681 }
6682 if (!printed) {
6683 pw.println(" mAllowAppSwitchUids:");
6684 printed = true;
6685 }
6686 pw.print(" User ");
6687 pw.print(mAllowAppSwitchUids.keyAt(i));
6688 pw.print(": Type ");
6689 pw.print(types.keyAt(j));
6690 pw.print(" = ");
6691 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6692 pw.println();
6693 }
6694 }
6695 }
6696 }
6697 if (dumpPackage == null) {
6698 if (mController != null) {
6699 pw.println(" mController=" + mController
6700 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6701 }
6702 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6703 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6704 }
6705
6706 return needSep;
6707 }
6708 }
6709
6710 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006711 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6712 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 synchronized (mGlobalLock) {
6714 if (dumpPackage == null) {
6715 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6716 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006717 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6718 if (mRunningVoice != null) {
6719 final long vrToken = proto.start(
6720 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6721 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6722 mRunningVoice.toString());
6723 mVoiceWakeLock.writeToProto(
6724 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6725 proto.end(vrToken);
6726 }
6727 mVrController.writeToProto(proto,
6728 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729 if (mController != null) {
6730 final long token = proto.start(CONTROLLER);
6731 proto.write(CONTROLLER, mController.toString());
6732 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6733 proto.end(token);
6734 }
6735 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6736 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6737 }
6738
6739 if (mHomeProcess != null && (dumpPackage == null
6740 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006741 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006742 }
6743
6744 if (mPreviousProcess != null && (dumpPackage == null
6745 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006746 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006747 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6748 }
6749
6750 if (mHeavyWeightProcess != null && (dumpPackage == null
6751 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006752 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006753 }
6754
6755 for (Map.Entry<String, Integer> entry
6756 : mCompatModePackages.getPackages().entrySet()) {
6757 String pkg = entry.getKey();
6758 int mode = entry.getValue();
6759 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6760 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6761 proto.write(PACKAGE, pkg);
6762 proto.write(MODE, mode);
6763 proto.end(compatToken);
6764 }
6765 }
6766
6767 if (mCurAppTimeTracker != null) {
6768 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6769 }
6770
6771 }
6772 }
6773
6774 @Override
6775 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6776 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6777 boolean dumpFocusedStackOnly) {
6778 synchronized (mGlobalLock) {
6779 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6780 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6781 }
6782 }
6783
6784 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006785 public void dumpForOom(PrintWriter pw) {
6786 synchronized (mGlobalLock) {
6787 pw.println(" mHomeProcess: " + mHomeProcess);
6788 pw.println(" mPreviousProcess: " + mPreviousProcess);
6789 if (mHeavyWeightProcess != null) {
6790 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6791 }
6792 }
6793 }
6794
6795 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 public boolean canGcNow() {
6797 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006798 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 }
6800 }
6801
6802 @Override
6803 public WindowProcessController getTopApp() {
6804 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006805 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 return top != null ? top.app : null;
6807 }
6808 }
6809
6810 @Override
6811 public void rankTaskLayersIfNeeded() {
6812 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006813 if (mRootActivityContainer != null) {
6814 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815 }
6816 }
6817 }
6818
6819 @Override
6820 public void scheduleDestroyAllActivities(String reason) {
6821 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006822 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 }
6824 }
6825
6826 @Override
6827 public void removeUser(int userId) {
6828 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006829 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 }
6831 }
6832
6833 @Override
6834 public boolean switchUser(int userId, UserState userState) {
6835 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006836 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 }
6838 }
6839
6840 @Override
6841 public void onHandleAppCrash(WindowProcessController wpc) {
6842 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006843 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006844 }
6845 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006846
6847 @Override
6848 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6849 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006850 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006851 }
6852 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006853
6854 @Override
6855 public void onUidActive(int uid, int procState) {
6856 synchronized (mGlobalLock) {
6857 mActiveUids.put(uid, procState);
6858 }
6859 }
6860
6861 @Override
6862 public void onUidInactive(int uid) {
6863 synchronized (mGlobalLock) {
6864 mActiveUids.remove(uid);
6865 }
6866 }
6867
6868 @Override
6869 public void onActiveUidsCleared() {
6870 synchronized (mGlobalLock) {
6871 mActiveUids.clear();
6872 }
6873 }
6874
6875 @Override
6876 public void onUidProcStateChanged(int uid, int procState) {
6877 synchronized (mGlobalLock) {
6878 if (mActiveUids.get(uid) != null) {
6879 mActiveUids.put(uid, procState);
6880 }
6881 }
6882 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006883
6884 @Override
6885 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6886 synchronized (mGlobalLock) {
6887 mPendingTempWhitelist.put(uid, tag);
6888 }
6889 }
6890
6891 @Override
6892 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6893 synchronized (mGlobalLock) {
6894 mPendingTempWhitelist.remove(uid);
6895 }
6896 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006897
6898 @Override
6899 public boolean handleAppCrashInActivityController(String processName, int pid,
6900 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6901 Runnable killCrashingAppCallback) {
6902 synchronized (mGlobalLock) {
6903 if (mController == null) {
6904 return false;
6905 }
6906
6907 try {
6908 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6909 stackTrace)) {
6910 killCrashingAppCallback.run();
6911 return true;
6912 }
6913 } catch (RemoteException e) {
6914 mController = null;
6915 Watchdog.getInstance().setActivityController(null);
6916 }
6917 return false;
6918 }
6919 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006920
6921 @Override
6922 public void removeRecentTasksByPackageName(String packageName, int userId) {
6923 synchronized (mGlobalLock) {
6924 mRecentTasks.removeTasksByPackageName(packageName, userId);
6925 }
6926 }
6927
6928 @Override
6929 public void cleanupRecentTasksForUser(int userId) {
6930 synchronized (mGlobalLock) {
6931 mRecentTasks.cleanupLocked(userId);
6932 }
6933 }
6934
6935 @Override
6936 public void loadRecentTasksForUser(int userId) {
6937 synchronized (mGlobalLock) {
6938 mRecentTasks.loadUserRecentsLocked(userId);
6939 }
6940 }
6941
6942 @Override
6943 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6944 synchronized (mGlobalLock) {
6945 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6946 }
6947 }
6948
6949 @Override
6950 public void flushRecentTasks() {
6951 mRecentTasks.flush();
6952 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006953
6954 @Override
6955 public WindowProcessController getHomeProcess() {
6956 synchronized (mGlobalLock) {
6957 return mHomeProcess;
6958 }
6959 }
6960
6961 @Override
6962 public WindowProcessController getPreviousProcess() {
6963 synchronized (mGlobalLock) {
6964 return mPreviousProcess;
6965 }
6966 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006967
6968 @Override
6969 public void clearLockedTasks(String reason) {
6970 synchronized (mGlobalLock) {
6971 getLockTaskController().clearLockedTasks(reason);
6972 }
6973 }
6974
6975 @Override
6976 public void updateUserConfiguration() {
6977 synchronized (mGlobalLock) {
6978 final Configuration configuration = new Configuration(getGlobalConfiguration());
6979 final int currentUserId = mAmInternal.getCurrentUserId();
6980 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6981 configuration, currentUserId, Settings.System.canWrite(mContext));
6982 updateConfigurationLocked(configuration, null /* starting */,
6983 false /* initLocale */, false /* persistent */, currentUserId,
6984 false /* deferResume */);
6985 }
6986 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006987
6988 @Override
6989 public boolean canShowErrorDialogs() {
6990 synchronized (mGlobalLock) {
6991 return mShowDialogs && !mSleeping && !mShuttingDown
6992 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6993 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6994 mAmInternal.getCurrentUserId())
6995 && !(UserManager.isDeviceInDemoMode(mContext)
6996 && mAmInternal.getCurrentUser().isDemo());
6997 }
6998 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006999
7000 @Override
7001 public void setProfileApp(String profileApp) {
7002 synchronized (mGlobalLock) {
7003 mProfileApp = profileApp;
7004 }
7005 }
7006
7007 @Override
7008 public void setProfileProc(WindowProcessController wpc) {
7009 synchronized (mGlobalLock) {
7010 mProfileProc = wpc;
7011 }
7012 }
7013
7014 @Override
7015 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7016 synchronized (mGlobalLock) {
7017 mProfilerInfo = profilerInfo;
7018 }
7019 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007020
7021 @Override
7022 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7023 synchronized (mGlobalLock) {
7024 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7025 }
7026 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007027
7028 @Override
7029 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7030 synchronized (mGlobalLock) {
7031 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7032 }
7033 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007034 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007035}