1 /* 2 * Copyright (C) 2020 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.launcher3.ui; 18 19 import android.app.Activity; 20 import android.app.Application; 21 import android.os.Bundle; 22 23 import androidx.test.InstrumentationRegistry; 24 25 import com.android.launcher3.tapl.TestHelpers; 26 27 import java.util.WeakHashMap; 28 import java.util.stream.Collectors; 29 30 public class ActivityLeakTracker implements Application.ActivityLifecycleCallbacks { 31 private final WeakHashMap<Activity, Boolean> mActivities = new WeakHashMap<>(); 32 33 private int mActivitiesCreated; 34 ActivityLeakTracker()35 ActivityLeakTracker() { 36 if (!TestHelpers.isInLauncherProcess()) return; 37 final Application app = 38 (Application) InstrumentationRegistry.getTargetContext().getApplicationContext(); 39 app.registerActivityLifecycleCallbacks(this); 40 } 41 getActivitiesCreated()42 public int getActivitiesCreated() { 43 return mActivitiesCreated; 44 } 45 46 @Override onActivityCreated(Activity activity, Bundle bundle)47 public void onActivityCreated(Activity activity, Bundle bundle) { 48 mActivities.put(activity, true); 49 ++mActivitiesCreated; 50 } 51 52 @Override onActivityStarted(Activity activity)53 public void onActivityStarted(Activity activity) { 54 } 55 56 @Override onActivityResumed(Activity activity)57 public void onActivityResumed(Activity activity) { 58 } 59 60 @Override onActivityPaused(Activity activity)61 public void onActivityPaused(Activity activity) { 62 } 63 64 @Override onActivityStopped(Activity activity)65 public void onActivityStopped(Activity activity) { 66 } 67 68 @Override onActivitySaveInstanceState(Activity activity, Bundle bundle)69 public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { 70 } 71 72 @Override onActivityDestroyed(Activity activity)73 public void onActivityDestroyed(Activity activity) { 74 } 75 noLeakedActivities()76 public boolean noLeakedActivities() { 77 for (Activity activity : mActivities.keySet()) { 78 if (activity.isDestroyed()) { 79 return false; 80 } 81 } 82 83 return mActivities.size() <= 2; 84 } 85 getActivitiesList()86 public String getActivitiesList() { 87 return mActivities.keySet().stream().map(a -> a.getClass().getSimpleName()) 88 .collect(Collectors.joining(",")); 89 } 90 } 91