1 /* 2 * Copyright (C) 2023 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 17 package com.android.car.portraitlauncher.homeactivities; 18 19 import android.app.ActivityManager; 20 import android.app.ActivityTaskManager; 21 import android.app.TaskInfo; 22 import android.content.Context; 23 import android.content.Intent; 24 import android.os.Build; 25 import android.util.Log; 26 27 import java.util.ArrayDeque; 28 import java.util.Queue; 29 30 /** 31 * A simple class to cancel, cache, start tasks. 32 */ 33 class TaskInfoCache { 34 public static final String TAG = TaskInfoCache.class.getSimpleName(); 35 private static final boolean DBG = Build.IS_DEBUGGABLE; 36 private final ActivityTaskManager mActivityTaskManager; 37 private final Queue<TaskInfo> mCachedTaskQueue; 38 private final Context mContext; 39 TaskInfoCache(Context context)40 TaskInfoCache(Context context) { 41 mContext = context; 42 mActivityTaskManager = ActivityTaskManager.getInstance(); 43 mCachedTaskQueue = new ArrayDeque<>(); 44 } 45 46 /** Cancel the given task */ cancelTask(ActivityManager.RunningTaskInfo taskInfo)47 boolean cancelTask(ActivityManager.RunningTaskInfo taskInfo) { 48 logIfDebuggable("Cancel task " + taskInfo); 49 if (mActivityTaskManager == null) { 50 throw new RuntimeException("ActivityTaskManager cannot be null"); 51 } 52 53 return mActivityTaskManager.removeTask(taskInfo.taskId); 54 } 55 56 /** Cache the given task and save it to queue {@code mCancelledTaskQueue}. */ cacheTask(ActivityManager.RunningTaskInfo taskInfo)57 boolean cacheTask(ActivityManager.RunningTaskInfo taskInfo) { 58 logIfDebuggable("Cache task " + taskInfo); 59 return mCachedTaskQueue.add(taskInfo); 60 } 61 62 /** Start the task in {@code mCancelledTaskQueue} in order. */ startCachedTasks()63 void startCachedTasks() { 64 logIfDebuggable("Start cached tasks, tasks size =" + mCachedTaskQueue.size()); 65 while (!mCachedTaskQueue.isEmpty()) { 66 Intent intent = mCachedTaskQueue.remove().baseIntent; 67 try { 68 logIfDebuggable("Start cached task " + intent); 69 mContext.startActivity(intent); 70 } catch (SecurityException e) { 71 Log.e(TAG, "Failed to launch cached task", e); 72 } 73 } 74 } 75 logIfDebuggable(String message)76 private static void logIfDebuggable(String message) { 77 if (DBG) { 78 Log.d(TAG, message); 79 } 80 } 81 } 82