blob: 486a4ea24f65ed450a4d62cef5d9f9dab355e27e [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700196import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700197import android.os.SystemClock;
198import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.UserManager;
203import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700204import android.os.storage.IStorageManager;
205import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.provider.Settings;
207import android.service.voice.IVoiceInteractionSession;
208import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900209import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.telecom.TelecomManager;
211import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700212import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700213import android.util.ArrayMap;
214import android.util.EventLog;
215import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700216import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700218import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700220import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700221import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700222import android.view.IRecentsAnimationRunner;
223import android.view.RemoteAnimationAdapter;
224import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700225import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700226
Evan Rosky4505b352018-09-06 11:20:40 -0700227import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700228import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700229import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700232import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700235import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
236import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700237import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700238import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.policy.IKeyguardDismissCallback;
240import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.util.ArrayUtils;
242import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700243import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700244import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700245import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.server.LocalServices;
247import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700248import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800249import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700251import com.android.server.am.ActivityManagerService;
252import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
253import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
254import com.android.server.am.AppTimeTracker;
255import com.android.server.am.BaseErrorDialog;
256import com.android.server.am.EventLogTags;
257import com.android.server.am.PendingIntentController;
258import com.android.server.am.PendingIntentRecord;
259import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900260import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700261import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700262import com.android.server.pm.UserManagerService;
263import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700264import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700265
Wale Ogunwale31913b52018-10-13 08:29:31 -0700266import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700268import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700269import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700271import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700272import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700273import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800274import java.lang.annotation.ElementType;
275import java.lang.annotation.Retention;
276import java.lang.annotation.RetentionPolicy;
277import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700278import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700280import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700281import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400283import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700286import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Map;
288import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289
290/**
291 * System service for managing activities and their containers (task, stacks, displays,... ).
292 *
293 * {@hide}
294 */
295public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700296 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700298 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
299 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
300 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
301 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
302 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700303 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700304
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700306 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700308 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309
Wale Ogunwale98875612018-10-12 07:53:02 -0700310 /** Used to indicate that an app transition should be animated. */
311 static final boolean ANIMATE = true;
312
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700313 /** Hardware-reported OpenGLES version. */
314 final int GL_ES_VERSION;
315
Wale Ogunwale31913b52018-10-13 08:29:31 -0700316 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
317 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
318 public static final String DUMP_LASTANR_CMD = "lastanr" ;
319 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
320 public static final String DUMP_STARTER_CMD = "starter" ;
321 public static final String DUMP_CONTAINERS_CMD = "containers" ;
322 public static final String DUMP_RECENTS_CMD = "recents" ;
323 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
324
Wale Ogunwale64258362018-10-16 15:13:37 -0700325 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
326 public static final int RELAUNCH_REASON_NONE = 0;
327 /** This activity is being relaunched due to windowing mode change. */
328 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
329 /** This activity is being relaunched due to a free-resize operation. */
330 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
331
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700332 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700333
Wale Ogunwalef6733932018-06-27 05:14:34 -0700334 /**
335 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
336 * change at runtime. Use mContext for non-UI purposes.
337 */
338 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700339 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700340 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700342 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700343 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700344 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800345 @VisibleForTesting
346 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 PowerManagerInternal mPowerManagerInternal;
348 private UsageStatsManagerInternal mUsageStatsInternal;
349
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700350 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 IntentFirewall mIntentFirewall;
352
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700353 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800354 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800355 /**
356 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
357 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
358 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
359 *
360 * @see WindowManagerThreadPriorityBooster
361 */
362 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700363 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800364 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700365 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700366 private UserManagerService mUserManager;
367 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700368 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800369 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700370 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700371 /** All processes currently running that might have a window organized by name. */
372 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700373 /** All processes we currently have running mapped by pid */
374 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700375 /** This is the process holding what we currently consider to be the "home" activity. */
376 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700377 /** The currently running heavy-weight process, if any. */
378 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700379 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /**
381 * This is the process holding the activity the user last visited that is in a different process
382 * from the one they are currently in.
383 */
384 WindowProcessController mPreviousProcess;
385 /** The time at which the previous process was last visible. */
386 long mPreviousProcessVisibleTime;
387
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700388 /** List of intents that were used to start the most recent tasks. */
389 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700390 /** State of external calls telling us if the device is awake or asleep. */
391 private boolean mKeyguardShown = false;
392
393 // Wrapper around VoiceInteractionServiceManager
394 private AssistUtils mAssistUtils;
395
396 // VoiceInteraction session ID that changes for each new request except when
397 // being called for multi-window assist in a single session.
398 private int mViSessionId = 1000;
399
400 // How long to wait in getAssistContextExtras for the activity and foreground services
401 // to respond with the result.
402 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
403
404 // How long top wait when going through the modern assist (which doesn't need to block
405 // on getting this result before starting to launch its UI).
406 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
407
408 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
409 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
410
Alison Cichowlas3e340502018-08-07 17:15:01 -0400411 // Permission tokens are used to temporarily granted a trusted app the ability to call
412 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
413 // showing any appropriate error messages to the user.
414 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
415 10 * MINUTE_IN_MILLIS;
416
417 // How long before the service actually expires a token. This is slightly longer than
418 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
419 // expiration exception.
420 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
421 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
422
423 // How long the service will remember expired tokens, for the purpose of providing error
424 // messaging when a client uses an expired token.
425 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
426 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
427
428 // Activity tokens of system activities that are delegating their call to
429 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
430 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
431
432 // Permission tokens that have expired, but we remember for error reporting.
433 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
434
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700435 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
436
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700437 // Keeps track of the active voice interaction service component, notified from
438 // VoiceInteractionManagerService
439 ComponentName mActiveVoiceInteractionServiceComponent;
440
Wale Ogunwalee2172292018-10-25 10:11:10 -0700441 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700442 KeyguardController mKeyguardController;
443 private final ClientLifecycleManager mLifecycleManager;
444 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700445 /** The controller for all operations related to locktask. */
446 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700447 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 boolean mSuppressResizeConfigChanges;
450
451 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
452 new UpdateConfigurationResult();
453
454 static final class UpdateConfigurationResult {
455 // Configuration changes that were updated.
456 int changes;
457 // If the activity was relaunched to match the new configuration.
458 boolean activityRelaunched;
459
460 void reset() {
461 changes = 0;
462 activityRelaunched = false;
463 }
464 }
465
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700466 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700467 private int mConfigurationSeq;
468 // To cache the list of supported system locales
469 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700470
471 /**
472 * Temp object used when global and/or display override configuration is updated. It is also
473 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
474 * anyone...
475 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700476 private Configuration mTempConfig = new Configuration();
477
Wale Ogunwalef6733932018-06-27 05:14:34 -0700478 /** Temporary to avoid allocations. */
479 final StringBuilder mStringBuilder = new StringBuilder(256);
480
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 // Amount of time after a call to stopAppSwitches() during which we will
482 // prevent further untrusted switches from happening.
483 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
484
485 /**
486 * The time at which we will allow normal application switches again,
487 * after a call to {@link #stopAppSwitches()}.
488 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 /**
491 * This is set to true after the first switch after mAppSwitchesAllowedTime
492 * is set; any switches after that will clear the time.
493 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495
496 IActivityController mController = null;
497 boolean mControllerIsAMonkey = false;
498
Wale Ogunwale214f3482018-10-04 11:00:47 -0700499 final int mFactoryTest;
500
501 /** Used to control how we initialize the service. */
502 ComponentName mTopComponent;
503 String mTopAction = Intent.ACTION_MAIN;
504 String mTopData;
505
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800506 /** Profiling app information. */
507 String mProfileApp = null;
508 WindowProcessController mProfileProc = null;
509 ProfilerInfo mProfilerInfo = null;
510
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700512 * Dump of the activity state at the time of the last ANR. Cleared after
513 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
514 */
515 String mLastANRState;
516
517 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 * Used to retain an update lock when the foreground activity is in
519 * immersive mode.
520 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700521 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522
523 /**
524 * Packages that are being allowed to perform unrestricted app switches. Mapping is
525 * User -> Type -> uid.
526 */
527 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
528
529 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700530 private int mThumbnailWidth;
531 private int mThumbnailHeight;
532 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533
534 /**
535 * Flag that indicates if multi-window is enabled.
536 *
537 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
538 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
539 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
540 * At least one of the forms of multi-window must be enabled in order for this flag to be
541 * initialized to 'true'.
542 *
543 * @see #mSupportsSplitScreenMultiWindow
544 * @see #mSupportsFreeformWindowManagement
545 * @see #mSupportsPictureInPicture
546 * @see #mSupportsMultiDisplay
547 */
548 boolean mSupportsMultiWindow;
549 boolean mSupportsSplitScreenMultiWindow;
550 boolean mSupportsFreeformWindowManagement;
551 boolean mSupportsPictureInPicture;
552 boolean mSupportsMultiDisplay;
553 boolean mForceResizableActivities;
554
555 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
556
557 // VR Vr2d Display Id.
558 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700559
Wale Ogunwalef6733932018-06-27 05:14:34 -0700560 /**
561 * Set while we are wanting to sleep, to prevent any
562 * activities from being started/resumed.
563 *
564 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
565 *
566 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
567 * while in the sleep state until there is a pending transition out of sleep, in which case
568 * mSleeping is set to false, and remains false while awake.
569 *
570 * Whether mSleeping can quickly toggled between true/false without the device actually
571 * display changing states is undefined.
572 */
573 private boolean mSleeping = false;
574
575 /**
576 * The process state used for processes that are running the top activities.
577 * This changes between TOP and TOP_SLEEPING to following mSleeping.
578 */
579 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
580
581 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
582 // automatically. Important for devices without direct input devices.
583 private boolean mShowDialogs = true;
584
585 /** Set if we are shutting down the system, similar to sleeping. */
586 boolean mShuttingDown = false;
587
588 /**
589 * We want to hold a wake lock while running a voice interaction session, since
590 * this may happen with the screen off and we need to keep the CPU running to
591 * be able to continue to interact with the user.
592 */
593 PowerManager.WakeLock mVoiceWakeLock;
594
595 /**
596 * Set while we are running a voice interaction. This overrides sleeping while it is active.
597 */
598 IVoiceInteractionSession mRunningVoice;
599
600 /**
601 * The last resumed activity. This is identical to the current resumed activity most
602 * of the time but could be different when we're pausing one activity before we resume
603 * another activity.
604 */
605 ActivityRecord mLastResumedActivity;
606
607 /**
608 * The activity that is currently being traced as the active resumed activity.
609 *
610 * @see #updateResumedAppTrace
611 */
612 private @Nullable ActivityRecord mTracedResumedActivity;
613
614 /** If non-null, we are tracking the time the user spends in the currently focused app. */
615 AppTimeTracker mCurAppTimeTracker;
616
Wale Ogunwale008163e2018-07-23 23:11:08 -0700617 private AppWarnings mAppWarnings;
618
Wale Ogunwale53783742018-09-16 10:21:51 -0700619 /**
620 * Packages that the user has asked to have run in screen size
621 * compatibility mode instead of filling the screen.
622 */
623 CompatModePackages mCompatModePackages;
624
Wale Ogunwalef6733932018-06-27 05:14:34 -0700625 private FontScaleSettingObserver mFontScaleSettingObserver;
626
Michal Karpinski4026cae2019-02-12 11:51:47 +0000627 private String mDeviceOwnerPackageName;
628
Wale Ogunwalef6733932018-06-27 05:14:34 -0700629 private final class FontScaleSettingObserver extends ContentObserver {
630 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
631 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
632
633 public FontScaleSettingObserver() {
634 super(mH);
635 final ContentResolver resolver = mContext.getContentResolver();
636 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
637 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
638 UserHandle.USER_ALL);
639 }
640
641 @Override
642 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
643 if (mFontScaleUri.equals(uri)) {
644 updateFontScaleIfNeeded(userId);
645 } else if (mHideErrorDialogsUri.equals(uri)) {
646 synchronized (mGlobalLock) {
647 updateShouldShowDialogsLocked(getGlobalConfiguration());
648 }
649 }
650 }
651 }
652
Riddle Hsua0536432019-02-16 00:38:59 +0800653 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
654 @Target(ElementType.METHOD)
655 @Retention(RetentionPolicy.SOURCE)
656 @interface HotPath {
657 int NONE = 0;
658 int OOM_ADJUSTMENT = 1;
659 int LRU_UPDATE = 2;
660 int PROCESS_CHANGE = 3;
661 int caller() default NONE;
662 }
663
Charles Chen8d98dd22018-12-26 17:36:54 +0800664 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
665 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700666 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700667 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700668 mSystemThread = ActivityThread.currentActivityThread();
669 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700670 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800671 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700672 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700673 }
674
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700675 public void onSystemReady() {
676 synchronized (mGlobalLock) {
677 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
678 PackageManager.FEATURE_CANT_SAVE_STATE);
679 mAssistUtils = new AssistUtils(mContext);
680 mVrController.onSystemReady();
681 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700682 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700683 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700684 }
685
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700686 public void onInitPowerManagement() {
687 synchronized (mGlobalLock) {
688 mStackSupervisor.initPowerManagement();
689 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
690 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
691 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
692 mVoiceWakeLock.setReferenceCounted(false);
693 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700694 }
695
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700696 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700697 mFontScaleSettingObserver = new FontScaleSettingObserver();
698 }
699
Wale Ogunwale59507092018-10-29 09:00:30 -0700700 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700701 final boolean freeformWindowManagement =
702 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
703 || Settings.Global.getInt(
704 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
705
706 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
707 final boolean supportsPictureInPicture = supportsMultiWindow &&
708 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
709 final boolean supportsSplitScreenMultiWindow =
710 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
711 final boolean supportsMultiDisplay = mContext.getPackageManager()
712 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700713 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
714 final boolean forceResizable = Settings.Global.getInt(
715 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700716 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700717
718 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900719 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700720
721 final Configuration configuration = new Configuration();
722 Settings.System.getConfiguration(resolver, configuration);
723 if (forceRtl) {
724 // This will take care of setting the correct layout direction flags
725 configuration.setLayoutDirection(configuration.locale);
726 }
727
728 synchronized (mGlobalLock) {
729 mForceResizableActivities = forceResizable;
730 final boolean multiWindowFormEnabled = freeformWindowManagement
731 || supportsSplitScreenMultiWindow
732 || supportsPictureInPicture
733 || supportsMultiDisplay;
734 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
735 mSupportsMultiWindow = true;
736 mSupportsFreeformWindowManagement = freeformWindowManagement;
737 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
738 mSupportsPictureInPicture = supportsPictureInPicture;
739 mSupportsMultiDisplay = supportsMultiDisplay;
740 } else {
741 mSupportsMultiWindow = false;
742 mSupportsFreeformWindowManagement = false;
743 mSupportsSplitScreenMultiWindow = false;
744 mSupportsPictureInPicture = false;
745 mSupportsMultiDisplay = false;
746 }
747 mWindowManager.setForceResizableTasks(mForceResizableActivities);
748 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700749 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
750 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700751 // This happens before any activities are started, so we can change global configuration
752 // in-place.
753 updateConfigurationLocked(configuration, null, true);
754 final Configuration globalConfig = getGlobalConfiguration();
755 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
756
757 // Load resources only after the current configuration has been set.
758 final Resources res = mContext.getResources();
759 mThumbnailWidth = res.getDimensionPixelSize(
760 com.android.internal.R.dimen.thumbnail_width);
761 mThumbnailHeight = res.getDimensionPixelSize(
762 com.android.internal.R.dimen.thumbnail_height);
763
764 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
765 mFullscreenThumbnailScale = (float) res
766 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
767 (float) globalConfig.screenWidthDp;
768 } else {
769 mFullscreenThumbnailScale = res.getFraction(
770 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
771 }
772 }
773 }
774
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800775 public WindowManagerGlobalLock getGlobalLock() {
776 return mGlobalLock;
777 }
778
Riddle Hsud93a6c42018-11-29 21:50:06 +0800779 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
780 Looper looper) {
781 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700782 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700783 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700784 final File systemDir = SystemServiceManager.ensureSystemDir();
785 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
786 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700787 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700788
789 mTempConfig.setToDefaults();
790 mTempConfig.setLocales(LocaleList.getDefault());
791 mConfigurationSeq = mTempConfig.seq = 1;
792 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800793 mRootActivityContainer = new RootActivityContainer(this);
794 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700795
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700796 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700797 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700798 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700799 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700800 mRecentTasks = createRecentTasks();
801 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700802 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700803 mKeyguardController = mStackSupervisor.getKeyguardController();
804 }
805
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700806 public void onActivityManagerInternalAdded() {
807 synchronized (mGlobalLock) {
808 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
809 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
810 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700811 }
812
Yunfan Chen75157d72018-07-27 14:47:21 +0900813 int increaseConfigurationSeqLocked() {
814 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
815 return mConfigurationSeq;
816 }
817
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818 protected ActivityStackSupervisor createStackSupervisor() {
819 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
820 supervisor.initialize();
821 return supervisor;
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void setWindowManager(WindowManagerService wm) {
825 synchronized (mGlobalLock) {
826 mWindowManager = wm;
827 mLockTaskController.setWindowManager(wm);
828 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800829 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700830 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700831 }
832
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700833 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
834 synchronized (mGlobalLock) {
835 mUsageStatsInternal = usageStatsManager;
836 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700837 }
838
Wale Ogunwalef6733932018-06-27 05:14:34 -0700839 UserManagerService getUserManager() {
840 if (mUserManager == null) {
841 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
842 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
843 }
844 return mUserManager;
845 }
846
847 AppOpsService getAppOpsService() {
848 if (mAppOpsService == null) {
849 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
850 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
851 }
852 return mAppOpsService;
853 }
854
855 boolean hasUserRestriction(String restriction, int userId) {
856 return getUserManager().hasUserRestriction(restriction, userId);
857 }
858
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700859 protected RecentTasks createRecentTasks() {
860 return new RecentTasks(this, mStackSupervisor);
861 }
862
863 RecentTasks getRecentTasks() {
864 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700865 }
866
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700867 ClientLifecycleManager getLifecycleManager() {
868 return mLifecycleManager;
869 }
870
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700871 ActivityStartController getActivityStartController() {
872 return mActivityStartController;
873 }
874
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700875 TaskChangeNotificationController getTaskChangeNotificationController() {
876 return mTaskChangeNotificationController;
877 }
878
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700879 LockTaskController getLockTaskController() {
880 return mLockTaskController;
881 }
882
Yunfan Chen75157d72018-07-27 14:47:21 +0900883 /**
884 * Return the global configuration used by the process corresponding to the input pid. This is
885 * usually the global configuration with some overrides specific to that process.
886 */
887 Configuration getGlobalConfigurationForCallingPid() {
888 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800889 return getGlobalConfigurationForPid(pid);
890 }
891
892 /**
893 * Return the global configuration used by the process corresponding to the given pid.
894 */
895 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900896 if (pid == MY_PID || pid < 0) {
897 return getGlobalConfiguration();
898 }
899 synchronized (mGlobalLock) {
900 final WindowProcessController app = mPidMap.get(pid);
901 return app != null ? app.getConfiguration() : getGlobalConfiguration();
902 }
903 }
904
905 /**
906 * Return the device configuration info used by the process corresponding to the input pid.
907 * The value is consistent with the global configuration for the process.
908 */
909 @Override
910 public ConfigurationInfo getDeviceConfigurationInfo() {
911 ConfigurationInfo config = new ConfigurationInfo();
912 synchronized (mGlobalLock) {
913 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
914 config.reqTouchScreen = globalConfig.touchscreen;
915 config.reqKeyboardType = globalConfig.keyboard;
916 config.reqNavigation = globalConfig.navigation;
917 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
918 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
919 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
920 }
921 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
922 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
923 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
924 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700925 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900926 }
927 return config;
928 }
929
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700930 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700931 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700932 }
933
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700934 public static final class Lifecycle extends SystemService {
935 private final ActivityTaskManagerService mService;
936
937 public Lifecycle(Context context) {
938 super(context);
939 mService = new ActivityTaskManagerService(context);
940 }
941
942 @Override
943 public void onStart() {
944 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700945 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700946 }
947
Garfield Tan891146c2018-10-09 12:14:00 -0700948 @Override
949 public void onUnlockUser(int userId) {
950 synchronized (mService.getGlobalLock()) {
951 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
952 }
953 }
954
955 @Override
956 public void onCleanupUser(int userId) {
957 synchronized (mService.getGlobalLock()) {
958 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
959 }
960 }
961
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700962 public ActivityTaskManagerService getService() {
963 return mService;
964 }
965 }
966
967 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700968 public final int startActivity(IApplicationThread caller, String callingPackage,
969 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
970 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
971 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
972 resultWho, requestCode, startFlags, profilerInfo, bOptions,
973 UserHandle.getCallingUserId());
974 }
975
976 @Override
977 public final int startActivities(IApplicationThread caller, String callingPackage,
978 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
979 int userId) {
980 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700981 enforceNotIsolatedCaller(reason);
982 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700983 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000984 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
985 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
986 reason, null /* originatingPendingIntent */,
987 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700988 }
989
990 @Override
991 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
992 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
993 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
994 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
995 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
996 true /*validateIncomingUser*/);
997 }
998
999 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1000 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1001 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1002 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001003 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001005 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001006 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1007
1008 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001009 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001010 .setCaller(caller)
1011 .setCallingPackage(callingPackage)
1012 .setResolvedType(resolvedType)
1013 .setResultTo(resultTo)
1014 .setResultWho(resultWho)
1015 .setRequestCode(requestCode)
1016 .setStartFlags(startFlags)
1017 .setProfilerInfo(profilerInfo)
1018 .setActivityOptions(bOptions)
1019 .setMayWait(userId)
1020 .execute();
1021
1022 }
1023
1024 @Override
1025 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1026 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001027 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1028 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 // Refuse possible leaked file descriptors
1030 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1031 throw new IllegalArgumentException("File descriptors passed in Intent");
1032 }
1033
1034 if (!(target instanceof PendingIntentRecord)) {
1035 throw new IllegalArgumentException("Bad PendingIntent object");
1036 }
1037
1038 PendingIntentRecord pir = (PendingIntentRecord)target;
1039
1040 synchronized (mGlobalLock) {
1041 // If this is coming from the currently resumed activity, it is
1042 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001043 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 if (stack.mResumedActivity != null &&
1045 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001046 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 }
1048 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001049 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051 }
1052
1053 @Override
1054 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1055 Bundle bOptions) {
1056 // Refuse possible leaked file descriptors
1057 if (intent != null && intent.hasFileDescriptors()) {
1058 throw new IllegalArgumentException("File descriptors passed in Intent");
1059 }
1060 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1061
1062 synchronized (mGlobalLock) {
1063 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1064 if (r == null) {
1065 SafeActivityOptions.abort(options);
1066 return false;
1067 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001068 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 // The caller is not running... d'oh!
1070 SafeActivityOptions.abort(options);
1071 return false;
1072 }
1073 intent = new Intent(intent);
1074 // The caller is not allowed to change the data.
1075 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1076 // And we are resetting to find the next component...
1077 intent.setComponent(null);
1078
1079 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1080
1081 ActivityInfo aInfo = null;
1082 try {
1083 List<ResolveInfo> resolves =
1084 AppGlobals.getPackageManager().queryIntentActivities(
1085 intent, r.resolvedType,
1086 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1087 UserHandle.getCallingUserId()).getList();
1088
1089 // Look for the original activity in the list...
1090 final int N = resolves != null ? resolves.size() : 0;
1091 for (int i=0; i<N; i++) {
1092 ResolveInfo rInfo = resolves.get(i);
1093 if (rInfo.activityInfo.packageName.equals(r.packageName)
1094 && rInfo.activityInfo.name.equals(r.info.name)) {
1095 // We found the current one... the next matching is
1096 // after it.
1097 i++;
1098 if (i<N) {
1099 aInfo = resolves.get(i).activityInfo;
1100 }
1101 if (debug) {
1102 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1103 + "/" + r.info.name);
1104 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1105 ? "null" : aInfo.packageName + "/" + aInfo.name));
1106 }
1107 break;
1108 }
1109 }
1110 } catch (RemoteException e) {
1111 }
1112
1113 if (aInfo == null) {
1114 // Nobody who is next!
1115 SafeActivityOptions.abort(options);
1116 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1117 return false;
1118 }
1119
1120 intent.setComponent(new ComponentName(
1121 aInfo.applicationInfo.packageName, aInfo.name));
1122 intent.setFlags(intent.getFlags()&~(
1123 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1124 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1125 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1126 FLAG_ACTIVITY_NEW_TASK));
1127
1128 // Okay now we need to start the new activity, replacing the currently running activity.
1129 // This is a little tricky because we want to start the new one as if the current one is
1130 // finished, but not finish the current one first so that there is no flicker.
1131 // And thus...
1132 final boolean wasFinishing = r.finishing;
1133 r.finishing = true;
1134
1135 // Propagate reply information over to the new activity.
1136 final ActivityRecord resultTo = r.resultTo;
1137 final String resultWho = r.resultWho;
1138 final int requestCode = r.requestCode;
1139 r.resultTo = null;
1140 if (resultTo != null) {
1141 resultTo.removeResultsLocked(r, resultWho, requestCode);
1142 }
1143
1144 final long origId = Binder.clearCallingIdentity();
1145 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001146 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001147 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001148 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001149 .setResolvedType(r.resolvedType)
1150 .setActivityInfo(aInfo)
1151 .setResultTo(resultTo != null ? resultTo.appToken : null)
1152 .setResultWho(resultWho)
1153 .setRequestCode(requestCode)
1154 .setCallingPid(-1)
1155 .setCallingUid(r.launchedFromUid)
1156 .setCallingPackage(r.launchedFromPackage)
1157 .setRealCallingPid(-1)
1158 .setRealCallingUid(r.launchedFromUid)
1159 .setActivityOptions(options)
1160 .execute();
1161 Binder.restoreCallingIdentity(origId);
1162
1163 r.finishing = wasFinishing;
1164 if (res != ActivityManager.START_SUCCESS) {
1165 return false;
1166 }
1167 return true;
1168 }
1169 }
1170
1171 @Override
1172 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1173 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1174 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1175 final WaitResult res = new WaitResult();
1176 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001177 enforceNotIsolatedCaller("startActivityAndWait");
1178 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1179 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001180 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001181 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 .setCaller(caller)
1183 .setCallingPackage(callingPackage)
1184 .setResolvedType(resolvedType)
1185 .setResultTo(resultTo)
1186 .setResultWho(resultWho)
1187 .setRequestCode(requestCode)
1188 .setStartFlags(startFlags)
1189 .setActivityOptions(bOptions)
1190 .setMayWait(userId)
1191 .setProfilerInfo(profilerInfo)
1192 .setWaitResult(res)
1193 .execute();
1194 }
1195 return res;
1196 }
1197
1198 @Override
1199 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1200 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1201 int startFlags, Configuration config, Bundle bOptions, int userId) {
1202 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001203 enforceNotIsolatedCaller("startActivityWithConfig");
1204 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1205 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001206 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001207 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 .setCaller(caller)
1209 .setCallingPackage(callingPackage)
1210 .setResolvedType(resolvedType)
1211 .setResultTo(resultTo)
1212 .setResultWho(resultWho)
1213 .setRequestCode(requestCode)
1214 .setStartFlags(startFlags)
1215 .setGlobalConfiguration(config)
1216 .setActivityOptions(bOptions)
1217 .setMayWait(userId)
1218 .execute();
1219 }
1220 }
1221
Alison Cichowlas3e340502018-08-07 17:15:01 -04001222
1223 @Override
1224 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1225 int callingUid = Binder.getCallingUid();
1226 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1227 throw new SecurityException("Only the system process can request a permission token, "
1228 + "received request from uid: " + callingUid);
1229 }
1230 IBinder permissionToken = new Binder();
1231 synchronized (mGlobalLock) {
1232 mStartActivitySources.put(permissionToken, delegatorToken);
1233 }
1234
1235 Message expireMsg = PooledLambda.obtainMessage(
1236 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1237 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1238
1239 Message forgetMsg = PooledLambda.obtainMessage(
1240 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1241 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1242
1243 return permissionToken;
1244 }
1245
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001246 @Override
1247 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1248 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001249 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1250 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001251 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001252 // permission grants) as any app that may launch one of your own activities. So we only
1253 // allow this in two cases:
1254 // 1) The caller is an activity that is part of the core framework, and then only when it
1255 // is running as the system.
1256 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1257 // can only be requested by a system activity, which may then delegate this call to
1258 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001259 final ActivityRecord sourceRecord;
1260 final int targetUid;
1261 final String targetPackage;
1262 final boolean isResolver;
1263 synchronized (mGlobalLock) {
1264 if (resultTo == null) {
1265 throw new SecurityException("Must be called from an activity");
1266 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267 final IBinder sourceToken;
1268 if (permissionToken != null) {
1269 // To even attempt to use a permissionToken, an app must also have this signature
1270 // permission.
1271 mAmInternal.enforceCallingPermission(
1272 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1273 "startActivityAsCaller");
1274 // If called with a permissionToken, we want the sourceRecord from the delegator
1275 // activity that requested this token.
1276 sourceToken = mStartActivitySources.remove(permissionToken);
1277 if (sourceToken == null) {
1278 // Invalid permissionToken, check if it recently expired.
1279 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1280 throw new SecurityException("Called with expired permission token: "
1281 + permissionToken);
1282 } else {
1283 throw new SecurityException("Called with invalid permission token: "
1284 + permissionToken);
1285 }
1286 }
1287 } else {
1288 // This method was called directly by the source.
1289 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001290 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001291
Wale Ogunwaled32da472018-11-16 07:19:28 -08001292 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001293 if (sourceRecord == null) {
1294 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001295 }
1296 if (sourceRecord.app == null) {
1297 throw new SecurityException("Called without a process attached to activity");
1298 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299
1300 // Whether called directly or from a delegate, the source activity must be from the
1301 // android package.
1302 if (!sourceRecord.info.packageName.equals("android")) {
1303 throw new SecurityException("Must be called from an activity that is "
1304 + "declared in the android package");
1305 }
1306
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001307 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001308 // This is still okay, as long as this activity is running under the
1309 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001310 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001312 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001313 + " must be system uid or original calling uid "
1314 + sourceRecord.launchedFromUid);
1315 }
1316 }
1317 if (ignoreTargetSecurity) {
1318 if (intent.getComponent() == null) {
1319 throw new SecurityException(
1320 "Component must be specified with ignoreTargetSecurity");
1321 }
1322 if (intent.getSelector() != null) {
1323 throw new SecurityException(
1324 "Selector not allowed with ignoreTargetSecurity");
1325 }
1326 }
1327 targetUid = sourceRecord.launchedFromUid;
1328 targetPackage = sourceRecord.launchedFromPackage;
1329 isResolver = sourceRecord.isResolverOrChildActivity();
1330 }
1331
1332 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001333 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001334 }
1335
1336 // TODO: Switch to user app stacks here.
1337 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001338 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 .setCallingUid(targetUid)
1340 .setCallingPackage(targetPackage)
1341 .setResolvedType(resolvedType)
1342 .setResultTo(resultTo)
1343 .setResultWho(resultWho)
1344 .setRequestCode(requestCode)
1345 .setStartFlags(startFlags)
1346 .setActivityOptions(bOptions)
1347 .setMayWait(userId)
1348 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1349 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1350 .execute();
1351 } catch (SecurityException e) {
1352 // XXX need to figure out how to propagate to original app.
1353 // A SecurityException here is generally actually a fault of the original
1354 // calling activity (such as a fairly granting permissions), so propagate it
1355 // back to them.
1356 /*
1357 StringBuilder msg = new StringBuilder();
1358 msg.append("While launching");
1359 msg.append(intent.toString());
1360 msg.append(": ");
1361 msg.append(e.getMessage());
1362 */
1363 throw e;
1364 }
1365 }
1366
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001367 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1368 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1369 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1370 }
1371
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 @Override
1373 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1374 Intent intent, String resolvedType, IVoiceInteractionSession session,
1375 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1376 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001377 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 if (session == null || interactor == null) {
1379 throw new NullPointerException("null session or interactor");
1380 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001381 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001383 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 .setCallingUid(callingUid)
1385 .setCallingPackage(callingPackage)
1386 .setResolvedType(resolvedType)
1387 .setVoiceSession(session)
1388 .setVoiceInteractor(interactor)
1389 .setStartFlags(startFlags)
1390 .setProfilerInfo(profilerInfo)
1391 .setActivityOptions(bOptions)
1392 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001393 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 .execute();
1395 }
1396
1397 @Override
1398 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1399 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1401 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001403 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 .setCallingUid(callingUid)
1405 .setCallingPackage(callingPackage)
1406 .setResolvedType(resolvedType)
1407 .setActivityOptions(bOptions)
1408 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001409 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 .execute();
1411 }
1412
1413 @Override
1414 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1415 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 final int callingPid = Binder.getCallingPid();
1418 final long origId = Binder.clearCallingIdentity();
1419 try {
1420 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001421 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1422 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423
1424 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001425 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1426 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1428 recentsUid, assistDataReceiver);
1429 }
1430 } finally {
1431 Binder.restoreCallingIdentity(origId);
1432 }
1433 }
1434
1435 @Override
1436 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001437 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 "startActivityFromRecents()");
1439
1440 final int callingPid = Binder.getCallingPid();
1441 final int callingUid = Binder.getCallingUid();
1442 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1443 final long origId = Binder.clearCallingIdentity();
1444 try {
1445 synchronized (mGlobalLock) {
1446 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1447 safeOptions);
1448 }
1449 } finally {
1450 Binder.restoreCallingIdentity(origId);
1451 }
1452 }
1453
1454 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001455 * Public API to check if the client is allowed to start an activity on specified display.
1456 *
1457 * If the target display is private or virtual, some restrictions will apply.
1458 *
1459 * @param displayId Target display id.
1460 * @param intent Intent used to launch the activity.
1461 * @param resolvedType The MIME type of the intent.
1462 * @param userId The id of the user for whom the call is made.
1463 * @return {@code true} if a call to start an activity on the target display should succeed and
1464 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1465 */
1466 @Override
1467 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1468 String resolvedType, int userId) {
1469 final int callingUid = Binder.getCallingUid();
1470 final int callingPid = Binder.getCallingPid();
1471 final long origId = Binder.clearCallingIdentity();
1472
1473 try {
1474 // Collect information about the target of the Intent.
1475 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1476 0 /* startFlags */, null /* profilerInfo */, userId,
1477 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1478 UserHandle.USER_NULL));
1479 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1480
1481 synchronized (mGlobalLock) {
1482 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1483 aInfo);
1484 }
1485 } finally {
1486 Binder.restoreCallingIdentity(origId);
1487 }
1488 }
1489
1490 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001491 * This is the internal entry point for handling Activity.finish().
1492 *
1493 * @param token The Binder token referencing the Activity we want to finish.
1494 * @param resultCode Result code, if any, from this Activity.
1495 * @param resultData Result data (Intent), if any, from this Activity.
1496 * @param finishTask Whether to finish the task associated with this Activity.
1497 *
1498 * @return Returns true if the activity successfully finished, or false if it is still running.
1499 */
1500 @Override
1501 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1502 int finishTask) {
1503 // Refuse possible leaked file descriptors
1504 if (resultData != null && resultData.hasFileDescriptors()) {
1505 throw new IllegalArgumentException("File descriptors passed in Intent");
1506 }
1507
1508 synchronized (mGlobalLock) {
1509 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1510 if (r == null) {
1511 return true;
1512 }
1513 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001514 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001515 ActivityRecord rootR = tr.getRootActivity();
1516 if (rootR == null) {
1517 Slog.w(TAG, "Finishing task with all activities already finished");
1518 }
1519 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1520 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001521 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001522 return false;
1523 }
1524
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001525 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1526 // We should consolidate.
1527 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001529 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001530 if (next != null) {
1531 // ask watcher if this is allowed
1532 boolean resumeOK = true;
1533 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001534 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001535 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001536 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001537 Watchdog.getInstance().setActivityController(null);
1538 }
1539
1540 if (!resumeOK) {
1541 Slog.i(TAG, "Not finishing activity because controller resumed");
1542 return false;
1543 }
1544 }
1545 }
1546 final long origId = Binder.clearCallingIdentity();
1547 try {
1548 boolean res;
1549 final boolean finishWithRootActivity =
1550 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1551 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1552 || (finishWithRootActivity && r == rootR)) {
1553 // If requested, remove the task that is associated to this activity only if it
1554 // was the root activity in the task. The result code and data is ignored
1555 // because we don't support returning them across task boundaries. Also, to
1556 // keep backwards compatibility we remove the task from recents when finishing
1557 // task with root activity.
1558 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1559 finishWithRootActivity, "finish-activity");
1560 if (!res) {
1561 Slog.i(TAG, "Removing task failed to finish activity");
1562 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001563 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001564 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 } else {
1566 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1567 resultData, "app-request", true);
1568 if (!res) {
1569 Slog.i(TAG, "Failed to finish by app-request");
1570 }
1571 }
1572 return res;
1573 } finally {
1574 Binder.restoreCallingIdentity(origId);
1575 }
1576 }
1577 }
1578
1579 @Override
1580 public boolean finishActivityAffinity(IBinder token) {
1581 synchronized (mGlobalLock) {
1582 final long origId = Binder.clearCallingIdentity();
1583 try {
1584 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1585 if (r == null) {
1586 return false;
1587 }
1588
1589 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1590 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001591 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001592 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 return false;
1594 }
1595 return task.getStack().finishActivityAffinityLocked(r);
1596 } finally {
1597 Binder.restoreCallingIdentity(origId);
1598 }
1599 }
1600 }
1601
1602 @Override
1603 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1604 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001605 try {
1606 WindowProcessController proc = null;
1607 synchronized (mGlobalLock) {
1608 ActivityStack stack = ActivityRecord.getStackLocked(token);
1609 if (stack == null) {
1610 return;
1611 }
1612 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1613 false /* fromTimeout */, false /* processPausingActivities */, config);
1614 if (r != null) {
1615 proc = r.app;
1616 }
1617 if (stopProfiling && proc != null) {
1618 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 }
1620 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001621 } finally {
1622 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001624 }
1625
1626 @Override
1627 public final void activityResumed(IBinder token) {
1628 final long origId = Binder.clearCallingIdentity();
1629 synchronized (mGlobalLock) {
1630 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001631 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001632 }
1633 Binder.restoreCallingIdentity(origId);
1634 }
1635
1636 @Override
1637 public final void activityPaused(IBinder token) {
1638 final long origId = Binder.clearCallingIdentity();
1639 synchronized (mGlobalLock) {
1640 ActivityStack stack = ActivityRecord.getStackLocked(token);
1641 if (stack != null) {
1642 stack.activityPausedLocked(token, false);
1643 }
1644 }
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647
1648 @Override
1649 public final void activityStopped(IBinder token, Bundle icicle,
1650 PersistableBundle persistentState, CharSequence description) {
1651 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1652
1653 // Refuse possible leaked file descriptors
1654 if (icicle != null && icicle.hasFileDescriptors()) {
1655 throw new IllegalArgumentException("File descriptors passed in Bundle");
1656 }
1657
1658 final long origId = Binder.clearCallingIdentity();
1659
1660 synchronized (mGlobalLock) {
1661 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1662 if (r != null) {
1663 r.activityStoppedLocked(icicle, persistentState, description);
1664 }
1665 }
1666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001667 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001668
1669 Binder.restoreCallingIdentity(origId);
1670 }
1671
1672 @Override
1673 public final void activityDestroyed(IBinder token) {
1674 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1675 synchronized (mGlobalLock) {
1676 ActivityStack stack = ActivityRecord.getStackLocked(token);
1677 if (stack != null) {
1678 stack.activityDestroyedLocked(token, "activityDestroyed");
1679 }
1680 }
1681 }
1682
1683 @Override
1684 public final void activityRelaunched(IBinder token) {
1685 final long origId = Binder.clearCallingIdentity();
1686 synchronized (mGlobalLock) {
1687 mStackSupervisor.activityRelaunchedLocked(token);
1688 }
1689 Binder.restoreCallingIdentity(origId);
1690 }
1691
1692 public final void activitySlept(IBinder token) {
1693 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1694
1695 final long origId = Binder.clearCallingIdentity();
1696
1697 synchronized (mGlobalLock) {
1698 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1699 if (r != null) {
1700 mStackSupervisor.activitySleptLocked(r);
1701 }
1702 }
1703
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706
1707 @Override
1708 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1709 synchronized (mGlobalLock) {
1710 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1711 if (r == null) {
1712 return;
1713 }
1714 final long origId = Binder.clearCallingIdentity();
1715 try {
1716 r.setRequestedOrientation(requestedOrientation);
1717 } finally {
1718 Binder.restoreCallingIdentity(origId);
1719 }
1720 }
1721 }
1722
1723 @Override
1724 public int getRequestedOrientation(IBinder token) {
1725 synchronized (mGlobalLock) {
1726 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1727 if (r == null) {
1728 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1729 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001730 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 }
1732 }
1733
1734 @Override
1735 public void setImmersive(IBinder token, boolean immersive) {
1736 synchronized (mGlobalLock) {
1737 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1738 if (r == null) {
1739 throw new IllegalArgumentException();
1740 }
1741 r.immersive = immersive;
1742
1743 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001744 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001746 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747 }
1748 }
1749 }
1750
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001751 void applyUpdateLockStateLocked(ActivityRecord r) {
1752 // Modifications to the UpdateLock state are done on our handler, outside
1753 // the activity manager's locks. The new state is determined based on the
1754 // state *now* of the relevant activity record. The object is passed to
1755 // the handler solely for logging detail, not to be consulted/modified.
1756 final boolean nextState = r != null && r.immersive;
1757 mH.post(() -> {
1758 if (mUpdateLock.isHeld() != nextState) {
1759 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1760 "Applying new update lock state '" + nextState + "' for " + r);
1761 if (nextState) {
1762 mUpdateLock.acquire();
1763 } else {
1764 mUpdateLock.release();
1765 }
1766 }
1767 });
1768 }
1769
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 @Override
1771 public boolean isImmersive(IBinder token) {
1772 synchronized (mGlobalLock) {
1773 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1774 if (r == null) {
1775 throw new IllegalArgumentException();
1776 }
1777 return r.immersive;
1778 }
1779 }
1780
1781 @Override
1782 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001783 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001784 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001785 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001786 return (r != null) ? r.immersive : false;
1787 }
1788 }
1789
1790 @Override
1791 public void overridePendingTransition(IBinder token, String packageName,
1792 int enterAnim, int exitAnim) {
1793 synchronized (mGlobalLock) {
1794 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1795 if (self == null) {
1796 return;
1797 }
1798
1799 final long origId = Binder.clearCallingIdentity();
1800
1801 if (self.isState(
1802 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001803 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001804 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 }
1806
1807 Binder.restoreCallingIdentity(origId);
1808 }
1809 }
1810
1811 @Override
1812 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001813 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001815 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 if (r == null) {
1817 return ActivityManager.COMPAT_MODE_UNKNOWN;
1818 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001819 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001820 }
1821 }
1822
1823 @Override
1824 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001825 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001827 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001829 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001830 if (r == null) {
1831 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1832 return;
1833 }
1834 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001835 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001836 }
1837 }
1838
1839 @Override
1840 public int getLaunchedFromUid(IBinder activityToken) {
1841 ActivityRecord srec;
1842 synchronized (mGlobalLock) {
1843 srec = ActivityRecord.forTokenLocked(activityToken);
1844 }
1845 if (srec == null) {
1846 return -1;
1847 }
1848 return srec.launchedFromUid;
1849 }
1850
1851 @Override
1852 public String getLaunchedFromPackage(IBinder activityToken) {
1853 ActivityRecord srec;
1854 synchronized (mGlobalLock) {
1855 srec = ActivityRecord.forTokenLocked(activityToken);
1856 }
1857 if (srec == null) {
1858 return null;
1859 }
1860 return srec.launchedFromPackage;
1861 }
1862
1863 @Override
1864 public boolean convertFromTranslucent(IBinder token) {
1865 final long origId = Binder.clearCallingIdentity();
1866 try {
1867 synchronized (mGlobalLock) {
1868 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1869 if (r == null) {
1870 return false;
1871 }
1872 final boolean translucentChanged = r.changeWindowTranslucency(true);
1873 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001874 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 return translucentChanged;
1878 }
1879 } finally {
1880 Binder.restoreCallingIdentity(origId);
1881 }
1882 }
1883
1884 @Override
1885 public boolean convertToTranslucent(IBinder token, Bundle options) {
1886 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1887 final long origId = Binder.clearCallingIdentity();
1888 try {
1889 synchronized (mGlobalLock) {
1890 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1891 if (r == null) {
1892 return false;
1893 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001894 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 int index = task.mActivities.lastIndexOf(r);
1896 if (index > 0) {
1897 ActivityRecord under = task.mActivities.get(index - 1);
1898 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1899 }
1900 final boolean translucentChanged = r.changeWindowTranslucency(false);
1901 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001902 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001904 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001905 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 return translucentChanged;
1907 }
1908 } finally {
1909 Binder.restoreCallingIdentity(origId);
1910 }
1911 }
1912
1913 @Override
1914 public void notifyActivityDrawn(IBinder token) {
1915 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1916 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001917 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001919 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 }
1921 }
1922 }
1923
1924 @Override
1925 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1926 synchronized (mGlobalLock) {
1927 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1928 if (r == null) {
1929 return;
1930 }
1931 r.reportFullyDrawnLocked(restoredFromBundle);
1932 }
1933 }
1934
1935 @Override
1936 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1937 synchronized (mGlobalLock) {
1938 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1939 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1940 return stack.mDisplayId;
1941 }
1942 return DEFAULT_DISPLAY;
1943 }
1944 }
1945
1946 @Override
1947 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 long ident = Binder.clearCallingIdentity();
1950 try {
1951 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001952 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001954 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 }
1956 return null;
1957 }
1958 } finally {
1959 Binder.restoreCallingIdentity(ident);
1960 }
1961 }
1962
1963 @Override
1964 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001965 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1967 final long callingId = Binder.clearCallingIdentity();
1968 try {
1969 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001970 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 if (stack == null) {
1972 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1973 return;
1974 }
1975 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001976 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001977 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 }
1979 }
1980 } finally {
1981 Binder.restoreCallingIdentity(callingId);
1982 }
1983 }
1984
1985 @Override
1986 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001987 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1989 final long callingId = Binder.clearCallingIdentity();
1990 try {
1991 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001992 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001993 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 if (task == null) {
1995 return;
1996 }
1997 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001998 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001999 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 }
2001 }
2002 } finally {
2003 Binder.restoreCallingIdentity(callingId);
2004 }
2005 }
2006
2007 @Override
2008 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 synchronized (mGlobalLock) {
2011 final long ident = Binder.clearCallingIdentity();
2012 try {
2013 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2014 "remove-task");
2015 } finally {
2016 Binder.restoreCallingIdentity(ident);
2017 }
2018 }
2019 }
2020
2021 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002022 public void removeAllVisibleRecentTasks() {
2023 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2024 synchronized (mGlobalLock) {
2025 final long ident = Binder.clearCallingIdentity();
2026 try {
2027 getRecentTasks().removeAllVisibleTasks();
2028 } finally {
2029 Binder.restoreCallingIdentity(ident);
2030 }
2031 }
2032 }
2033
2034 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2036 synchronized (mGlobalLock) {
2037 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2038 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002039 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 }
2042 return false;
2043 }
2044
2045 @Override
2046 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2047 Intent resultData) {
2048
2049 synchronized (mGlobalLock) {
2050 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2051 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002052 return r.getActivityStack().navigateUpToLocked(
2053 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 return false;
2056 }
2057 }
2058
2059 /**
2060 * Attempts to move a task backwards in z-order (the order of activities within the task is
2061 * unchanged).
2062 *
2063 * There are several possible results of this call:
2064 * - if the task is locked, then we will show the lock toast
2065 * - if there is a task behind the provided task, then that task is made visible and resumed as
2066 * this task is moved to the back
2067 * - otherwise, if there are no other tasks in the stack:
2068 * - if this task is in the pinned stack, then we remove the stack completely, which will
2069 * have the effect of moving the task to the top or bottom of the fullscreen stack
2070 * (depending on whether it is visible)
2071 * - otherwise, we simply return home and hide this task
2072 *
2073 * @param token A reference to the activity we wish to move
2074 * @param nonRoot If false then this only works if the activity is the root
2075 * of a task; if true it will work for any activity in a task.
2076 * @return Returns true if the move completed, false if not.
2077 */
2078 @Override
2079 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002080 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 synchronized (mGlobalLock) {
2082 final long origId = Binder.clearCallingIdentity();
2083 try {
2084 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002085 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 if (task != null) {
2087 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2088 }
2089 } finally {
2090 Binder.restoreCallingIdentity(origId);
2091 }
2092 }
2093 return false;
2094 }
2095
2096 @Override
2097 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002098 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 long ident = Binder.clearCallingIdentity();
2100 Rect rect = new Rect();
2101 try {
2102 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002103 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002104 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2105 if (task == null) {
2106 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2107 return rect;
2108 }
2109 if (task.getStack() != null) {
2110 // Return the bounds from window manager since it will be adjusted for various
2111 // things like the presense of a docked stack for tasks that aren't resizeable.
2112 task.getWindowContainerBounds(rect);
2113 } else {
2114 // Task isn't in window manager yet since it isn't associated with a stack.
2115 // Return the persist value from activity manager
2116 if (!task.matchParentBounds()) {
2117 rect.set(task.getBounds());
2118 } else if (task.mLastNonFullscreenBounds != null) {
2119 rect.set(task.mLastNonFullscreenBounds);
2120 }
2121 }
2122 }
2123 } finally {
2124 Binder.restoreCallingIdentity(ident);
2125 }
2126 return rect;
2127 }
2128
2129 @Override
2130 public ActivityManager.TaskDescription getTaskDescription(int id) {
2131 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002132 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002134 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002135 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2136 if (tr != null) {
2137 return tr.lastTaskDescription;
2138 }
2139 }
2140 return null;
2141 }
2142
2143 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002144 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2145 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2146 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2147 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2148 return;
2149 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002150 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002151 synchronized (mGlobalLock) {
2152 final long ident = Binder.clearCallingIdentity();
2153 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002154 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002155 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002156 if (task == null) {
2157 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2158 return;
2159 }
2160
2161 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2162 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2163
2164 if (!task.isActivityTypeStandardOrUndefined()) {
2165 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2166 + " non-standard task " + taskId + " to windowing mode="
2167 + windowingMode);
2168 }
2169
2170 final ActivityStack stack = task.getStack();
2171 if (toTop) {
2172 stack.moveToFront("setTaskWindowingMode", task);
2173 }
2174 stack.setWindowingMode(windowingMode);
2175 } finally {
2176 Binder.restoreCallingIdentity(ident);
2177 }
2178 }
2179 }
2180
2181 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002183 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 ActivityRecord r = getCallingRecordLocked(token);
2185 return r != null ? r.info.packageName : null;
2186 }
2187 }
2188
2189 @Override
2190 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 ActivityRecord r = getCallingRecordLocked(token);
2193 return r != null ? r.intent.getComponent() : null;
2194 }
2195 }
2196
2197 private ActivityRecord getCallingRecordLocked(IBinder token) {
2198 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2199 if (r == null) {
2200 return null;
2201 }
2202 return r.resultTo;
2203 }
2204
2205 @Override
2206 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002207 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002208
2209 synchronized (mGlobalLock) {
2210 final long origId = Binder.clearCallingIdentity();
2211 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002212 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 } finally {
2214 Binder.restoreCallingIdentity(origId);
2215 }
2216 }
2217 }
2218
2219 /**
2220 * TODO: Add mController hook
2221 */
2222 @Override
2223 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002224 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225
2226 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2227 synchronized (mGlobalLock) {
2228 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2229 false /* fromRecents */);
2230 }
2231 }
2232
2233 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2234 boolean fromRecents) {
2235
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002236 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 Binder.getCallingUid(), -1, -1, "Task to front")) {
2238 SafeActivityOptions.abort(options);
2239 return;
2240 }
2241 final long origId = Binder.clearCallingIdentity();
2242 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002243 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 if (task == null) {
2245 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002246 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 return;
2248 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002249 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002251 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002252 return;
2253 }
2254 ActivityOptions realOptions = options != null
2255 ? options.getOptions(mStackSupervisor)
2256 : null;
2257 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2258 false /* forceNonResizable */);
2259
2260 final ActivityRecord topActivity = task.getTopActivity();
2261 if (topActivity != null) {
2262
2263 // We are reshowing a task, use a starting window to hide the initial draw delay
2264 // so the transition can start earlier.
2265 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2266 true /* taskSwitch */, fromRecents);
2267 }
2268 } finally {
2269 Binder.restoreCallingIdentity(origId);
2270 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002271 }
2272
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002273 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2274 int callingPid, int callingUid, String name) {
2275 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2276 return true;
2277 }
2278
2279 if (getRecentTasks().isCallerRecents(sourceUid)) {
2280 return true;
2281 }
2282
2283 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2284 if (perm == PackageManager.PERMISSION_GRANTED) {
2285 return true;
2286 }
2287 if (checkAllowAppSwitchUid(sourceUid)) {
2288 return true;
2289 }
2290
2291 // If the actual IPC caller is different from the logical source, then
2292 // also see if they are allowed to control app switches.
2293 if (callingUid != -1 && callingUid != sourceUid) {
2294 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2295 if (perm == PackageManager.PERMISSION_GRANTED) {
2296 return true;
2297 }
2298 if (checkAllowAppSwitchUid(callingUid)) {
2299 return true;
2300 }
2301 }
2302
2303 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2304 return false;
2305 }
2306
2307 private boolean checkAllowAppSwitchUid(int uid) {
2308 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2309 if (types != null) {
2310 for (int i = types.size() - 1; i >= 0; i--) {
2311 if (types.valueAt(i).intValue() == uid) {
2312 return true;
2313 }
2314 }
2315 }
2316 return false;
2317 }
2318
2319 @Override
2320 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2321 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2322 "setActivityController()");
2323 synchronized (mGlobalLock) {
2324 mController = controller;
2325 mControllerIsAMonkey = imAMonkey;
2326 Watchdog.getInstance().setActivityController(controller);
2327 }
2328 }
2329
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002330 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002331 synchronized (mGlobalLock) {
2332 return mController != null && mControllerIsAMonkey;
2333 }
2334 }
2335
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336 @Override
2337 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2338 synchronized (mGlobalLock) {
2339 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2340 }
2341 }
2342
2343 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002344 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2345 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2346 }
2347
2348 @Override
2349 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2350 @WindowConfiguration.ActivityType int ignoreActivityType,
2351 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2352 final int callingUid = Binder.getCallingUid();
2353 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2354
2355 synchronized (mGlobalLock) {
2356 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2357
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002358 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002359 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002360 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002361 ignoreWindowingMode, callingUid, allowed);
2362 }
2363
2364 return list;
2365 }
2366
2367 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2369 synchronized (mGlobalLock) {
2370 final long origId = Binder.clearCallingIdentity();
2371 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2372 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002373 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 }
2375 Binder.restoreCallingIdentity(origId);
2376 }
2377 }
2378
2379 @Override
2380 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002381 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 ActivityStack stack = ActivityRecord.getStackLocked(token);
2383 if (stack != null) {
2384 return stack.willActivityBeVisibleLocked(token);
2385 }
2386 return false;
2387 }
2388 }
2389
2390 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002391 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002392 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002393 synchronized (mGlobalLock) {
2394 final long ident = Binder.clearCallingIdentity();
2395 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002396 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002397 if (task == null) {
2398 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2399 return;
2400 }
2401
2402 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2403 + " to stackId=" + stackId + " toTop=" + toTop);
2404
Wale Ogunwaled32da472018-11-16 07:19:28 -08002405 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002406 if (stack == null) {
2407 throw new IllegalStateException(
2408 "moveTaskToStack: No stack for stackId=" + stackId);
2409 }
2410 if (!stack.isActivityTypeStandardOrUndefined()) {
2411 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2412 + taskId + " to stack " + stackId);
2413 }
2414 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002416 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2417 }
2418 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2419 "moveTaskToStack");
2420 } finally {
2421 Binder.restoreCallingIdentity(ident);
2422 }
2423 }
2424 }
2425
2426 @Override
2427 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2428 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002429 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002430
2431 final long ident = Binder.clearCallingIdentity();
2432 try {
2433 synchronized (mGlobalLock) {
2434 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002435 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002436 if (stack == null) {
2437 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2438 return;
2439 }
2440 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2441 throw new IllegalArgumentException("Stack: " + stackId
2442 + " doesn't support animated resize.");
2443 }
2444 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2445 animationDuration, false /* fromFullscreen */);
2446 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002447 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002448 if (stack == null) {
2449 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2450 return;
2451 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002452 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002453 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2454 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2455 }
2456 }
2457 } finally {
2458 Binder.restoreCallingIdentity(ident);
2459 }
2460 }
2461
wilsonshih5c4cf522019-01-25 09:03:47 +08002462 @Override
2463 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2464 int animationDuration) {
2465 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2466
2467 final long ident = Binder.clearCallingIdentity();
2468 try {
2469 synchronized (mGlobalLock) {
2470 if (xOffset == 0 && yOffset == 0) {
2471 return;
2472 }
2473 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2474 if (stack == null) {
2475 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2476 return;
2477 }
2478 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2479 throw new IllegalArgumentException("Stack: " + stackId
2480 + " doesn't support animated resize.");
2481 }
2482 final Rect destBounds = new Rect();
2483 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002484 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002485 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2486 return;
2487 }
2488 destBounds.offset(xOffset, yOffset);
2489 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2490 animationDuration, false /* fromFullscreen */);
2491 }
2492 } finally {
2493 Binder.restoreCallingIdentity(ident);
2494 }
2495 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002496 /**
2497 * Moves the specified task to the primary-split-screen stack.
2498 *
2499 * @param taskId Id of task to move.
2500 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2501 * exist already. See
2502 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2503 * and
2504 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2505 * @param toTop If the task and stack should be moved to the top.
2506 * @param animate Whether we should play an animation for the moving the task.
2507 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2508 * stack. Pass {@code null} to use default bounds.
2509 * @param showRecents If the recents activity should be shown on the other side of the task
2510 * going into split-screen mode.
2511 */
2512 @Override
2513 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2514 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002515 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002516 "setTaskWindowingModeSplitScreenPrimary()");
2517 synchronized (mGlobalLock) {
2518 final long ident = Binder.clearCallingIdentity();
2519 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002520 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002521 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002522 if (task == null) {
2523 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2524 return false;
2525 }
2526 if (DEBUG_STACK) Slog.d(TAG_STACK,
2527 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2528 + " to createMode=" + createMode + " toTop=" + toTop);
2529 if (!task.isActivityTypeStandardOrUndefined()) {
2530 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2531 + " non-standard task " + taskId + " to split-screen windowing mode");
2532 }
2533
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002534 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 final int windowingMode = task.getWindowingMode();
2536 final ActivityStack stack = task.getStack();
2537 if (toTop) {
2538 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2539 }
2540 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002541 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2542 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 return windowingMode != task.getWindowingMode();
2544 } finally {
2545 Binder.restoreCallingIdentity(ident);
2546 }
2547 }
2548 }
2549
2550 /**
2551 * Removes stacks in the input windowing modes from the system if they are of activity type
2552 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2553 */
2554 @Override
2555 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002556 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 "removeStacksInWindowingModes()");
2558
2559 synchronized (mGlobalLock) {
2560 final long ident = Binder.clearCallingIdentity();
2561 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002562 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 } finally {
2564 Binder.restoreCallingIdentity(ident);
2565 }
2566 }
2567 }
2568
2569 @Override
2570 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572 "removeStacksWithActivityTypes()");
2573
2574 synchronized (mGlobalLock) {
2575 final long ident = Binder.clearCallingIdentity();
2576 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002577 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 } finally {
2579 Binder.restoreCallingIdentity(ident);
2580 }
2581 }
2582 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583
2584 @Override
2585 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2586 int userId) {
2587 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002588 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2589 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002590 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002591 final boolean detailed = checkGetTasksPermission(
2592 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2593 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002594 == PackageManager.PERMISSION_GRANTED;
2595
2596 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002597 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 callingUid);
2599 }
2600 }
2601
2602 @Override
2603 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002604 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002605 long ident = Binder.clearCallingIdentity();
2606 try {
2607 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002608 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002609 }
2610 } finally {
2611 Binder.restoreCallingIdentity(ident);
2612 }
2613 }
2614
2615 @Override
2616 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002617 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002618 long ident = Binder.clearCallingIdentity();
2619 try {
2620 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002621 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002622 }
2623 } finally {
2624 Binder.restoreCallingIdentity(ident);
2625 }
2626 }
2627
2628 @Override
2629 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002630 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002631 final long callingUid = Binder.getCallingUid();
2632 final long origId = Binder.clearCallingIdentity();
2633 try {
2634 synchronized (mGlobalLock) {
2635 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002636 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002637 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2638 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2639 }
2640 } finally {
2641 Binder.restoreCallingIdentity(origId);
2642 }
2643 }
2644
2645 @Override
2646 public void startLockTaskModeByToken(IBinder token) {
2647 synchronized (mGlobalLock) {
2648 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2649 if (r == null) {
2650 return;
2651 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002652 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002653 }
2654 }
2655
2656 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002657 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002658 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002659 // This makes inner call to look as if it was initiated by system.
2660 long ident = Binder.clearCallingIdentity();
2661 try {
2662 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002663 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002664 MATCH_TASK_IN_STACKS_ONLY);
2665 if (task == null) {
2666 return;
2667 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002668
2669 // When starting lock task mode the stack must be in front and focused
2670 task.getStack().moveToFront("startSystemLockTaskMode");
2671 startLockTaskModeLocked(task, true /* isSystemCaller */);
2672 }
2673 } finally {
2674 Binder.restoreCallingIdentity(ident);
2675 }
2676 }
2677
2678 @Override
2679 public void stopLockTaskModeByToken(IBinder token) {
2680 synchronized (mGlobalLock) {
2681 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2682 if (r == null) {
2683 return;
2684 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002685 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002686 }
2687 }
2688
2689 /**
2690 * This API should be called by SystemUI only when user perform certain action to dismiss
2691 * lock task mode. We should only dismiss pinned lock task mode in this case.
2692 */
2693 @Override
2694 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002695 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002696 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2697 }
2698
2699 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2700 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2701 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2702 return;
2703 }
2704
Wale Ogunwaled32da472018-11-16 07:19:28 -08002705 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002706 if (stack == null || task != stack.topTask()) {
2707 throw new IllegalArgumentException("Invalid task, not in foreground");
2708 }
2709
2710 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2711 // system or a specific app.
2712 // * System-initiated requests will only start the pinned mode (screen pinning)
2713 // * App-initiated requests
2714 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2715 // - will start the pinned mode, otherwise
2716 final int callingUid = Binder.getCallingUid();
2717 long ident = Binder.clearCallingIdentity();
2718 try {
2719 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002720 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002722 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002723 } finally {
2724 Binder.restoreCallingIdentity(ident);
2725 }
2726 }
2727
2728 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2729 final int callingUid = Binder.getCallingUid();
2730 long ident = Binder.clearCallingIdentity();
2731 try {
2732 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002733 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002734 }
2735 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2736 // task and jumping straight into a call in the case of emergency call back.
2737 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2738 if (tm != null) {
2739 tm.showInCallScreen(false);
2740 }
2741 } finally {
2742 Binder.restoreCallingIdentity(ident);
2743 }
2744 }
2745
2746 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002747 public void updateLockTaskPackages(int userId, String[] packages) {
2748 final int callingUid = Binder.getCallingUid();
2749 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2750 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2751 "updateLockTaskPackages()");
2752 }
2753 synchronized (this) {
2754 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2755 + Arrays.toString(packages));
2756 getLockTaskController().updateLockTaskPackages(userId, packages);
2757 }
2758 }
2759
2760 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 public boolean isInLockTaskMode() {
2762 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2763 }
2764
2765 @Override
2766 public int getLockTaskModeState() {
2767 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002768 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 }
2770 }
2771
2772 @Override
2773 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2774 synchronized (mGlobalLock) {
2775 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2776 if (r != null) {
2777 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002778 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002780 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002781 }
2782 }
2783 }
2784
2785 @Override
2786 public Bundle getActivityOptions(IBinder token) {
2787 final long origId = Binder.clearCallingIdentity();
2788 try {
2789 synchronized (mGlobalLock) {
2790 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2791 if (r != null) {
2792 final ActivityOptions activityOptions = r.takeOptionsLocked();
2793 return activityOptions == null ? null : activityOptions.toBundle();
2794 }
2795 return null;
2796 }
2797 } finally {
2798 Binder.restoreCallingIdentity(origId);
2799 }
2800 }
2801
2802 @Override
2803 public List<IBinder> getAppTasks(String callingPackage) {
2804 int callingUid = Binder.getCallingUid();
2805 long ident = Binder.clearCallingIdentity();
2806 try {
2807 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002808 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810 } finally {
2811 Binder.restoreCallingIdentity(ident);
2812 }
2813 }
2814
2815 @Override
2816 public void finishVoiceTask(IVoiceInteractionSession session) {
2817 synchronized (mGlobalLock) {
2818 final long origId = Binder.clearCallingIdentity();
2819 try {
2820 // TODO: VI Consider treating local voice interactions and voice tasks
2821 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002822 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 } finally {
2824 Binder.restoreCallingIdentity(origId);
2825 }
2826 }
2827
2828 }
2829
2830 @Override
2831 public boolean isTopOfTask(IBinder token) {
2832 synchronized (mGlobalLock) {
2833 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002834 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835 }
2836 }
2837
2838 @Override
2839 public void notifyLaunchTaskBehindComplete(IBinder token) {
2840 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2841 }
2842
2843 @Override
2844 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002845 mH.post(() -> {
2846 synchronized (mGlobalLock) {
2847 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002848 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002849 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002850 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002851 } catch (RemoteException e) {
2852 }
2853 }
2854 }
2855
2856 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 }
2858
2859 /** Called from an app when assist data is ready. */
2860 @Override
2861 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2862 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002863 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 synchronized (pae) {
2865 pae.result = extras;
2866 pae.structure = structure;
2867 pae.content = content;
2868 if (referrer != null) {
2869 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2870 }
2871 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002872 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002873 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2874 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875 structure.setHomeActivity(pae.isHome);
2876 }
2877 pae.haveResult = true;
2878 pae.notifyAll();
2879 if (pae.intent == null && pae.receiver == null) {
2880 // Caller is just waiting for the result.
2881 return;
2882 }
2883 }
2884 // We are now ready to launch the assist activity.
2885 IAssistDataReceiver sendReceiver = null;
2886 Bundle sendBundle = null;
2887 synchronized (mGlobalLock) {
2888 buildAssistBundleLocked(pae, extras);
2889 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002890 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 if (!exists) {
2892 // Timed out.
2893 return;
2894 }
2895
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002896 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 // Caller wants result sent back to them.
2898 sendBundle = new Bundle();
2899 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2900 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2901 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2902 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2903 }
2904 }
2905 if (sendReceiver != null) {
2906 try {
2907 sendReceiver.onHandleAssistData(sendBundle);
2908 } catch (RemoteException e) {
2909 }
2910 return;
2911 }
2912
2913 final long ident = Binder.clearCallingIdentity();
2914 try {
2915 if (TextUtils.equals(pae.intent.getAction(),
2916 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2917 pae.intent.putExtras(pae.extras);
2918 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2919 } else {
2920 pae.intent.replaceExtras(pae.extras);
2921 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2922 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2923 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002924 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925
2926 try {
2927 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2928 } catch (ActivityNotFoundException e) {
2929 Slog.w(TAG, "No activity to handle assist action.", e);
2930 }
2931 }
2932 } finally {
2933 Binder.restoreCallingIdentity(ident);
2934 }
2935 }
2936
2937 @Override
2938 public int addAppTask(IBinder activityToken, Intent intent,
2939 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2940 final int callingUid = Binder.getCallingUid();
2941 final long callingIdent = Binder.clearCallingIdentity();
2942
2943 try {
2944 synchronized (mGlobalLock) {
2945 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2946 if (r == null) {
2947 throw new IllegalArgumentException("Activity does not exist; token="
2948 + activityToken);
2949 }
2950 ComponentName comp = intent.getComponent();
2951 if (comp == null) {
2952 throw new IllegalArgumentException("Intent " + intent
2953 + " must specify explicit component");
2954 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002955 if (thumbnail.getWidth() != mThumbnailWidth
2956 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 throw new IllegalArgumentException("Bad thumbnail size: got "
2958 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002959 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002960 }
2961 if (intent.getSelector() != null) {
2962 intent.setSelector(null);
2963 }
2964 if (intent.getSourceBounds() != null) {
2965 intent.setSourceBounds(null);
2966 }
2967 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2968 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2969 // The caller has added this as an auto-remove task... that makes no
2970 // sense, so turn off auto-remove.
2971 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2972 }
2973 }
2974 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2975 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2976 if (ainfo.applicationInfo.uid != callingUid) {
2977 throw new SecurityException(
2978 "Can't add task for another application: target uid="
2979 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2980 }
2981
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002982 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002984 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002986 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002987 // The app has too many tasks already and we can't add any more
2988 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2989 return INVALID_TASK_ID;
2990 }
2991 task.lastTaskDescription.copyFrom(description);
2992
2993 // TODO: Send the thumbnail to WM to store it.
2994
2995 return task.taskId;
2996 }
2997 } finally {
2998 Binder.restoreCallingIdentity(callingIdent);
2999 }
3000 }
3001
3002 @Override
3003 public Point getAppTaskThumbnailSize() {
3004 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003005 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 }
3007 }
3008
3009 @Override
3010 public void setTaskResizeable(int taskId, int resizeableMode) {
3011 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003012 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3014 if (task == null) {
3015 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3016 return;
3017 }
3018 task.setResizeMode(resizeableMode);
3019 }
3020 }
3021
3022 @Override
3023 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003024 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 long ident = Binder.clearCallingIdentity();
3026 try {
3027 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003028 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003029 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 if (task == null) {
3031 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3032 return;
3033 }
3034 // Place the task in the right stack if it isn't there already based on
3035 // the requested bounds.
3036 // The stack transition logic is:
3037 // - a null bounds on a freeform task moves that task to fullscreen
3038 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3039 // that task to freeform
3040 // - otherwise the task is not moved
3041 ActivityStack stack = task.getStack();
3042 if (!task.getWindowConfiguration().canResizeTask()) {
3043 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3044 }
3045 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3046 stack = stack.getDisplay().getOrCreateStack(
3047 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3048 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3049 stack = stack.getDisplay().getOrCreateStack(
3050 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3051 }
3052
3053 // Reparent the task to the right stack if necessary
3054 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3055 if (stack != task.getStack()) {
3056 // Defer resume until the task is resized below
3057 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3058 DEFER_RESUME, "resizeTask");
3059 preserveWindow = false;
3060 }
3061
3062 // After reparenting (which only resizes the task to the stack bounds), resize the
3063 // task to the actual bounds provided
3064 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3065 }
3066 } finally {
3067 Binder.restoreCallingIdentity(ident);
3068 }
3069 }
3070
3071 @Override
3072 public boolean releaseActivityInstance(IBinder token) {
3073 synchronized (mGlobalLock) {
3074 final long origId = Binder.clearCallingIdentity();
3075 try {
3076 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3077 if (r == null) {
3078 return false;
3079 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003080 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 } finally {
3082 Binder.restoreCallingIdentity(origId);
3083 }
3084 }
3085 }
3086
3087 @Override
3088 public void releaseSomeActivities(IApplicationThread appInt) {
3089 synchronized (mGlobalLock) {
3090 final long origId = Binder.clearCallingIdentity();
3091 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003092 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003093 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003094 } finally {
3095 Binder.restoreCallingIdentity(origId);
3096 }
3097 }
3098 }
3099
3100 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003101 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003102 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 != PackageManager.PERMISSION_GRANTED) {
3104 throw new SecurityException("Requires permission "
3105 + android.Manifest.permission.DEVICE_POWER);
3106 }
3107
3108 synchronized (mGlobalLock) {
3109 long ident = Binder.clearCallingIdentity();
3110 if (mKeyguardShown != keyguardShowing) {
3111 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003112 final Message msg = PooledLambda.obtainMessage(
3113 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3114 keyguardShowing);
3115 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 }
3117 try {
wilsonshih177261f2019-02-22 12:02:18 +08003118 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 } finally {
3120 Binder.restoreCallingIdentity(ident);
3121 }
3122 }
3123
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003124 mH.post(() -> {
3125 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3126 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3127 }
3128 });
3129 }
3130
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003131 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003132 mH.post(() -> {
3133 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3134 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3135 }
3136 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137 }
3138
3139 @Override
3140 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003141 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3142 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143
3144 final File passedIconFile = new File(filePath);
3145 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3146 passedIconFile.getName());
3147 if (!legitIconFile.getPath().equals(filePath)
3148 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3149 throw new IllegalArgumentException("Bad file path: " + filePath
3150 + " passed for userId " + userId);
3151 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003152 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 }
3154
3155 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003156 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3158 final ActivityOptions activityOptions = safeOptions != null
3159 ? safeOptions.getOptions(mStackSupervisor)
3160 : null;
3161 if (activityOptions == null
3162 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3163 || activityOptions.getCustomInPlaceResId() == 0) {
3164 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3165 "with valid animation");
3166 }
lumark588a3e82018-07-20 18:53:54 +08003167 // Get top display of front most application.
3168 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3169 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003170 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3171 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3172 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003173 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003174 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003175 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 }
3177
3178 @Override
3179 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 synchronized (mGlobalLock) {
3182 final long ident = Binder.clearCallingIdentity();
3183 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003184 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 if (stack == null) {
3186 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3187 return;
3188 }
3189 if (!stack.isActivityTypeStandardOrUndefined()) {
3190 throw new IllegalArgumentException(
3191 "Removing non-standard stack is not allowed.");
3192 }
3193 mStackSupervisor.removeStack(stack);
3194 } finally {
3195 Binder.restoreCallingIdentity(ident);
3196 }
3197 }
3198 }
3199
3200 @Override
3201 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003202 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203
3204 synchronized (mGlobalLock) {
3205 final long ident = Binder.clearCallingIdentity();
3206 try {
3207 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3208 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003209 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 } finally {
3211 Binder.restoreCallingIdentity(ident);
3212 }
3213 }
3214 }
3215
3216 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003217 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003218 synchronized (mGlobalLock) {
3219 long ident = Binder.clearCallingIdentity();
3220 try {
3221 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3222 if (r == null) {
3223 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003224 "toggleFreeformWindowingMode: No activity record matching token="
3225 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 }
3227
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003228 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003229 if (stack == null) {
3230 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3231 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003232 }
3233
Yunfan Chend967af82019-01-17 18:30:18 +09003234 if (!stack.inFreeformWindowingMode()
3235 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3236 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3237 + "toggle between fullscreen and freeform.");
3238 }
3239
3240 if (stack.inFreeformWindowingMode()) {
3241 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3242 } else {
3243 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3244 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 } finally {
3246 Binder.restoreCallingIdentity(ident);
3247 }
3248 }
3249 }
3250
3251 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3252 @Override
3253 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003254 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003256 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003257 }
3258
3259 /** Unregister a task stack listener so that it stops receiving callbacks. */
3260 @Override
3261 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003262 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003263 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003264 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003265 }
3266
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 @Override
3268 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3269 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3270 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3271 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3272 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3273 }
3274
3275 @Override
3276 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3277 IBinder activityToken, int flags) {
3278 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3279 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3280 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3281 }
3282
3283 @Override
3284 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3285 Bundle args) {
3286 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3287 true /* focused */, true /* newSessionId */, userHandle, args,
3288 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3289 }
3290
3291 @Override
3292 public Bundle getAssistContextExtras(int requestType) {
3293 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3294 null, null, true /* focused */, true /* newSessionId */,
3295 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3296 if (pae == null) {
3297 return null;
3298 }
3299 synchronized (pae) {
3300 while (!pae.haveResult) {
3301 try {
3302 pae.wait();
3303 } catch (InterruptedException e) {
3304 }
3305 }
3306 }
3307 synchronized (mGlobalLock) {
3308 buildAssistBundleLocked(pae, pae.result);
3309 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003310 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003311 }
3312 return pae.extras;
3313 }
3314
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003315 /**
3316 * Binder IPC calls go through the public entry point.
3317 * This can be called with or without the global lock held.
3318 */
3319 private static int checkCallingPermission(String permission) {
3320 return checkPermission(
3321 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3322 }
3323
3324 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003325 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003326 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3327 mAmInternal.enforceCallingPermission(permission, func);
3328 }
3329 }
3330
3331 @VisibleForTesting
3332 int checkGetTasksPermission(String permission, int pid, int uid) {
3333 return checkPermission(permission, pid, uid);
3334 }
3335
3336 static int checkPermission(String permission, int pid, int uid) {
3337 if (permission == null) {
3338 return PackageManager.PERMISSION_DENIED;
3339 }
3340 return checkComponentPermission(permission, pid, uid, -1, true);
3341 }
3342
Wale Ogunwale214f3482018-10-04 11:00:47 -07003343 public static int checkComponentPermission(String permission, int pid, int uid,
3344 int owningUid, boolean exported) {
3345 return ActivityManagerService.checkComponentPermission(
3346 permission, pid, uid, owningUid, exported);
3347 }
3348
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003349 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3350 if (getRecentTasks().isCallerRecents(callingUid)) {
3351 // Always allow the recents component to get tasks
3352 return true;
3353 }
3354
3355 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3356 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3357 if (!allowed) {
3358 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3359 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3360 // Temporary compatibility: some existing apps on the system image may
3361 // still be requesting the old permission and not switched to the new
3362 // one; if so, we'll still allow them full access. This means we need
3363 // to see if they are holding the old permission and are a system app.
3364 try {
3365 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3366 allowed = true;
3367 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3368 + " is using old GET_TASKS but privileged; allowing");
3369 }
3370 } catch (RemoteException e) {
3371 }
3372 }
3373 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3374 + " does not hold REAL_GET_TASKS; limiting output");
3375 }
3376 return allowed;
3377 }
3378
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3380 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3381 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3382 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003383 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384 "enqueueAssistContext()");
3385
3386 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003387 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 if (activity == null) {
3389 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3390 return null;
3391 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003392 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3394 return null;
3395 }
3396 if (focused) {
3397 if (activityToken != null) {
3398 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3399 if (activity != caller) {
3400 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3401 + " is not current top " + activity);
3402 return null;
3403 }
3404 }
3405 } else {
3406 activity = ActivityRecord.forTokenLocked(activityToken);
3407 if (activity == null) {
3408 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3409 + " couldn't be found");
3410 return null;
3411 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003412 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3414 return null;
3415 }
3416 }
3417
3418 PendingAssistExtras pae;
3419 Bundle extras = new Bundle();
3420 if (args != null) {
3421 extras.putAll(args);
3422 }
3423 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003424 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425
3426 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3427 userHandle);
3428 pae.isHome = activity.isActivityTypeHome();
3429
3430 // Increment the sessionId if necessary
3431 if (newSessionId) {
3432 mViSessionId++;
3433 }
3434 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003435 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3436 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003438 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439 } catch (RemoteException e) {
3440 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3441 return null;
3442 }
3443 return pae;
3444 }
3445 }
3446
3447 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3448 if (result != null) {
3449 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3450 }
3451 if (pae.hint != null) {
3452 pae.extras.putBoolean(pae.hint, true);
3453 }
3454 }
3455
3456 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3457 IAssistDataReceiver receiver;
3458 synchronized (mGlobalLock) {
3459 mPendingAssistExtras.remove(pae);
3460 receiver = pae.receiver;
3461 }
3462 if (receiver != null) {
3463 // Caller wants result sent back to them.
3464 Bundle sendBundle = new Bundle();
3465 // At least return the receiver extras
3466 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3467 try {
3468 pae.receiver.onHandleAssistData(sendBundle);
3469 } catch (RemoteException e) {
3470 }
3471 }
3472 }
3473
3474 public class PendingAssistExtras extends Binder implements Runnable {
3475 public final ActivityRecord activity;
3476 public boolean isHome;
3477 public final Bundle extras;
3478 public final Intent intent;
3479 public final String hint;
3480 public final IAssistDataReceiver receiver;
3481 public final int userHandle;
3482 public boolean haveResult = false;
3483 public Bundle result = null;
3484 public AssistStructure structure = null;
3485 public AssistContent content = null;
3486 public Bundle receiverExtras;
3487
3488 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3489 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3490 int _userHandle) {
3491 activity = _activity;
3492 extras = _extras;
3493 intent = _intent;
3494 hint = _hint;
3495 receiver = _receiver;
3496 receiverExtras = _receiverExtras;
3497 userHandle = _userHandle;
3498 }
3499
3500 @Override
3501 public void run() {
3502 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3503 synchronized (this) {
3504 haveResult = true;
3505 notifyAll();
3506 }
3507 pendingAssistExtrasTimedOut(this);
3508 }
3509 }
3510
3511 @Override
3512 public boolean isAssistDataAllowedOnCurrentActivity() {
3513 int userId;
3514 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003515 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003516 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3517 return false;
3518 }
3519
3520 final ActivityRecord activity = focusedStack.getTopActivity();
3521 if (activity == null) {
3522 return false;
3523 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003524 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 }
3526 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3527 }
3528
3529 @Override
3530 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3531 long ident = Binder.clearCallingIdentity();
3532 try {
3533 synchronized (mGlobalLock) {
3534 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003535 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003536 if (top != caller) {
3537 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3538 + " is not current top " + top);
3539 return false;
3540 }
3541 if (!top.nowVisible) {
3542 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3543 + " is not visible");
3544 return false;
3545 }
3546 }
3547 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3548 token);
3549 } finally {
3550 Binder.restoreCallingIdentity(ident);
3551 }
3552 }
3553
3554 @Override
3555 public boolean isRootVoiceInteraction(IBinder token) {
3556 synchronized (mGlobalLock) {
3557 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3558 if (r == null) {
3559 return false;
3560 }
3561 return r.rootVoiceInteraction;
3562 }
3563 }
3564
Wale Ogunwalef6733932018-06-27 05:14:34 -07003565 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3566 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3567 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3568 if (activityToCallback == null) return;
3569 activityToCallback.setVoiceSessionLocked(voiceSession);
3570
3571 // Inform the activity
3572 try {
3573 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3574 voiceInteractor);
3575 long token = Binder.clearCallingIdentity();
3576 try {
3577 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3578 } finally {
3579 Binder.restoreCallingIdentity(token);
3580 }
3581 // TODO: VI Should we cache the activity so that it's easier to find later
3582 // rather than scan through all the stacks and activities?
3583 } catch (RemoteException re) {
3584 activityToCallback.clearVoiceSessionLocked();
3585 // TODO: VI Should this terminate the voice session?
3586 }
3587 }
3588
3589 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3590 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3591 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3592 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3593 boolean wasRunningVoice = mRunningVoice != null;
3594 mRunningVoice = session;
3595 if (!wasRunningVoice) {
3596 mVoiceWakeLock.acquire();
3597 updateSleepIfNeededLocked();
3598 }
3599 }
3600 }
3601
3602 void finishRunningVoiceLocked() {
3603 if (mRunningVoice != null) {
3604 mRunningVoice = null;
3605 mVoiceWakeLock.release();
3606 updateSleepIfNeededLocked();
3607 }
3608 }
3609
3610 @Override
3611 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3612 synchronized (mGlobalLock) {
3613 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3614 if (keepAwake) {
3615 mVoiceWakeLock.acquire();
3616 } else {
3617 mVoiceWakeLock.release();
3618 }
3619 }
3620 }
3621 }
3622
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003623 @Override
3624 public ComponentName getActivityClassForToken(IBinder token) {
3625 synchronized (mGlobalLock) {
3626 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3627 if (r == null) {
3628 return null;
3629 }
3630 return r.intent.getComponent();
3631 }
3632 }
3633
3634 @Override
3635 public String getPackageForToken(IBinder token) {
3636 synchronized (mGlobalLock) {
3637 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3638 if (r == null) {
3639 return null;
3640 }
3641 return r.packageName;
3642 }
3643 }
3644
3645 @Override
3646 public void showLockTaskEscapeMessage(IBinder token) {
3647 synchronized (mGlobalLock) {
3648 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3649 if (r == null) {
3650 return;
3651 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003652 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003653 }
3654 }
3655
3656 @Override
3657 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003658 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003659 final long token = Binder.clearCallingIdentity();
3660 try {
3661 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003662 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 }
3664 } finally {
3665 Binder.restoreCallingIdentity(token);
3666 }
3667 }
3668
3669 /**
3670 * Try to place task to provided position. The final position might be different depending on
3671 * current user and stacks state. The task will be moved to target stack if it's currently in
3672 * different stack.
3673 */
3674 @Override
3675 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003676 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003677 synchronized (mGlobalLock) {
3678 long ident = Binder.clearCallingIdentity();
3679 try {
3680 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3681 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003682 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683 if (task == null) {
3684 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3685 + taskId);
3686 }
3687
Wale Ogunwaled32da472018-11-16 07:19:28 -08003688 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689
3690 if (stack == null) {
3691 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3692 + stackId);
3693 }
3694 if (!stack.isActivityTypeStandardOrUndefined()) {
3695 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3696 + " the position of task " + taskId + " in/to non-standard stack");
3697 }
3698
3699 // TODO: Have the callers of this API call a separate reparent method if that is
3700 // what they intended to do vs. having this method also do reparenting.
3701 if (task.getStack() == stack) {
3702 // Change position in current stack.
3703 stack.positionChildAt(task, position);
3704 } else {
3705 // Reparent to new stack.
3706 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3707 !DEFER_RESUME, "positionTaskInStack");
3708 }
3709 } finally {
3710 Binder.restoreCallingIdentity(ident);
3711 }
3712 }
3713 }
3714
3715 @Override
3716 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3717 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3718 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3719 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3720 synchronized (mGlobalLock) {
3721 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3722 if (record == null) {
3723 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3724 + "found for: " + token);
3725 }
3726 record.setSizeConfigurations(horizontalSizeConfiguration,
3727 verticalSizeConfigurations, smallestSizeConfigurations);
3728 }
3729 }
3730
3731 /**
3732 * Dismisses split-screen multi-window mode.
3733 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3734 */
3735 @Override
3736 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003737 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3739 final long ident = Binder.clearCallingIdentity();
3740 try {
3741 synchronized (mGlobalLock) {
3742 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003743 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003744 if (stack == null) {
3745 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3746 return;
3747 }
3748
3749 if (toTop) {
3750 // Caller wants the current split-screen primary stack to be the top stack after
3751 // it goes fullscreen, so move it to the front.
3752 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003753 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003754 // In this case the current split-screen primary stack shouldn't be the top
3755 // stack after it goes fullscreen, but it current has focus, so we move the
3756 // focus to the top-most split-screen secondary stack next to it.
3757 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3758 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3759 if (otherStack != null) {
3760 otherStack.moveToFront("dismissSplitScreenMode_other");
3761 }
3762 }
3763
Evan Rosky10475742018-09-05 19:02:48 -07003764 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003765 }
3766 } finally {
3767 Binder.restoreCallingIdentity(ident);
3768 }
3769 }
3770
3771 /**
3772 * Dismisses Pip
3773 * @param animate True if the dismissal should be animated.
3774 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3775 * default animation duration should be used.
3776 */
3777 @Override
3778 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003779 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003780 final long ident = Binder.clearCallingIdentity();
3781 try {
3782 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003783 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003784 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003785 if (stack == null) {
3786 Slog.w(TAG, "dismissPip: pinned stack not found.");
3787 return;
3788 }
3789 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3790 throw new IllegalArgumentException("Stack: " + stack
3791 + " doesn't support animated resize.");
3792 }
3793 if (animate) {
3794 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3795 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3796 } else {
3797 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3798 }
3799 }
3800 } finally {
3801 Binder.restoreCallingIdentity(ident);
3802 }
3803 }
3804
3805 @Override
3806 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003807 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 synchronized (mGlobalLock) {
3809 mSuppressResizeConfigChanges = suppress;
3810 }
3811 }
3812
3813 /**
3814 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3815 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3816 * activity and clearing the task at the same time.
3817 */
3818 @Override
3819 // TODO: API should just be about changing windowing modes...
3820 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003821 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 "moveTasksToFullscreenStack()");
3823 synchronized (mGlobalLock) {
3824 final long origId = Binder.clearCallingIdentity();
3825 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003826 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003827 if (stack != null){
3828 if (!stack.isActivityTypeStandardOrUndefined()) {
3829 throw new IllegalArgumentException(
3830 "You can't move tasks from non-standard stacks.");
3831 }
3832 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3833 }
3834 } finally {
3835 Binder.restoreCallingIdentity(origId);
3836 }
3837 }
3838 }
3839
3840 /**
3841 * Moves the top activity in the input stackId to the pinned stack.
3842 *
3843 * @param stackId Id of stack to move the top activity to pinned stack.
3844 * @param bounds Bounds to use for pinned stack.
3845 *
3846 * @return True if the top activity of the input stack was successfully moved to the pinned
3847 * stack.
3848 */
3849 @Override
3850 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003851 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003852 "moveTopActivityToPinnedStack()");
3853 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003854 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3856 + "Device doesn't support picture-in-picture mode");
3857 }
3858
3859 long ident = Binder.clearCallingIdentity();
3860 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003861 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862 } finally {
3863 Binder.restoreCallingIdentity(ident);
3864 }
3865 }
3866 }
3867
3868 @Override
3869 public boolean isInMultiWindowMode(IBinder token) {
3870 final long origId = Binder.clearCallingIdentity();
3871 try {
3872 synchronized (mGlobalLock) {
3873 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3874 if (r == null) {
3875 return false;
3876 }
3877 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3878 return r.inMultiWindowMode();
3879 }
3880 } finally {
3881 Binder.restoreCallingIdentity(origId);
3882 }
3883 }
3884
3885 @Override
3886 public boolean isInPictureInPictureMode(IBinder token) {
3887 final long origId = Binder.clearCallingIdentity();
3888 try {
3889 synchronized (mGlobalLock) {
3890 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3891 }
3892 } finally {
3893 Binder.restoreCallingIdentity(origId);
3894 }
3895 }
3896
3897 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003898 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3899 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900 return false;
3901 }
3902
3903 // If we are animating to fullscreen then we have already dispatched the PIP mode
3904 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003905 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3906 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003907 }
3908
3909 @Override
3910 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3911 final long origId = Binder.clearCallingIdentity();
3912 try {
3913 synchronized (mGlobalLock) {
3914 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3915 "enterPictureInPictureMode", token, params);
3916
3917 // If the activity is already in picture in picture mode, then just return early
3918 if (isInPictureInPictureMode(r)) {
3919 return true;
3920 }
3921
3922 // Activity supports picture-in-picture, now check that we can enter PiP at this
3923 // point, if it is
3924 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3925 false /* beforeStopping */)) {
3926 return false;
3927 }
3928
3929 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003930 synchronized (mGlobalLock) {
3931 // Only update the saved args from the args that are set
3932 r.pictureInPictureArgs.copyOnlySet(params);
3933 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3934 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3935 // Adjust the source bounds by the insets for the transition down
3936 final Rect sourceBounds = new Rect(
3937 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003938 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003939 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003940 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003941 stack.setPictureInPictureAspectRatio(aspectRatio);
3942 stack.setPictureInPictureActions(actions);
3943 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3944 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3945 logPictureInPictureArgs(params);
3946 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003947 };
3948
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003949 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 // If the keyguard is showing or occluded, then try and dismiss it before
3951 // entering picture-in-picture (this will prompt the user to authenticate if the
3952 // device is currently locked).
3953 dismissKeyguard(token, new KeyguardDismissCallback() {
3954 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003955 public void onDismissSucceeded() {
3956 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003957 }
3958 }, null /* message */);
3959 } else {
3960 // Enter picture in picture immediately otherwise
3961 enterPipRunnable.run();
3962 }
3963 return true;
3964 }
3965 } finally {
3966 Binder.restoreCallingIdentity(origId);
3967 }
3968 }
3969
3970 @Override
3971 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3972 final long origId = Binder.clearCallingIdentity();
3973 try {
3974 synchronized (mGlobalLock) {
3975 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3976 "setPictureInPictureParams", token, params);
3977
3978 // Only update the saved args from the args that are set
3979 r.pictureInPictureArgs.copyOnlySet(params);
3980 if (r.inPinnedWindowingMode()) {
3981 // If the activity is already in picture-in-picture, update the pinned stack now
3982 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3983 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003984 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 if (!stack.isAnimatingBoundsToFullscreen()) {
3986 stack.setPictureInPictureAspectRatio(
3987 r.pictureInPictureArgs.getAspectRatio());
3988 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3989 }
3990 }
3991 logPictureInPictureArgs(params);
3992 }
3993 } finally {
3994 Binder.restoreCallingIdentity(origId);
3995 }
3996 }
3997
3998 @Override
3999 public int getMaxNumPictureInPictureActions(IBinder token) {
4000 // Currently, this is a static constant, but later, we may change this to be dependent on
4001 // the context of the activity
4002 return 3;
4003 }
4004
4005 private void logPictureInPictureArgs(PictureInPictureParams params) {
4006 if (params.hasSetActions()) {
4007 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4008 params.getActions().size());
4009 }
4010 if (params.hasSetAspectRatio()) {
4011 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4012 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4013 MetricsLogger.action(lm);
4014 }
4015 }
4016
4017 /**
4018 * Checks the state of the system and the activity associated with the given {@param token} to
4019 * verify that picture-in-picture is supported for that activity.
4020 *
4021 * @return the activity record for the given {@param token} if all the checks pass.
4022 */
4023 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4024 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004025 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004026 throw new IllegalStateException(caller
4027 + ": Device doesn't support picture-in-picture mode.");
4028 }
4029
4030 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4031 if (r == null) {
4032 throw new IllegalStateException(caller
4033 + ": Can't find activity for token=" + token);
4034 }
4035
4036 if (!r.supportsPictureInPicture()) {
4037 throw new IllegalStateException(caller
4038 + ": Current activity does not support picture-in-picture.");
4039 }
4040
4041 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004042 && !mWindowManager.isValidPictureInPictureAspectRatio(
4043 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 final float minAspectRatio = mContext.getResources().getFloat(
4045 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4046 final float maxAspectRatio = mContext.getResources().getFloat(
4047 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4048 throw new IllegalArgumentException(String.format(caller
4049 + ": Aspect ratio is too extreme (must be between %f and %f).",
4050 minAspectRatio, maxAspectRatio));
4051 }
4052
4053 // Truncate the number of actions if necessary
4054 params.truncateActions(getMaxNumPictureInPictureActions(token));
4055
4056 return r;
4057 }
4058
4059 @Override
4060 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004061 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 synchronized (mGlobalLock) {
4063 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4064 if (r == null) {
4065 throw new IllegalArgumentException("Activity does not exist; token="
4066 + activityToken);
4067 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004068 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004069 }
4070 }
4071
4072 @Override
4073 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4074 Rect tempDockedTaskInsetBounds,
4075 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004076 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004077 long ident = Binder.clearCallingIdentity();
4078 try {
4079 synchronized (mGlobalLock) {
4080 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4081 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4082 PRESERVE_WINDOWS);
4083 }
4084 } finally {
4085 Binder.restoreCallingIdentity(ident);
4086 }
4087 }
4088
4089 @Override
4090 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004091 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004092 final long ident = Binder.clearCallingIdentity();
4093 try {
4094 synchronized (mGlobalLock) {
4095 mStackSupervisor.setSplitScreenResizing(resizing);
4096 }
4097 } finally {
4098 Binder.restoreCallingIdentity(ident);
4099 }
4100 }
4101
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004102 /**
4103 * Check that we have the features required for VR-related API calls, and throw an exception if
4104 * not.
4105 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004106 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004107 if (!mContext.getPackageManager().hasSystemFeature(
4108 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4109 throw new UnsupportedOperationException("VR mode not supported on this device!");
4110 }
4111 }
4112
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 @Override
4114 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004115 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116
4117 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4118
4119 ActivityRecord r;
4120 synchronized (mGlobalLock) {
4121 r = ActivityRecord.isInStackLocked(token);
4122 }
4123
4124 if (r == null) {
4125 throw new IllegalArgumentException();
4126 }
4127
4128 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004129 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 VrManagerInternal.NO_ERROR) {
4131 return err;
4132 }
4133
4134 // Clear the binder calling uid since this path may call moveToTask().
4135 final long callingId = Binder.clearCallingIdentity();
4136 try {
4137 synchronized (mGlobalLock) {
4138 r.requestedVrComponent = (enabled) ? packageName : null;
4139
4140 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004141 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004142 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 }
4144 return 0;
4145 }
4146 } finally {
4147 Binder.restoreCallingIdentity(callingId);
4148 }
4149 }
4150
4151 @Override
4152 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4153 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4154 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004155 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4157 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4158 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004159 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 || activity.voiceSession != null) {
4161 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4162 return;
4163 }
4164 if (activity.pendingVoiceInteractionStart) {
4165 Slog.w(TAG, "Pending start of voice interaction already.");
4166 return;
4167 }
4168 activity.pendingVoiceInteractionStart = true;
4169 }
4170 LocalServices.getService(VoiceInteractionManagerInternal.class)
4171 .startLocalVoiceInteraction(callingActivity, options);
4172 }
4173
4174 @Override
4175 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4176 LocalServices.getService(VoiceInteractionManagerInternal.class)
4177 .stopLocalVoiceInteraction(callingActivity);
4178 }
4179
4180 @Override
4181 public boolean supportsLocalVoiceInteraction() {
4182 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4183 .supportsLocalVoiceInteraction();
4184 }
4185
4186 /** Notifies all listeners when the pinned stack animation starts. */
4187 @Override
4188 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004189 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004190 }
4191
4192 /** Notifies all listeners when the pinned stack animation ends. */
4193 @Override
4194 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004195 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004196 }
4197
4198 @Override
4199 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004200 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201 final long ident = Binder.clearCallingIdentity();
4202 try {
4203 synchronized (mGlobalLock) {
4204 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4205 }
4206 } finally {
4207 Binder.restoreCallingIdentity(ident);
4208 }
4209 }
4210
4211 @Override
4212 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004213 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004214
4215 synchronized (mGlobalLock) {
4216 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004217 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 // Call might come when display is not yet added or has already been removed.
4219 if (DEBUG_CONFIGURATION) {
4220 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4221 + displayId);
4222 }
4223 return false;
4224 }
4225
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004226 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004228 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 }
4230
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004231 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004232 final Message msg = PooledLambda.obtainMessage(
4233 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4234 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004235 }
4236
4237 final long origId = Binder.clearCallingIdentity();
4238 try {
4239 if (values != null) {
4240 Settings.System.clearConfiguration(values);
4241 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4244 return mTmpUpdateConfigurationResult.changes != 0;
4245 } finally {
4246 Binder.restoreCallingIdentity(origId);
4247 }
4248 }
4249 }
4250
4251 @Override
4252 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254
4255 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004258 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 }
4260
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004262 final Message msg = PooledLambda.obtainMessage(
4263 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4264 DEFAULT_DISPLAY);
4265 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 }
4267
4268 final long origId = Binder.clearCallingIdentity();
4269 try {
4270 if (values != null) {
4271 Settings.System.clearConfiguration(values);
4272 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 UserHandle.USER_NULL, false /* deferResume */,
4275 mTmpUpdateConfigurationResult);
4276 return mTmpUpdateConfigurationResult.changes != 0;
4277 } finally {
4278 Binder.restoreCallingIdentity(origId);
4279 }
4280 }
4281 }
4282
4283 @Override
4284 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4285 CharSequence message) {
4286 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4289 }
4290 final long callingId = Binder.clearCallingIdentity();
4291 try {
4292 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004293 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 }
4295 } finally {
4296 Binder.restoreCallingIdentity(callingId);
4297 }
4298 }
4299
4300 @Override
4301 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004302 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 "cancelTaskWindowTransition()");
4304 final long ident = Binder.clearCallingIdentity();
4305 try {
4306 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004307 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 MATCH_TASK_IN_STACKS_ONLY);
4309 if (task == null) {
4310 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4311 return;
4312 }
4313 task.cancelWindowTransition();
4314 }
4315 } finally {
4316 Binder.restoreCallingIdentity(ident);
4317 }
4318 }
4319
4320 @Override
4321 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004322 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 final long ident = Binder.clearCallingIdentity();
4324 try {
4325 final TaskRecord task;
4326 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004327 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4329 if (task == null) {
4330 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4331 return null;
4332 }
4333 }
4334 // Don't call this while holding the lock as this operation might hit the disk.
4335 return task.getSnapshot(reducedResolution);
4336 } finally {
4337 Binder.restoreCallingIdentity(ident);
4338 }
4339 }
4340
4341 @Override
4342 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4343 synchronized (mGlobalLock) {
4344 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4345 if (r == null) {
4346 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4347 + token);
4348 return;
4349 }
4350 final long origId = Binder.clearCallingIdentity();
4351 try {
4352 r.setDisablePreviewScreenshots(disable);
4353 } finally {
4354 Binder.restoreCallingIdentity(origId);
4355 }
4356 }
4357 }
4358
4359 /** Return the user id of the last resumed activity. */
4360 @Override
4361 public @UserIdInt
4362 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004363 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4365 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004366 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004367 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004369 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 }
4371 }
4372
4373 @Override
4374 public void updateLockTaskFeatures(int userId, int flags) {
4375 final int callingUid = Binder.getCallingUid();
4376 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004377 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 "updateLockTaskFeatures()");
4379 }
4380 synchronized (mGlobalLock) {
4381 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4382 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004383 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384 }
4385 }
4386
4387 @Override
4388 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4389 synchronized (mGlobalLock) {
4390 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4391 if (r == null) {
4392 return;
4393 }
4394 final long origId = Binder.clearCallingIdentity();
4395 try {
4396 r.setShowWhenLocked(showWhenLocked);
4397 } finally {
4398 Binder.restoreCallingIdentity(origId);
4399 }
4400 }
4401 }
4402
4403 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004404 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4405 synchronized (mGlobalLock) {
4406 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4407 if (r == null) {
4408 return;
4409 }
4410 final long origId = Binder.clearCallingIdentity();
4411 try {
4412 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4413 } finally {
4414 Binder.restoreCallingIdentity(origId);
4415 }
4416 }
4417 }
4418
4419 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4421 synchronized (mGlobalLock) {
4422 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4423 if (r == null) {
4424 return;
4425 }
4426 final long origId = Binder.clearCallingIdentity();
4427 try {
4428 r.setTurnScreenOn(turnScreenOn);
4429 } finally {
4430 Binder.restoreCallingIdentity(origId);
4431 }
4432 }
4433 }
4434
4435 @Override
4436 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 "registerRemoteAnimations");
4439 definition.setCallingPid(Binder.getCallingPid());
4440 synchronized (mGlobalLock) {
4441 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4442 if (r == null) {
4443 return;
4444 }
4445 final long origId = Binder.clearCallingIdentity();
4446 try {
4447 r.registerRemoteAnimations(definition);
4448 } finally {
4449 Binder.restoreCallingIdentity(origId);
4450 }
4451 }
4452 }
4453
4454 @Override
4455 public void registerRemoteAnimationForNextActivityStart(String packageName,
4456 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 "registerRemoteAnimationForNextActivityStart");
4459 adapter.setCallingPid(Binder.getCallingPid());
4460 synchronized (mGlobalLock) {
4461 final long origId = Binder.clearCallingIdentity();
4462 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004463 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004464 packageName, adapter);
4465 } finally {
4466 Binder.restoreCallingIdentity(origId);
4467 }
4468 }
4469 }
4470
Evan Rosky966759f2019-01-15 10:33:58 -08004471 @Override
4472 public void registerRemoteAnimationsForDisplay(int displayId,
4473 RemoteAnimationDefinition definition) {
4474 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4475 "registerRemoteAnimations");
4476 definition.setCallingPid(Binder.getCallingPid());
4477 synchronized (mGlobalLock) {
4478 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4479 if (display == null) {
4480 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4481 return;
4482 }
4483 final long origId = Binder.clearCallingIdentity();
4484 try {
4485 display.mDisplayContent.registerRemoteAnimations(definition);
4486 } finally {
4487 Binder.restoreCallingIdentity(origId);
4488 }
4489 }
4490 }
4491
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4493 @Override
4494 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4495 synchronized (mGlobalLock) {
4496 final long origId = Binder.clearCallingIdentity();
4497 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004498 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004499 } finally {
4500 Binder.restoreCallingIdentity(origId);
4501 }
4502 }
4503 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004504
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004505 @Override
4506 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004508 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004509 final int pid = Binder.getCallingPid();
4510 final WindowProcessController wpc = mPidMap.get(pid);
4511 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004512 }
4513 }
4514
4515 @Override
4516 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004517 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004518 != PERMISSION_GRANTED) {
4519 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4520 + Binder.getCallingPid()
4521 + ", uid=" + Binder.getCallingUid()
4522 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4523 Slog.w(TAG, msg);
4524 throw new SecurityException(msg);
4525 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004526 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004527 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004528 final int pid = Binder.getCallingPid();
4529 final WindowProcessController proc = mPidMap.get(pid);
4530 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004531 }
4532 }
4533
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004534 @Override
4535 public void stopAppSwitches() {
4536 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4537 synchronized (mGlobalLock) {
4538 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4539 mDidAppSwitch = false;
4540 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4541 }
4542 }
4543
4544 @Override
4545 public void resumeAppSwitches() {
4546 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4547 synchronized (mGlobalLock) {
4548 // Note that we don't execute any pending app switches... we will
4549 // let those wait until either the timeout, or the next start
4550 // activity request.
4551 mAppSwitchesAllowedTime = 0;
4552 }
4553 }
4554
4555 void onStartActivitySetDidAppSwitch() {
4556 if (mDidAppSwitch) {
4557 // This is the second allowed switch since we stopped switches, so now just generally
4558 // allow switches. Use case:
4559 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4560 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4561 // anyone to switch again).
4562 mAppSwitchesAllowedTime = 0;
4563 } else {
4564 mDidAppSwitch = true;
4565 }
4566 }
4567
4568 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004569 boolean shouldDisableNonVrUiLocked() {
4570 return mVrController.shouldDisableNonVrUiLocked();
4571 }
4572
Wale Ogunwale53783742018-09-16 10:21:51 -07004573 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004574 // VR apps are expected to run in a main display. If an app is turning on VR for
4575 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4576 // fullscreen stack before enabling VR Mode.
4577 // TODO: The goal of this code is to keep the VR app on the main display. When the
4578 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4579 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4580 // option would be a better choice here.
4581 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4582 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4583 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004584 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004585 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004586 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004587 }
4588 mH.post(() -> {
4589 if (!mVrController.onVrModeChanged(r)) {
4590 return;
4591 }
4592 synchronized (mGlobalLock) {
4593 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4594 mWindowManager.disableNonVrUi(disableNonVrUi);
4595 if (disableNonVrUi) {
4596 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4597 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004598 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004599 }
4600 }
4601 });
4602 }
4603
Wale Ogunwale53783742018-09-16 10:21:51 -07004604 @Override
4605 public int getPackageScreenCompatMode(String packageName) {
4606 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4607 synchronized (mGlobalLock) {
4608 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4609 }
4610 }
4611
4612 @Override
4613 public void setPackageScreenCompatMode(String packageName, int mode) {
4614 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4615 "setPackageScreenCompatMode");
4616 synchronized (mGlobalLock) {
4617 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4618 }
4619 }
4620
4621 @Override
4622 public boolean getPackageAskScreenCompat(String packageName) {
4623 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4624 synchronized (mGlobalLock) {
4625 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4626 }
4627 }
4628
4629 @Override
4630 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4631 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4632 "setPackageAskScreenCompat");
4633 synchronized (mGlobalLock) {
4634 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4635 }
4636 }
4637
Wale Ogunwale64258362018-10-16 15:13:37 -07004638 public static String relaunchReasonToString(int relaunchReason) {
4639 switch (relaunchReason) {
4640 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4641 return "window_resize";
4642 case RELAUNCH_REASON_FREE_RESIZE:
4643 return "free_resize";
4644 default:
4645 return null;
4646 }
4647 }
4648
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004649 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004650 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004651 }
4652
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004653 /** Pokes the task persister. */
4654 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4655 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4656 }
4657
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004658 boolean isKeyguardLocked() {
4659 return mKeyguardController.isKeyguardLocked();
4660 }
4661
Garfield Tan01548632018-11-27 10:15:48 -08004662 /**
4663 * Clears launch params for the given package.
4664 * @param packageNames the names of the packages of which the launch params are to be cleared
4665 */
4666 @Override
4667 public void clearLaunchParamsForPackages(List<String> packageNames) {
4668 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4669 "clearLaunchParamsForPackages");
4670 synchronized (mGlobalLock) {
4671 for (int i = 0; i < packageNames.size(); ++i) {
4672 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4673 }
4674 }
4675 }
4676
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004677 /**
4678 * Makes the display with the given id a single task instance display. I.e the display can only
4679 * contain one task.
4680 */
4681 @Override
4682 public void setDisplayToSingleTaskInstance(int displayId) {
4683 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4684 "setDisplayToSingleTaskInstance");
4685 final long origId = Binder.clearCallingIdentity();
4686 try {
4687 final ActivityDisplay display =
4688 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4689 if (display != null) {
4690 display.setDisplayToSingleTaskInstance();
4691 }
4692 } finally {
4693 Binder.restoreCallingIdentity(origId);
4694 }
4695 }
4696
Wale Ogunwale31913b52018-10-13 08:29:31 -07004697 void dumpLastANRLocked(PrintWriter pw) {
4698 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4699 if (mLastANRState == null) {
4700 pw.println(" <no ANR has occurred since boot>");
4701 } else {
4702 pw.println(mLastANRState);
4703 }
4704 }
4705
4706 void dumpLastANRTracesLocked(PrintWriter pw) {
4707 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4708
4709 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4710 if (ArrayUtils.isEmpty(files)) {
4711 pw.println(" <no ANR has occurred since boot>");
4712 return;
4713 }
4714 // Find the latest file.
4715 File latest = null;
4716 for (File f : files) {
4717 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4718 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004719 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004720 }
4721 pw.print("File: ");
4722 pw.print(latest.getName());
4723 pw.println();
4724 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4725 String line;
4726 while ((line = in.readLine()) != null) {
4727 pw.println(line);
4728 }
4729 } catch (IOException e) {
4730 pw.print("Unable to read: ");
4731 pw.print(e);
4732 pw.println();
4733 }
4734 }
4735
4736 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4737 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4738 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4739 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4740 }
4741
4742 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4743 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4744 pw.println(header);
4745
Wale Ogunwaled32da472018-11-16 07:19:28 -08004746 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004747 dumpPackage);
4748 boolean needSep = printedAnything;
4749
4750 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004751 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004752 " ResumedActivity: ");
4753 if (printed) {
4754 printedAnything = true;
4755 needSep = false;
4756 }
4757
4758 if (dumpPackage == null) {
4759 if (needSep) {
4760 pw.println();
4761 }
4762 printedAnything = true;
4763 mStackSupervisor.dump(pw, " ");
4764 }
4765
4766 if (!printedAnything) {
4767 pw.println(" (nothing)");
4768 }
4769 }
4770
4771 void dumpActivityContainersLocked(PrintWriter pw) {
4772 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004773 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004774 pw.println(" ");
4775 }
4776
4777 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4778 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4779 getActivityStartController().dump(pw, "", dumpPackage);
4780 }
4781
4782 /**
4783 * There are three things that cmd can be:
4784 * - a flattened component name that matches an existing activity
4785 * - the cmd arg isn't the flattened component name of an existing activity:
4786 * dump all activity whose component contains the cmd as a substring
4787 * - A hex number of the ActivityRecord object instance.
4788 *
4789 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4790 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4791 */
4792 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4793 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4794 ArrayList<ActivityRecord> activities;
4795
4796 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004797 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004798 dumpFocusedStackOnly);
4799 }
4800
4801 if (activities.size() <= 0) {
4802 return false;
4803 }
4804
4805 String[] newArgs = new String[args.length - opti];
4806 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4807
4808 TaskRecord lastTask = null;
4809 boolean needSep = false;
4810 for (int i = activities.size() - 1; i >= 0; i--) {
4811 ActivityRecord r = activities.get(i);
4812 if (needSep) {
4813 pw.println();
4814 }
4815 needSep = true;
4816 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004817 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004818 if (lastTask != task) {
4819 lastTask = task;
4820 pw.print("TASK "); pw.print(lastTask.affinity);
4821 pw.print(" id="); pw.print(lastTask.taskId);
4822 pw.print(" userId="); pw.println(lastTask.userId);
4823 if (dumpAll) {
4824 lastTask.dump(pw, " ");
4825 }
4826 }
4827 }
4828 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4829 }
4830 return true;
4831 }
4832
4833 /**
4834 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4835 * there is a thread associated with the activity.
4836 */
4837 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4838 final ActivityRecord r, String[] args, boolean dumpAll) {
4839 String innerPrefix = prefix + " ";
4840 synchronized (mGlobalLock) {
4841 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4842 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4843 pw.print(" pid=");
4844 if (r.hasProcess()) pw.println(r.app.getPid());
4845 else pw.println("(not running)");
4846 if (dumpAll) {
4847 r.dump(pw, innerPrefix);
4848 }
4849 }
4850 if (r.attachedToProcess()) {
4851 // flush anything that is already in the PrintWriter since the thread is going
4852 // to write to the file descriptor directly
4853 pw.flush();
4854 try {
4855 TransferPipe tp = new TransferPipe();
4856 try {
4857 r.app.getThread().dumpActivity(tp.getWriteFd(),
4858 r.appToken, innerPrefix, args);
4859 tp.go(fd);
4860 } finally {
4861 tp.kill();
4862 }
4863 } catch (IOException e) {
4864 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4865 } catch (RemoteException e) {
4866 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4867 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004868 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004869 }
4870
sanryhuang498e77e2018-12-06 14:57:01 +08004871 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4872 boolean testPssMode) {
4873 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4874 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4875 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004876 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004877 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4878 st.toString());
4879 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004880 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4881 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4882 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004883 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4884 testPssMode);
4885 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004886 }
4887
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004888 int getCurrentUserId() {
4889 return mAmInternal.getCurrentUserId();
4890 }
4891
4892 private void enforceNotIsolatedCaller(String caller) {
4893 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4894 throw new SecurityException("Isolated process not allowed to call " + caller);
4895 }
4896 }
4897
Wale Ogunwalef6733932018-06-27 05:14:34 -07004898 public Configuration getConfiguration() {
4899 Configuration ci;
4900 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004901 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004902 ci.userSetLocale = false;
4903 }
4904 return ci;
4905 }
4906
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004907 /**
4908 * Current global configuration information. Contains general settings for the entire system,
4909 * also corresponds to the merged configuration of the default display.
4910 */
4911 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004912 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004913 }
4914
4915 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4916 boolean initLocale) {
4917 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4918 }
4919
4920 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4921 boolean initLocale, boolean deferResume) {
4922 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4923 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4924 UserHandle.USER_NULL, deferResume);
4925 }
4926
Wale Ogunwale59507092018-10-29 09:00:30 -07004927 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004928 final long origId = Binder.clearCallingIdentity();
4929 try {
4930 synchronized (mGlobalLock) {
4931 updateConfigurationLocked(values, null, false, true, userId,
4932 false /* deferResume */);
4933 }
4934 } finally {
4935 Binder.restoreCallingIdentity(origId);
4936 }
4937 }
4938
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004939 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4940 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4941 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4942 deferResume, null /* result */);
4943 }
4944
4945 /**
4946 * Do either or both things: (1) change the current configuration, and (2)
4947 * make sure the given activity is running with the (now) current
4948 * configuration. Returns true if the activity has been left running, or
4949 * false if <var>starting</var> is being destroyed to match the new
4950 * configuration.
4951 *
4952 * @param userId is only used when persistent parameter is set to true to persist configuration
4953 * for that particular user
4954 */
4955 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4956 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4957 ActivityTaskManagerService.UpdateConfigurationResult result) {
4958 int changes = 0;
4959 boolean kept = true;
4960
4961 if (mWindowManager != null) {
4962 mWindowManager.deferSurfaceLayout();
4963 }
4964 try {
4965 if (values != null) {
4966 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4967 deferResume);
4968 }
4969
4970 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4971 } finally {
4972 if (mWindowManager != null) {
4973 mWindowManager.continueSurfaceLayout();
4974 }
4975 }
4976
4977 if (result != null) {
4978 result.changes = changes;
4979 result.activityRelaunched = !kept;
4980 }
4981 return kept;
4982 }
4983
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004984 /** Update default (global) configuration and notify listeners about changes. */
4985 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4986 boolean persistent, int userId, boolean deferResume) {
4987 mTempConfig.setTo(getGlobalConfiguration());
4988 final int changes = mTempConfig.updateFrom(values);
4989 if (changes == 0) {
4990 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4991 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4992 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4993 // (even if there are no actual changes) to unfreeze the window.
4994 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4995 return 0;
4996 }
4997
4998 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4999 "Updating global configuration to: " + values);
5000
5001 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5002 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5003 values.colorMode,
5004 values.densityDpi,
5005 values.fontScale,
5006 values.hardKeyboardHidden,
5007 values.keyboard,
5008 values.keyboardHidden,
5009 values.mcc,
5010 values.mnc,
5011 values.navigation,
5012 values.navigationHidden,
5013 values.orientation,
5014 values.screenHeightDp,
5015 values.screenLayout,
5016 values.screenWidthDp,
5017 values.smallestScreenWidthDp,
5018 values.touchscreen,
5019 values.uiMode);
5020
5021
5022 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5023 final LocaleList locales = values.getLocales();
5024 int bestLocaleIndex = 0;
5025 if (locales.size() > 1) {
5026 if (mSupportedSystemLocales == null) {
5027 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5028 }
5029 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5030 }
5031 SystemProperties.set("persist.sys.locale",
5032 locales.get(bestLocaleIndex).toLanguageTag());
5033 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005034
5035 final Message m = PooledLambda.obtainMessage(
5036 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5037 locales.get(bestLocaleIndex));
5038 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005039 }
5040
Yunfan Chen75157d72018-07-27 14:47:21 +09005041 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005042
5043 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005044 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005045
5046 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5047 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005048 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005049
5050 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005051 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005052
5053 AttributeCache ac = AttributeCache.instance();
5054 if (ac != null) {
5055 ac.updateConfiguration(mTempConfig);
5056 }
5057
5058 // Make sure all resources in our process are updated right now, so that anyone who is going
5059 // to retrieve resource values after we return will be sure to get the new ones. This is
5060 // especially important during boot, where the first config change needs to guarantee all
5061 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005062 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005063
5064 // We need another copy of global config because we're scheduling some calls instead of
5065 // running them in place. We need to be sure that object we send will be handled unchanged.
5066 final Configuration configCopy = new Configuration(mTempConfig);
5067 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005068 final Message msg = PooledLambda.obtainMessage(
5069 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5070 this, userId, configCopy);
5071 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072 }
5073
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005074 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005075 final int pid = mPidMap.keyAt(i);
5076 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005077 if (DEBUG_CONFIGURATION) {
5078 Slog.v(TAG_CONFIGURATION, "Update process config of "
5079 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005080 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005081 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005082 }
5083
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005084 final Message msg = PooledLambda.obtainMessage(
5085 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5086 mAmInternal, changes, initLocale);
5087 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005088
5089 // Override configuration of the default display duplicates global config, so we need to
5090 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005091 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005092 DEFAULT_DISPLAY);
5093
5094 return changes;
5095 }
5096
5097 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5098 boolean deferResume, int displayId) {
5099 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5100 displayId, null /* result */);
5101 }
5102
5103 /**
5104 * Updates override configuration specific for the selected display. If no config is provided,
5105 * new one will be computed in WM based on current display info.
5106 */
5107 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5108 ActivityRecord starting, boolean deferResume, int displayId,
5109 ActivityTaskManagerService.UpdateConfigurationResult result) {
5110 int changes = 0;
5111 boolean kept = true;
5112
5113 if (mWindowManager != null) {
5114 mWindowManager.deferSurfaceLayout();
5115 }
5116 try {
5117 if (values != null) {
5118 if (displayId == DEFAULT_DISPLAY) {
5119 // Override configuration of the default display duplicates global config, so
5120 // we're calling global config update instead for default display. It will also
5121 // apply the correct override config.
5122 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5123 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5124 } else {
5125 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5126 }
5127 }
5128
5129 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5130 } finally {
5131 if (mWindowManager != null) {
5132 mWindowManager.continueSurfaceLayout();
5133 }
5134 }
5135
5136 if (result != null) {
5137 result.changes = changes;
5138 result.activityRelaunched = !kept;
5139 }
5140 return kept;
5141 }
5142
5143 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5144 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005145 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005146 final int changes = mTempConfig.updateFrom(values);
5147 if (changes != 0) {
5148 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5149 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005150 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005151
5152 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5153 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005154 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005155
Wale Ogunwale5c918702018-10-18 11:06:33 -07005156 // Post message to start process to avoid possible deadlock of calling into AMS with
5157 // the ATMS lock held.
5158 final Message msg = PooledLambda.obtainMessage(
5159 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5160 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5161 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 }
5163 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164 return changes;
5165 }
5166
Wale Ogunwalef6733932018-06-27 05:14:34 -07005167 private void updateEventDispatchingLocked(boolean booted) {
5168 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5169 }
5170
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005171 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5172 final ContentResolver resolver = mContext.getContentResolver();
5173 Settings.System.putConfigurationForUser(resolver, config, userId);
5174 }
5175
5176 private void sendLocaleToMountDaemonMsg(Locale l) {
5177 try {
5178 IBinder service = ServiceManager.getService("mount");
5179 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5180 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5181 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5182 } catch (RemoteException e) {
5183 Log.e(TAG, "Error storing locale for decryption UI", e);
5184 }
5185 }
5186
Alison Cichowlas3e340502018-08-07 17:15:01 -04005187 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5188 mStartActivitySources.remove(permissionToken);
5189 mExpiredStartAsCallerTokens.add(permissionToken);
5190 }
5191
5192 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5193 mExpiredStartAsCallerTokens.remove(permissionToken);
5194 }
5195
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005196 boolean isActivityStartsLoggingEnabled() {
5197 return mAmInternal.isActivityStartsLoggingEnabled();
5198 }
5199
Michal Karpinski8596ded2018-11-14 14:43:48 +00005200 boolean isBackgroundActivityStartsEnabled() {
5201 return mAmInternal.isBackgroundActivityStartsEnabled();
5202 }
5203
Wale Ogunwalef6733932018-06-27 05:14:34 -07005204 void enableScreenAfterBoot(boolean booted) {
5205 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5206 SystemClock.uptimeMillis());
5207 mWindowManager.enableScreenAfterBoot();
5208
5209 synchronized (mGlobalLock) {
5210 updateEventDispatchingLocked(booted);
5211 }
5212 }
5213
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005214 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5215 if (r == null || !r.hasProcess()) {
5216 return KEY_DISPATCHING_TIMEOUT_MS;
5217 }
5218 return getInputDispatchingTimeoutLocked(r.app);
5219 }
5220
5221 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005222 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005223 }
5224
Wale Ogunwalef6733932018-06-27 05:14:34 -07005225 /**
5226 * Decide based on the configuration whether we should show the ANR,
5227 * crash, etc dialogs. The idea is that if there is no affordance to
5228 * press the on-screen buttons, or the user experience would be more
5229 * greatly impacted than the crash itself, we shouldn't show the dialog.
5230 *
5231 * A thought: SystemUI might also want to get told about this, the Power
5232 * dialog / global actions also might want different behaviors.
5233 */
5234 private void updateShouldShowDialogsLocked(Configuration config) {
5235 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5236 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5237 && config.navigation == Configuration.NAVIGATION_NONAV);
5238 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5239 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5240 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5241 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5242 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5243 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5244 HIDE_ERROR_DIALOGS, 0) != 0;
5245 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5246 }
5247
5248 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5249 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5250 FONT_SCALE, 1.0f, userId);
5251
5252 synchronized (this) {
5253 if (getGlobalConfiguration().fontScale == scaleFactor) {
5254 return;
5255 }
5256
5257 final Configuration configuration
5258 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5259 configuration.fontScale = scaleFactor;
5260 updatePersistentConfiguration(configuration, userId);
5261 }
5262 }
5263
5264 // Actually is sleeping or shutting down or whatever else in the future
5265 // is an inactive state.
5266 boolean isSleepingOrShuttingDownLocked() {
5267 return isSleepingLocked() || mShuttingDown;
5268 }
5269
5270 boolean isSleepingLocked() {
5271 return mSleeping;
5272 }
5273
Riddle Hsu16567132018-08-16 21:37:47 +08005274 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005275 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005276 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005277 if (task.isActivityTypeStandard()) {
5278 if (mCurAppTimeTracker != r.appTimeTracker) {
5279 // We are switching app tracking. Complete the current one.
5280 if (mCurAppTimeTracker != null) {
5281 mCurAppTimeTracker.stop();
5282 mH.obtainMessage(
5283 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005284 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005285 mCurAppTimeTracker = null;
5286 }
5287 if (r.appTimeTracker != null) {
5288 mCurAppTimeTracker = r.appTimeTracker;
5289 startTimeTrackingFocusedActivityLocked();
5290 }
5291 } else {
5292 startTimeTrackingFocusedActivityLocked();
5293 }
5294 } else {
5295 r.appTimeTracker = null;
5296 }
5297 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5298 // TODO: Probably not, because we don't want to resume voice on switching
5299 // back to this activity
5300 if (task.voiceInteractor != null) {
5301 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5302 } else {
5303 finishRunningVoiceLocked();
5304
5305 if (mLastResumedActivity != null) {
5306 final IVoiceInteractionSession session;
5307
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005308 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005309 if (lastResumedActivityTask != null
5310 && lastResumedActivityTask.voiceSession != null) {
5311 session = lastResumedActivityTask.voiceSession;
5312 } else {
5313 session = mLastResumedActivity.voiceSession;
5314 }
5315
5316 if (session != null) {
5317 // We had been in a voice interaction session, but now focused has
5318 // move to something different. Just finish the session, we can't
5319 // return to it and retain the proper state and synchronization with
5320 // the voice interaction service.
5321 finishVoiceTask(session);
5322 }
5323 }
5324 }
5325
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005326 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5327 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005328 }
5329 updateResumedAppTrace(r);
5330 mLastResumedActivity = r;
5331
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005332 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005333
5334 applyUpdateLockStateLocked(r);
5335 applyUpdateVrModeLocked(r);
5336
5337 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005338 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005339 r == null ? "NULL" : r.shortComponentName,
5340 reason);
5341 }
5342
5343 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5344 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005345 final ActivityTaskManagerInternal.SleepToken token =
5346 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005347 updateSleepIfNeededLocked();
5348 return token;
5349 }
5350 }
5351
5352 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005353 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005354 final boolean wasSleeping = mSleeping;
5355 boolean updateOomAdj = false;
5356
5357 if (!shouldSleep) {
5358 // If wasSleeping is true, we need to wake up activity manager state from when
5359 // we started sleeping. In either case, we need to apply the sleep tokens, which
5360 // will wake up stacks or put them to sleep as appropriate.
5361 if (wasSleeping) {
5362 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005363 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5364 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005365 startTimeTrackingFocusedActivityLocked();
5366 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5367 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5368 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005369 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005370 if (wasSleeping) {
5371 updateOomAdj = true;
5372 }
5373 } else if (!mSleeping && shouldSleep) {
5374 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005375 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5376 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005377 if (mCurAppTimeTracker != null) {
5378 mCurAppTimeTracker.stop();
5379 }
5380 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5381 mStackSupervisor.goingToSleepLocked();
5382 updateResumedAppTrace(null /* resumed */);
5383 updateOomAdj = true;
5384 }
5385 if (updateOomAdj) {
5386 mH.post(mAmInternal::updateOomAdj);
5387 }
5388 }
5389
5390 void updateOomAdj() {
5391 mH.post(mAmInternal::updateOomAdj);
5392 }
5393
Wale Ogunwale53783742018-09-16 10:21:51 -07005394 void updateCpuStats() {
5395 mH.post(mAmInternal::updateCpuStats);
5396 }
5397
Hui Yu03d12402018-12-06 18:00:37 -08005398 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5399 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005400 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5401 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005402 mH.sendMessage(m);
5403 }
5404
Hui Yu03d12402018-12-06 18:00:37 -08005405 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005406 ComponentName taskRoot = null;
5407 final TaskRecord task = activity.getTaskRecord();
5408 if (task != null) {
5409 final ActivityRecord rootActivity = task.getRootActivity();
5410 if (rootActivity != null) {
5411 taskRoot = rootActivity.mActivityComponent;
5412 }
5413 }
5414
Hui Yu03d12402018-12-06 18:00:37 -08005415 final Message m = PooledLambda.obtainMessage(
5416 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005417 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005418 mH.sendMessage(m);
5419 }
5420
Wale Ogunwale53783742018-09-16 10:21:51 -07005421 void setBooting(boolean booting) {
5422 mAmInternal.setBooting(booting);
5423 }
5424
5425 boolean isBooting() {
5426 return mAmInternal.isBooting();
5427 }
5428
5429 void setBooted(boolean booted) {
5430 mAmInternal.setBooted(booted);
5431 }
5432
5433 boolean isBooted() {
5434 return mAmInternal.isBooted();
5435 }
5436
5437 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5438 mH.post(() -> {
5439 if (finishBooting) {
5440 mAmInternal.finishBooting();
5441 }
5442 if (enableScreen) {
5443 mInternal.enableScreenAfterBoot(isBooted());
5444 }
5445 });
5446 }
5447
5448 void setHeavyWeightProcess(ActivityRecord root) {
5449 mHeavyWeightProcess = root.app;
5450 final Message m = PooledLambda.obtainMessage(
5451 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005452 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005453 mH.sendMessage(m);
5454 }
5455
5456 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5457 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5458 return;
5459 }
5460
5461 mHeavyWeightProcess = null;
5462 final Message m = PooledLambda.obtainMessage(
5463 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5464 proc.mUserId);
5465 mH.sendMessage(m);
5466 }
5467
5468 private void cancelHeavyWeightProcessNotification(int userId) {
5469 final INotificationManager inm = NotificationManager.getService();
5470 if (inm == null) {
5471 return;
5472 }
5473 try {
5474 inm.cancelNotificationWithTag("android", null,
5475 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5476 } catch (RuntimeException e) {
5477 Slog.w(TAG, "Error canceling notification for service", e);
5478 } catch (RemoteException e) {
5479 }
5480
5481 }
5482
5483 private void postHeavyWeightProcessNotification(
5484 WindowProcessController proc, Intent intent, int userId) {
5485 if (proc == null) {
5486 return;
5487 }
5488
5489 final INotificationManager inm = NotificationManager.getService();
5490 if (inm == null) {
5491 return;
5492 }
5493
5494 try {
5495 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5496 String text = mContext.getString(R.string.heavy_weight_notification,
5497 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5498 Notification notification =
5499 new Notification.Builder(context,
5500 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5501 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5502 .setWhen(0)
5503 .setOngoing(true)
5504 .setTicker(text)
5505 .setColor(mContext.getColor(
5506 com.android.internal.R.color.system_notification_accent_color))
5507 .setContentTitle(text)
5508 .setContentText(
5509 mContext.getText(R.string.heavy_weight_notification_detail))
5510 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5511 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5512 new UserHandle(userId)))
5513 .build();
5514 try {
5515 inm.enqueueNotificationWithTag("android", "android", null,
5516 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5517 } catch (RuntimeException e) {
5518 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5519 } catch (RemoteException e) {
5520 }
5521 } catch (PackageManager.NameNotFoundException e) {
5522 Slog.w(TAG, "Unable to create context for heavy notification", e);
5523 }
5524
5525 }
5526
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005527 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5528 IBinder token, String resultWho, int requestCode, Intent[] intents,
5529 String[] resolvedTypes, int flags, Bundle bOptions) {
5530
5531 ActivityRecord activity = null;
5532 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5533 activity = ActivityRecord.isInStackLocked(token);
5534 if (activity == null) {
5535 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5536 return null;
5537 }
5538 if (activity.finishing) {
5539 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5540 return null;
5541 }
5542 }
5543
5544 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5545 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5546 bOptions);
5547 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5548 if (noCreate) {
5549 return rec;
5550 }
5551 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5552 if (activity.pendingResults == null) {
5553 activity.pendingResults = new HashSet<>();
5554 }
5555 activity.pendingResults.add(rec.ref);
5556 }
5557 return rec;
5558 }
5559
Andrii Kulian52d255c2018-07-13 11:32:19 -07005560 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005561 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005562 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5564 mCurAppTimeTracker.start(resumedActivity.packageName);
5565 }
5566 }
5567
5568 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5569 if (mTracedResumedActivity != null) {
5570 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5571 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5572 }
5573 if (resumed != null) {
5574 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5575 constructResumedTraceName(resumed.packageName), 0);
5576 }
5577 mTracedResumedActivity = resumed;
5578 }
5579
5580 private String constructResumedTraceName(String packageName) {
5581 return "focused app: " + packageName;
5582 }
5583
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005584 /** Applies latest configuration and/or visibility updates if needed. */
5585 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5586 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005587 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005588 // mainStack is null during startup.
5589 if (mainStack != null) {
5590 if (changes != 0 && starting == null) {
5591 // If the configuration changed, and the caller is not already
5592 // in the process of starting an activity, then find the top
5593 // activity to check if its configuration needs to change.
5594 starting = mainStack.topRunningActivityLocked();
5595 }
5596
5597 if (starting != null) {
5598 kept = starting.ensureActivityConfiguration(changes,
5599 false /* preserveWindow */);
5600 // And we need to make sure at this point that all other activities
5601 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005602 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005603 !PRESERVE_WINDOWS);
5604 }
5605 }
5606
5607 return kept;
5608 }
5609
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005610 void scheduleAppGcsLocked() {
5611 mH.post(() -> mAmInternal.scheduleAppGcs());
5612 }
5613
Wale Ogunwale53783742018-09-16 10:21:51 -07005614 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5615 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5616 }
5617
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005618 /**
5619 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5620 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5621 * on demand.
5622 */
5623 IPackageManager getPackageManager() {
5624 return AppGlobals.getPackageManager();
5625 }
5626
5627 PackageManagerInternal getPackageManagerInternalLocked() {
5628 if (mPmInternal == null) {
5629 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5630 }
5631 return mPmInternal;
5632 }
5633
Wale Ogunwale008163e2018-07-23 23:11:08 -07005634 AppWarnings getAppWarningsLocked() {
5635 return mAppWarnings;
5636 }
5637
Wale Ogunwale214f3482018-10-04 11:00:47 -07005638 Intent getHomeIntent() {
5639 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5640 intent.setComponent(mTopComponent);
5641 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5642 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5643 intent.addCategory(Intent.CATEGORY_HOME);
5644 }
5645 return intent;
5646 }
5647
Chilun2ef71f72018-11-16 17:57:15 +08005648 /**
5649 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5650 * activities.
5651 *
5652 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5653 * component defined in config_secondaryHomeComponent.
5654 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5655 */
5656 Intent getSecondaryHomeIntent(String preferredPackage) {
5657 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5658 if (preferredPackage == null) {
5659 // Using the component stored in config if no package name.
5660 final String secondaryHomeComponent = mContext.getResources().getString(
5661 com.android.internal.R.string.config_secondaryHomeComponent);
5662 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5663 } else {
5664 intent.setPackage(preferredPackage);
5665 }
5666 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5667 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5668 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5669 }
5670 return intent;
5671 }
5672
Wale Ogunwale214f3482018-10-04 11:00:47 -07005673 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5674 if (info == null) return null;
5675 ApplicationInfo newInfo = new ApplicationInfo(info);
5676 newInfo.initForUser(userId);
5677 return newInfo;
5678 }
5679
Wale Ogunwale9c103022018-10-18 07:44:54 -07005680 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005681 if (uid == SYSTEM_UID) {
5682 // The system gets to run in any process. If there are multiple processes with the same
5683 // uid, just pick the first (this should never happen).
5684 final SparseArray<WindowProcessController> procs =
5685 mProcessNames.getMap().get(processName);
5686 if (procs == null) return null;
5687 final int procCount = procs.size();
5688 for (int i = 0; i < procCount; i++) {
5689 final int procUid = procs.keyAt(i);
5690 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5691 // Don't use an app process or different user process for system component.
5692 continue;
5693 }
5694 return procs.valueAt(i);
5695 }
5696 }
5697
5698 return mProcessNames.get(processName, uid);
5699 }
5700
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005701 WindowProcessController getProcessController(IApplicationThread thread) {
5702 if (thread == null) {
5703 return null;
5704 }
5705
5706 final IBinder threadBinder = thread.asBinder();
5707 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5708 for (int i = pmap.size()-1; i >= 0; i--) {
5709 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5710 for (int j = procs.size() - 1; j >= 0; j--) {
5711 final WindowProcessController proc = procs.valueAt(j);
5712 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5713 return proc;
5714 }
5715 }
5716 }
5717
5718 return null;
5719 }
5720
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005721 WindowProcessController getProcessController(int pid, int uid) {
5722 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5723 for (int i = pmap.size()-1; i >= 0; i--) {
5724 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5725 for (int j = procs.size() - 1; j >= 0; j--) {
5726 final WindowProcessController proc = procs.valueAt(j);
5727 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5728 return proc;
5729 }
5730 }
5731 }
5732 return null;
5733 }
5734
Riddle Hsua0536432019-02-16 00:38:59 +08005735 int getUidState(int uid) {
5736 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005737 }
5738
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005739 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005740 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005741 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5742 }
5743
Michal Karpinski4026cae2019-02-12 11:51:47 +00005744 boolean isDeviceOwner(String packageName) {
5745 if (packageName == null) {
5746 return false;
5747 }
5748 return packageName.equals(mDeviceOwnerPackageName);
5749 }
5750
5751 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5752 mDeviceOwnerPackageName = deviceOwnerPkg;
5753 }
5754
Wale Ogunwale9de19442018-10-18 19:05:03 -07005755 /**
5756 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5757 * the whitelist
5758 */
5759 String getPendingTempWhitelistTagForUidLocked(int uid) {
5760 return mPendingTempWhitelist.get(uid);
5761 }
5762
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005763 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5764 if (true || Build.IS_USER) {
5765 return;
5766 }
5767
5768 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5769 StrictMode.allowThreadDiskWrites();
5770 try {
5771 File tracesDir = new File("/data/anr");
5772 File tracesFile = null;
5773 try {
5774 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5775
5776 StringBuilder sb = new StringBuilder();
5777 Time tobj = new Time();
5778 tobj.set(System.currentTimeMillis());
5779 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5780 sb.append(": ");
5781 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5782 sb.append(" since ");
5783 sb.append(msg);
5784 FileOutputStream fos = new FileOutputStream(tracesFile);
5785 fos.write(sb.toString().getBytes());
5786 if (app == null) {
5787 fos.write("\n*** No application process!".getBytes());
5788 }
5789 fos.close();
5790 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5791 } catch (IOException e) {
5792 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5793 return;
5794 }
5795
5796 if (app != null && app.getPid() > 0) {
5797 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5798 firstPids.add(app.getPid());
5799 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5800 }
5801
5802 File lastTracesFile = null;
5803 File curTracesFile = null;
5804 for (int i=9; i>=0; i--) {
5805 String name = String.format(Locale.US, "slow%02d.txt", i);
5806 curTracesFile = new File(tracesDir, name);
5807 if (curTracesFile.exists()) {
5808 if (lastTracesFile != null) {
5809 curTracesFile.renameTo(lastTracesFile);
5810 } else {
5811 curTracesFile.delete();
5812 }
5813 }
5814 lastTracesFile = curTracesFile;
5815 }
5816 tracesFile.renameTo(curTracesFile);
5817 } finally {
5818 StrictMode.setThreadPolicy(oldPolicy);
5819 }
5820 }
5821
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005822 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005823 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005824
5825
Wale Ogunwale98875612018-10-12 07:53:02 -07005826 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5827 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005828
Riddle Hsud93a6c42018-11-29 21:50:06 +08005829 H(Looper looper) {
5830 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005831 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005832
5833 @Override
5834 public void handleMessage(Message msg) {
5835 switch (msg.what) {
5836 case REPORT_TIME_TRACKER_MSG: {
5837 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5838 tracker.deliverResult(mContext);
5839 } break;
5840 }
5841 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005842 }
5843
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005844 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005845 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005846
5847 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005848 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005849 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005850
5851 @Override
5852 public void handleMessage(Message msg) {
5853 switch (msg.what) {
5854 case DISMISS_DIALOG_UI_MSG: {
5855 final Dialog d = (Dialog) msg.obj;
5856 d.dismiss();
5857 break;
5858 }
5859 }
5860 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005861 }
5862
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005863 final class LocalService extends ActivityTaskManagerInternal {
5864 @Override
5865 public SleepToken acquireSleepToken(String tag, int displayId) {
5866 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005867 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005868 }
5869
5870 @Override
5871 public ComponentName getHomeActivityForUser(int userId) {
5872 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005873 final ActivityRecord homeActivity =
5874 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005875 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005876 }
5877 }
5878
5879 @Override
5880 public void onLocalVoiceInteractionStarted(IBinder activity,
5881 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5882 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005883 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005884 }
5885 }
5886
5887 @Override
5888 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5889 synchronized (mGlobalLock) {
5890 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5891 reasons, timestamp);
5892 }
5893 }
5894
5895 @Override
5896 public void notifyAppTransitionFinished() {
5897 synchronized (mGlobalLock) {
5898 mStackSupervisor.notifyAppTransitionDone();
5899 }
5900 }
5901
5902 @Override
5903 public void notifyAppTransitionCancelled() {
5904 synchronized (mGlobalLock) {
5905 mStackSupervisor.notifyAppTransitionDone();
5906 }
5907 }
5908
5909 @Override
5910 public List<IBinder> getTopVisibleActivities() {
5911 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005912 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005913 }
5914 }
5915
5916 @Override
5917 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5918 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005919 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005920 }
5921 }
5922
5923 @Override
5924 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5925 Bundle bOptions) {
5926 Preconditions.checkNotNull(intents, "intents");
5927 final String[] resolvedTypes = new String[intents.length];
5928
5929 // UID of the package on user userId.
5930 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5931 // packageUid may not be initialized.
5932 int packageUid = 0;
5933 final long ident = Binder.clearCallingIdentity();
5934
5935 try {
5936 for (int i = 0; i < intents.length; i++) {
5937 resolvedTypes[i] =
5938 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5939 }
5940
5941 packageUid = AppGlobals.getPackageManager().getPackageUid(
5942 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5943 } catch (RemoteException e) {
5944 // Shouldn't happen.
5945 } finally {
5946 Binder.restoreCallingIdentity(ident);
5947 }
5948
Riddle Hsu591bf612019-02-14 17:55:31 +08005949 return getActivityStartController().startActivitiesInPackage(
5950 packageUid, packageName,
5951 intents, resolvedTypes, null /* resultTo */,
5952 SafeActivityOptions.fromBundle(bOptions), userId,
5953 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5954 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005955 }
5956
5957 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005958 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5959 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5960 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5961 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005962 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005963 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005964 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5965 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5966 userId, validateIncomingUser, originatingPendingIntent,
5967 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005968 }
5969 }
5970
5971 @Override
5972 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5973 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5974 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5975 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005976 PendingIntentRecord originatingPendingIntent,
5977 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005978 synchronized (mGlobalLock) {
5979 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5980 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5981 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005982 validateIncomingUser, originatingPendingIntent,
5983 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005984 }
5985 }
5986
5987 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005988 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5989 Intent intent, Bundle options, int userId) {
5990 return ActivityTaskManagerService.this.startActivityAsUser(
5991 caller, callerPacakge, intent,
5992 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5993 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5994 false /*validateIncomingUser*/);
5995 }
5996
5997 @Override
lumark588a3e82018-07-20 18:53:54 +08005998 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005999 synchronized (mGlobalLock) {
6000
6001 // We might change the visibilities here, so prepare an empty app transition which
6002 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006003 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006004 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006005 if (activityDisplay == null) {
6006 return;
6007 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006008 final DisplayContent dc = activityDisplay.mDisplayContent;
6009 final boolean wasTransitionSet =
6010 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006011 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006012 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006013 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006014 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006015
6016 // If there was a transition set already we don't want to interfere with it as we
6017 // might be starting it too early.
6018 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006019 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006020 }
6021 }
6022 if (callback != null) {
6023 callback.run();
6024 }
6025 }
6026
6027 @Override
6028 public void notifyKeyguardTrustedChanged() {
6029 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006030 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006031 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006032 }
6033 }
6034 }
6035
6036 /**
6037 * Called after virtual display Id is updated by
6038 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6039 * {@param vrVr2dDisplayId}.
6040 */
6041 @Override
6042 public void setVr2dDisplayId(int vr2dDisplayId) {
6043 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6044 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006045 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006046 }
6047 }
6048
6049 @Override
6050 public void setFocusedActivity(IBinder token) {
6051 synchronized (mGlobalLock) {
6052 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6053 if (r == null) {
6054 throw new IllegalArgumentException(
6055 "setFocusedActivity: No activity record matching token=" + token);
6056 }
Louis Chang19443452018-10-09 12:10:21 +08006057 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006058 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006059 }
6060 }
6061 }
6062
6063 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006064 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006065 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006066 }
6067
6068 @Override
6069 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006070 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006071 }
6072
6073 @Override
6074 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006075 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006076 }
6077
6078 @Override
6079 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6080 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6081 }
6082
6083 @Override
6084 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006085 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006086 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006087
6088 @Override
6089 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6090 synchronized (mGlobalLock) {
6091 mActiveVoiceInteractionServiceComponent = component;
6092 }
6093 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006094
6095 @Override
6096 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6097 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6098 return;
6099 }
6100 synchronized (mGlobalLock) {
6101 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6102 if (types == null) {
6103 if (uid < 0) {
6104 return;
6105 }
6106 types = new ArrayMap<>();
6107 mAllowAppSwitchUids.put(userId, types);
6108 }
6109 if (uid < 0) {
6110 types.remove(type);
6111 } else {
6112 types.put(type, uid);
6113 }
6114 }
6115 }
6116
6117 @Override
6118 public void onUserStopped(int userId) {
6119 synchronized (mGlobalLock) {
6120 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6121 mAllowAppSwitchUids.remove(userId);
6122 }
6123 }
6124
6125 @Override
6126 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6127 synchronized (mGlobalLock) {
6128 return ActivityTaskManagerService.this.isGetTasksAllowed(
6129 caller, callingPid, callingUid);
6130 }
6131 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006132
Riddle Hsua0536432019-02-16 00:38:59 +08006133 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006134 @Override
6135 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006136 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006137 mProcessNames.put(proc.mName, proc.mUid, proc);
6138 }
6139 }
6140
Riddle Hsua0536432019-02-16 00:38:59 +08006141 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006142 @Override
6143 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006144 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006145 mProcessNames.remove(name, uid);
6146 }
6147 }
6148
Riddle Hsua0536432019-02-16 00:38:59 +08006149 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006150 @Override
6151 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006152 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006153 if (proc == mHomeProcess) {
6154 mHomeProcess = null;
6155 }
6156 if (proc == mPreviousProcess) {
6157 mPreviousProcess = null;
6158 }
6159 }
6160 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006161
Riddle Hsua0536432019-02-16 00:38:59 +08006162 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006163 @Override
6164 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006165 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006166 return mTopProcessState;
6167 }
6168 }
6169
Riddle Hsua0536432019-02-16 00:38:59 +08006170 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006171 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006172 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006173 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006174 return proc == mHeavyWeightProcess;
6175 }
6176 }
6177
Riddle Hsua0536432019-02-16 00:38:59 +08006178 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006179 @Override
6180 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006181 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006182 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6183 }
6184 }
6185
6186 @Override
6187 public void finishHeavyWeightApp() {
6188 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006189 if (mHeavyWeightProcess != null) {
6190 mHeavyWeightProcess.finishActivities();
6191 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006192 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6193 mHeavyWeightProcess);
6194 }
6195 }
6196
Riddle Hsua0536432019-02-16 00:38:59 +08006197 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006198 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006199 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006200 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006201 return isSleepingLocked();
6202 }
6203 }
6204
6205 @Override
6206 public boolean isShuttingDown() {
6207 synchronized (mGlobalLock) {
6208 return mShuttingDown;
6209 }
6210 }
6211
6212 @Override
6213 public boolean shuttingDown(boolean booted, int timeout) {
6214 synchronized (mGlobalLock) {
6215 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006216 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006217 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006218 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006219 return mStackSupervisor.shutdownLocked(timeout);
6220 }
6221 }
6222
6223 @Override
6224 public void enableScreenAfterBoot(boolean booted) {
6225 synchronized (mGlobalLock) {
6226 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6227 SystemClock.uptimeMillis());
6228 mWindowManager.enableScreenAfterBoot();
6229 updateEventDispatchingLocked(booted);
6230 }
6231 }
6232
6233 @Override
6234 public boolean showStrictModeViolationDialog() {
6235 synchronized (mGlobalLock) {
6236 return mShowDialogs && !mSleeping && !mShuttingDown;
6237 }
6238 }
6239
6240 @Override
6241 public void showSystemReadyErrorDialogsIfNeeded() {
6242 synchronized (mGlobalLock) {
6243 try {
6244 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6245 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6246 + " data partition or your device will be unstable.");
6247 mUiHandler.post(() -> {
6248 if (mShowDialogs) {
6249 AlertDialog d = new BaseErrorDialog(mUiContext);
6250 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6251 d.setCancelable(false);
6252 d.setTitle(mUiContext.getText(R.string.android_system_label));
6253 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6254 d.setButton(DialogInterface.BUTTON_POSITIVE,
6255 mUiContext.getText(R.string.ok),
6256 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6257 d.show();
6258 }
6259 });
6260 }
6261 } catch (RemoteException e) {
6262 }
6263
6264 if (!Build.isBuildConsistent()) {
6265 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6266 mUiHandler.post(() -> {
6267 if (mShowDialogs) {
6268 AlertDialog d = new BaseErrorDialog(mUiContext);
6269 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6270 d.setCancelable(false);
6271 d.setTitle(mUiContext.getText(R.string.android_system_label));
6272 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6273 d.setButton(DialogInterface.BUTTON_POSITIVE,
6274 mUiContext.getText(R.string.ok),
6275 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6276 d.show();
6277 }
6278 });
6279 }
6280 }
6281 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006282
6283 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006284 public void onProcessMapped(int pid, WindowProcessController proc) {
6285 synchronized (mGlobalLock) {
6286 mPidMap.put(pid, proc);
6287 }
6288 }
6289
6290 @Override
6291 public void onProcessUnMapped(int pid) {
6292 synchronized (mGlobalLock) {
6293 mPidMap.remove(pid);
6294 }
6295 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006296
6297 @Override
6298 public void onPackageDataCleared(String name) {
6299 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006300 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006301 mAppWarnings.onPackageDataCleared(name);
6302 }
6303 }
6304
6305 @Override
6306 public void onPackageUninstalled(String name) {
6307 synchronized (mGlobalLock) {
6308 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006309 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006310 }
6311 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006312
6313 @Override
6314 public void onPackageAdded(String name, boolean replacing) {
6315 synchronized (mGlobalLock) {
6316 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6317 }
6318 }
6319
6320 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006321 public void onPackageReplaced(ApplicationInfo aInfo) {
6322 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006323 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006324 }
6325 }
6326
6327 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006328 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6329 synchronized (mGlobalLock) {
6330 return compatibilityInfoForPackageLocked(ai);
6331 }
6332 }
6333
Yunfan Chen75157d72018-07-27 14:47:21 +09006334 /**
6335 * Set the corresponding display information for the process global configuration. To be
6336 * called when we need to show IME on a different display.
6337 *
6338 * @param pid The process id associated with the IME window.
6339 * @param displayId The ID of the display showing the IME.
6340 */
6341 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006342 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006343 if (pid == MY_PID || pid < 0) {
6344 if (DEBUG_CONFIGURATION) {
6345 Slog.w(TAG,
6346 "Trying to update display configuration for system/invalid process.");
6347 }
6348 return;
6349 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006350 synchronized (mGlobalLock) {
6351 final ActivityDisplay activityDisplay =
6352 mRootActivityContainer.getActivityDisplay(displayId);
6353 if (activityDisplay == null) {
6354 // Call might come when display is not yet added or has been removed.
6355 if (DEBUG_CONFIGURATION) {
6356 Slog.w(TAG, "Trying to update display configuration for non-existing "
6357 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006358 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006359 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006360 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006361 final WindowProcessController process = mPidMap.get(pid);
6362 if (process == null) {
6363 if (DEBUG_CONFIGURATION) {
6364 Slog.w(TAG, "Trying to update display configuration for invalid "
6365 + "process, pid=" + pid);
6366 }
6367 return;
6368 }
6369 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6370 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006371 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006372
6373 @Override
6374 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6375 int requestCode, int resultCode, Intent data) {
6376 synchronized (mGlobalLock) {
6377 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006378 if (r != null && r.getActivityStack() != null) {
6379 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6380 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006381 }
6382 }
6383 }
6384
6385 @Override
6386 public void clearPendingResultForActivity(IBinder activityToken,
6387 WeakReference<PendingIntentRecord> pir) {
6388 synchronized (mGlobalLock) {
6389 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6390 if (r != null && r.pendingResults != null) {
6391 r.pendingResults.remove(pir);
6392 }
6393 }
6394 }
6395
6396 @Override
6397 public IIntentSender getIntentSender(int type, String packageName,
6398 int callingUid, int userId, IBinder token, String resultWho,
6399 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6400 Bundle bOptions) {
6401 synchronized (mGlobalLock) {
6402 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6403 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6404 }
6405 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006406
6407 @Override
6408 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6409 synchronized (mGlobalLock) {
6410 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6411 if (r == null) {
6412 return null;
6413 }
6414 if (r.mServiceConnectionsHolder == null) {
6415 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6416 ActivityTaskManagerService.this, r);
6417 }
6418
6419 return r.mServiceConnectionsHolder;
6420 }
6421 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006422
6423 @Override
6424 public Intent getHomeIntent() {
6425 synchronized (mGlobalLock) {
6426 return ActivityTaskManagerService.this.getHomeIntent();
6427 }
6428 }
6429
6430 @Override
6431 public boolean startHomeActivity(int userId, String reason) {
6432 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006433 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006434 }
6435 }
6436
6437 @Override
6438 public boolean startHomeOnAllDisplays(int userId, String reason) {
6439 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006440 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006441 }
6442 }
6443
Riddle Hsua0536432019-02-16 00:38:59 +08006444 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006445 @Override
6446 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006447 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006448 if (mFactoryTest == FACTORY_TEST_OFF) {
6449 return false;
6450 }
6451 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6452 && wpc.mName.equals(mTopComponent.getPackageName())) {
6453 return true;
6454 }
6455 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6456 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6457 }
6458 }
6459
6460 @Override
6461 public void updateTopComponentForFactoryTest() {
6462 synchronized (mGlobalLock) {
6463 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6464 return;
6465 }
6466 final ResolveInfo ri = mContext.getPackageManager()
6467 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6468 final CharSequence errorMsg;
6469 if (ri != null) {
6470 final ActivityInfo ai = ri.activityInfo;
6471 final ApplicationInfo app = ai.applicationInfo;
6472 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6473 mTopAction = Intent.ACTION_FACTORY_TEST;
6474 mTopData = null;
6475 mTopComponent = new ComponentName(app.packageName, ai.name);
6476 errorMsg = null;
6477 } else {
6478 errorMsg = mContext.getResources().getText(
6479 com.android.internal.R.string.factorytest_not_system);
6480 }
6481 } else {
6482 errorMsg = mContext.getResources().getText(
6483 com.android.internal.R.string.factorytest_no_action);
6484 }
6485 if (errorMsg == null) {
6486 return;
6487 }
6488
6489 mTopAction = null;
6490 mTopData = null;
6491 mTopComponent = null;
6492 mUiHandler.post(() -> {
6493 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6494 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006495 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006496 });
6497 }
6498 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006499
Riddle Hsua0536432019-02-16 00:38:59 +08006500 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006501 @Override
6502 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6503 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006504 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006505 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006506 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006507
6508 wpc.clearRecentTasks();
6509 wpc.clearActivities();
6510
6511 if (wpc.isInstrumenting()) {
6512 finishInstrumentationCallback.run();
6513 }
6514
Jorim Jaggid0752812018-10-16 16:07:20 +02006515 if (!restarting && hasVisibleActivities) {
6516 mWindowManager.deferSurfaceLayout();
6517 try {
6518 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6519 // If there was nothing to resume, and we are not already restarting
6520 // this process, but there is a visible activity that is hosted by the
6521 // process...then make sure all visible activities are running, taking
6522 // care of restarting this process.
6523 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6524 !PRESERVE_WINDOWS);
6525 }
6526 } finally {
6527 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006528 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006529 }
6530 }
6531 }
6532
6533 @Override
6534 public void closeSystemDialogs(String reason) {
6535 enforceNotIsolatedCaller("closeSystemDialogs");
6536
6537 final int pid = Binder.getCallingPid();
6538 final int uid = Binder.getCallingUid();
6539 final long origId = Binder.clearCallingIdentity();
6540 try {
6541 synchronized (mGlobalLock) {
6542 // Only allow this from foreground processes, so that background
6543 // applications can't abuse it to prevent system UI from being shown.
6544 if (uid >= FIRST_APPLICATION_UID) {
6545 final WindowProcessController proc = mPidMap.get(pid);
6546 if (!proc.isPerceptible()) {
6547 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6548 + " from background process " + proc);
6549 return;
6550 }
6551 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006552 mWindowManager.closeSystemDialogs(reason);
6553
Wale Ogunwaled32da472018-11-16 07:19:28 -08006554 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006555 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006556 // Call into AM outside the synchronized block.
6557 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006558 } finally {
6559 Binder.restoreCallingIdentity(origId);
6560 }
6561 }
6562
6563 @Override
6564 public void cleanupDisabledPackageComponents(
6565 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6566 synchronized (mGlobalLock) {
6567 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006568 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006569 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006570 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006571 mStackSupervisor.scheduleIdleLocked();
6572 }
6573
6574 // Clean-up disabled tasks
6575 getRecentTasks().cleanupDisabledPackageTasksLocked(
6576 packageName, disabledClasses, userId);
6577 }
6578 }
6579
6580 @Override
6581 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6582 int userId) {
6583 synchronized (mGlobalLock) {
6584
6585 boolean didSomething =
6586 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006587 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006588 null, doit, evenPersistent, userId);
6589 return didSomething;
6590 }
6591 }
6592
6593 @Override
6594 public void resumeTopActivities(boolean scheduleIdle) {
6595 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006596 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006597 if (scheduleIdle) {
6598 mStackSupervisor.scheduleIdleLocked();
6599 }
6600 }
6601 }
6602
Riddle Hsua0536432019-02-16 00:38:59 +08006603 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006604 @Override
6605 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006606 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006607 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6608 }
6609 }
6610
Riddle Hsua0536432019-02-16 00:38:59 +08006611 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006612 @Override
6613 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006614 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006615 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006616 }
6617 }
6618
6619 @Override
6620 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6621 try {
6622 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6623 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6624 }
6625 } catch (RemoteException ex) {
6626 throw new SecurityException("Fail to check is caller a privileged app", ex);
6627 }
6628
6629 synchronized (mGlobalLock) {
6630 final long ident = Binder.clearCallingIdentity();
6631 try {
6632 if (mAmInternal.shouldConfirmCredentials(userId)) {
6633 if (mKeyguardController.isKeyguardLocked()) {
6634 // Showing launcher to avoid user entering credential twice.
6635 startHomeActivity(currentUserId, "notifyLockedProfile");
6636 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006637 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006638 }
6639 } finally {
6640 Binder.restoreCallingIdentity(ident);
6641 }
6642 }
6643 }
6644
6645 @Override
6646 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6647 mAmInternal.enforceCallingPermission(
6648 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6649
6650 synchronized (mGlobalLock) {
6651 final long ident = Binder.clearCallingIdentity();
6652 try {
6653 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6654 FLAG_ACTIVITY_TASK_ON_HOME);
6655 ActivityOptions activityOptions = options != null
6656 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006657 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006658 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006659 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006660 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006661 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006662 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6663 UserHandle.CURRENT);
6664 } finally {
6665 Binder.restoreCallingIdentity(ident);
6666 }
6667 }
6668 }
6669
6670 @Override
6671 public void writeActivitiesToProto(ProtoOutputStream proto) {
6672 synchronized (mGlobalLock) {
6673 // The output proto of "activity --proto activities"
6674 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006675 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006676 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6677 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006678 }
6679 }
6680
6681 @Override
6682 public void saveANRState(String reason) {
6683 synchronized (mGlobalLock) {
6684 final StringWriter sw = new StringWriter();
6685 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6686 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6687 if (reason != null) {
6688 pw.println(" Reason: " + reason);
6689 }
6690 pw.println();
6691 getActivityStartController().dump(pw, " ", null);
6692 pw.println();
6693 pw.println("-------------------------------------------------------------------------------");
6694 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6695 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6696 "" /* header */);
6697 pw.println();
6698 pw.close();
6699
6700 mLastANRState = sw.toString();
6701 }
6702 }
6703
6704 @Override
6705 public void clearSavedANRState() {
6706 synchronized (mGlobalLock) {
6707 mLastANRState = null;
6708 }
6709 }
6710
6711 @Override
6712 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6713 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6714 synchronized (mGlobalLock) {
6715 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6716 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6717 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6718 dumpLastANRLocked(pw);
6719 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6720 dumpLastANRTracesLocked(pw);
6721 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6722 dumpActivityStarterLocked(pw, dumpPackage);
6723 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6724 dumpActivityContainersLocked(pw);
6725 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6726 if (getRecentTasks() != null) {
6727 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6728 }
6729 }
6730 }
6731 }
6732
6733 @Override
6734 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6735 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6736 int wakefulness) {
6737 synchronized (mGlobalLock) {
6738 if (mHomeProcess != null && (dumpPackage == null
6739 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6740 if (needSep) {
6741 pw.println();
6742 needSep = false;
6743 }
6744 pw.println(" mHomeProcess: " + mHomeProcess);
6745 }
6746 if (mPreviousProcess != null && (dumpPackage == null
6747 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6748 if (needSep) {
6749 pw.println();
6750 needSep = false;
6751 }
6752 pw.println(" mPreviousProcess: " + mPreviousProcess);
6753 }
6754 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6755 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6756 StringBuilder sb = new StringBuilder(128);
6757 sb.append(" mPreviousProcessVisibleTime: ");
6758 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6759 pw.println(sb);
6760 }
6761 if (mHeavyWeightProcess != null && (dumpPackage == null
6762 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6763 if (needSep) {
6764 pw.println();
6765 needSep = false;
6766 }
6767 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6768 }
6769 if (dumpPackage == null) {
6770 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006771 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 }
6773 if (dumpAll) {
6774 if (dumpPackage == null) {
6775 pw.println(" mConfigWillChange: "
6776 + getTopDisplayFocusedStack().mConfigWillChange);
6777 }
6778 if (mCompatModePackages.getPackages().size() > 0) {
6779 boolean printed = false;
6780 for (Map.Entry<String, Integer> entry
6781 : mCompatModePackages.getPackages().entrySet()) {
6782 String pkg = entry.getKey();
6783 int mode = entry.getValue();
6784 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6785 continue;
6786 }
6787 if (!printed) {
6788 pw.println(" mScreenCompatPackages:");
6789 printed = true;
6790 }
6791 pw.println(" " + pkg + ": " + mode);
6792 }
6793 }
6794 }
6795
6796 if (dumpPackage == null) {
6797 pw.println(" mWakefulness="
6798 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006799 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006800 if (mRunningVoice != null) {
6801 pw.println(" mRunningVoice=" + mRunningVoice);
6802 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6803 }
6804 pw.println(" mSleeping=" + mSleeping);
6805 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6806 pw.println(" mVrController=" + mVrController);
6807 }
6808 if (mCurAppTimeTracker != null) {
6809 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6810 }
6811 if (mAllowAppSwitchUids.size() > 0) {
6812 boolean printed = false;
6813 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6814 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6815 for (int j = 0; j < types.size(); j++) {
6816 if (dumpPackage == null ||
6817 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6818 if (needSep) {
6819 pw.println();
6820 needSep = false;
6821 }
6822 if (!printed) {
6823 pw.println(" mAllowAppSwitchUids:");
6824 printed = true;
6825 }
6826 pw.print(" User ");
6827 pw.print(mAllowAppSwitchUids.keyAt(i));
6828 pw.print(": Type ");
6829 pw.print(types.keyAt(j));
6830 pw.print(" = ");
6831 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6832 pw.println();
6833 }
6834 }
6835 }
6836 }
6837 if (dumpPackage == null) {
6838 if (mController != null) {
6839 pw.println(" mController=" + mController
6840 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6841 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006842 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6843 pw.println(" mLaunchingActivityWakeLock="
6844 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 }
6846
6847 return needSep;
6848 }
6849 }
6850
6851 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006852 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6853 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 synchronized (mGlobalLock) {
6855 if (dumpPackage == null) {
6856 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6857 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006858 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6859 if (mRunningVoice != null) {
6860 final long vrToken = proto.start(
6861 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6862 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6863 mRunningVoice.toString());
6864 mVoiceWakeLock.writeToProto(
6865 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6866 proto.end(vrToken);
6867 }
6868 mVrController.writeToProto(proto,
6869 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 if (mController != null) {
6871 final long token = proto.start(CONTROLLER);
6872 proto.write(CONTROLLER, mController.toString());
6873 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6874 proto.end(token);
6875 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006876 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6877 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6878 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 }
6880
6881 if (mHomeProcess != null && (dumpPackage == null
6882 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006883 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006884 }
6885
6886 if (mPreviousProcess != null && (dumpPackage == null
6887 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006888 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6890 }
6891
6892 if (mHeavyWeightProcess != null && (dumpPackage == null
6893 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006894 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 }
6896
6897 for (Map.Entry<String, Integer> entry
6898 : mCompatModePackages.getPackages().entrySet()) {
6899 String pkg = entry.getKey();
6900 int mode = entry.getValue();
6901 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6902 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6903 proto.write(PACKAGE, pkg);
6904 proto.write(MODE, mode);
6905 proto.end(compatToken);
6906 }
6907 }
6908
6909 if (mCurAppTimeTracker != null) {
6910 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6911 }
6912
6913 }
6914 }
6915
6916 @Override
6917 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6918 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6919 boolean dumpFocusedStackOnly) {
6920 synchronized (mGlobalLock) {
6921 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6922 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6923 }
6924 }
6925
6926 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006927 public void dumpForOom(PrintWriter pw) {
6928 synchronized (mGlobalLock) {
6929 pw.println(" mHomeProcess: " + mHomeProcess);
6930 pw.println(" mPreviousProcess: " + mPreviousProcess);
6931 if (mHeavyWeightProcess != null) {
6932 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6933 }
6934 }
6935 }
6936
6937 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 public boolean canGcNow() {
6939 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006940 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006941 }
6942 }
6943
Riddle Hsua0536432019-02-16 00:38:59 +08006944 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006945 @Override
6946 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006947 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006948 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006949 return top != null ? top.app : null;
6950 }
6951 }
6952
Riddle Hsua0536432019-02-16 00:38:59 +08006953 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 @Override
6955 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006956 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006957 if (mRootActivityContainer != null) {
6958 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006959 }
6960 }
6961 }
6962
6963 @Override
6964 public void scheduleDestroyAllActivities(String reason) {
6965 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006966 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006967 }
6968 }
6969
6970 @Override
6971 public void removeUser(int userId) {
6972 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006973 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006974 }
6975 }
6976
6977 @Override
6978 public boolean switchUser(int userId, UserState userState) {
6979 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006980 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006981 }
6982 }
6983
6984 @Override
6985 public void onHandleAppCrash(WindowProcessController wpc) {
6986 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006987 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006988 }
6989 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006990
6991 @Override
6992 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6993 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006994 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006995 }
6996 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006997
Riddle Hsua0536432019-02-16 00:38:59 +08006998 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006999 @Override
7000 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007001 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007002 }
7003
Riddle Hsua0536432019-02-16 00:38:59 +08007004 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007005 @Override
7006 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007007 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007008 }
7009
Riddle Hsua0536432019-02-16 00:38:59 +08007010 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007011 @Override
7012 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007013 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007014 }
7015
Riddle Hsua0536432019-02-16 00:38:59 +08007016 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007017 @Override
7018 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007019 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007020 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007021
7022 @Override
7023 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007024 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007025 mPendingTempWhitelist.put(uid, tag);
7026 }
7027 }
7028
7029 @Override
7030 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007031 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007032 mPendingTempWhitelist.remove(uid);
7033 }
7034 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007035
7036 @Override
7037 public boolean handleAppCrashInActivityController(String processName, int pid,
7038 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7039 Runnable killCrashingAppCallback) {
7040 synchronized (mGlobalLock) {
7041 if (mController == null) {
7042 return false;
7043 }
7044
7045 try {
7046 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7047 stackTrace)) {
7048 killCrashingAppCallback.run();
7049 return true;
7050 }
7051 } catch (RemoteException e) {
7052 mController = null;
7053 Watchdog.getInstance().setActivityController(null);
7054 }
7055 return false;
7056 }
7057 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007058
7059 @Override
7060 public void removeRecentTasksByPackageName(String packageName, int userId) {
7061 synchronized (mGlobalLock) {
7062 mRecentTasks.removeTasksByPackageName(packageName, userId);
7063 }
7064 }
7065
7066 @Override
7067 public void cleanupRecentTasksForUser(int userId) {
7068 synchronized (mGlobalLock) {
7069 mRecentTasks.cleanupLocked(userId);
7070 }
7071 }
7072
7073 @Override
7074 public void loadRecentTasksForUser(int userId) {
7075 synchronized (mGlobalLock) {
7076 mRecentTasks.loadUserRecentsLocked(userId);
7077 }
7078 }
7079
7080 @Override
7081 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7082 synchronized (mGlobalLock) {
7083 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7084 }
7085 }
7086
7087 @Override
7088 public void flushRecentTasks() {
7089 mRecentTasks.flush();
7090 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007091
7092 @Override
7093 public WindowProcessController getHomeProcess() {
7094 synchronized (mGlobalLock) {
7095 return mHomeProcess;
7096 }
7097 }
7098
7099 @Override
7100 public WindowProcessController getPreviousProcess() {
7101 synchronized (mGlobalLock) {
7102 return mPreviousProcess;
7103 }
7104 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007105
7106 @Override
7107 public void clearLockedTasks(String reason) {
7108 synchronized (mGlobalLock) {
7109 getLockTaskController().clearLockedTasks(reason);
7110 }
7111 }
7112
7113 @Override
7114 public void updateUserConfiguration() {
7115 synchronized (mGlobalLock) {
7116 final Configuration configuration = new Configuration(getGlobalConfiguration());
7117 final int currentUserId = mAmInternal.getCurrentUserId();
7118 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7119 configuration, currentUserId, Settings.System.canWrite(mContext));
7120 updateConfigurationLocked(configuration, null /* starting */,
7121 false /* initLocale */, false /* persistent */, currentUserId,
7122 false /* deferResume */);
7123 }
7124 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007125
7126 @Override
7127 public boolean canShowErrorDialogs() {
7128 synchronized (mGlobalLock) {
7129 return mShowDialogs && !mSleeping && !mShuttingDown
7130 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7131 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7132 mAmInternal.getCurrentUserId())
7133 && !(UserManager.isDeviceInDemoMode(mContext)
7134 && mAmInternal.getCurrentUser().isDemo());
7135 }
7136 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007137
7138 @Override
7139 public void setProfileApp(String profileApp) {
7140 synchronized (mGlobalLock) {
7141 mProfileApp = profileApp;
7142 }
7143 }
7144
7145 @Override
7146 public void setProfileProc(WindowProcessController wpc) {
7147 synchronized (mGlobalLock) {
7148 mProfileProc = wpc;
7149 }
7150 }
7151
7152 @Override
7153 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7154 synchronized (mGlobalLock) {
7155 mProfilerInfo = profilerInfo;
7156 }
7157 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007158
7159 @Override
7160 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7161 synchronized (mGlobalLock) {
7162 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7163 }
7164 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007165
7166 @Override
7167 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7168 synchronized (mGlobalLock) {
7169 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7170 }
7171 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007172
7173 @Override
7174 public boolean isUidForeground(int uid) {
7175 synchronized (mGlobalLock) {
7176 return ActivityTaskManagerService.this.isUidForeground(uid);
7177 }
7178 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007179
7180 @Override
7181 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7182 synchronized (mGlobalLock) {
7183 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7184 }
7185 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007186 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007187}