1 /* 2 * Copyright (C) 2016 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.shortcuts; 18 19 import android.annotation.TargetApi; 20 import android.os.Build; 21 import android.os.UserHandle; 22 import android.util.LruCache; 23 24 import java.util.HashMap; 25 import java.util.List; 26 27 /** 28 * Loads {@link ShortcutInfoCompat}s on demand (e.g. when launcher 29 * loads for pinned shortcuts and on long-press for dynamic shortcuts), and caches them 30 * for handful of apps in an LruCache while launcher lives. 31 */ 32 @TargetApi(Build.VERSION_CODES.N) 33 public class ShortcutCache { 34 private static final String TAG = "ShortcutCache"; 35 private static final boolean LOGD = false; 36 37 private static final int CACHE_SIZE = 30; // Max number shortcuts we cache. 38 39 private LruCache<ShortcutKey, ShortcutInfoCompat> mCachedShortcuts; 40 // We always keep pinned shortcuts in the cache. 41 private HashMap<ShortcutKey, ShortcutInfoCompat> mPinnedShortcuts; 42 43 public ShortcutCache() { 44 mCachedShortcuts = new LruCache<>(CACHE_SIZE); 45 mPinnedShortcuts = new HashMap<>(); 46 } 47 48 /** 49 * Removes shortcuts from the cache when shortcuts change for a given package. 50 * 51 * Returns a map of ids to their evicted shortcuts. 52 * 53 * @see android.content.pm.LauncherApps.Callback#onShortcutsChanged(String, List, UserHandle). 54 */ 55 public void removeShortcuts(List<ShortcutInfoCompat> shortcuts) { 56 for (ShortcutInfoCompat shortcut : shortcuts) { 57 ShortcutKey key = ShortcutKey.fromInfo(shortcut); 58 mCachedShortcuts.remove(key); 59 mPinnedShortcuts.remove(key); 60 } 61 } 62 63 public ShortcutInfoCompat get(ShortcutKey key) { 64 if (mPinnedShortcuts.containsKey(key)) { 65 return mPinnedShortcuts.get(key); 66 } 67 return mCachedShortcuts.get(key); 68 } 69 70 public void put(ShortcutKey key, ShortcutInfoCompat shortcut) { 71 if (shortcut.isPinned()) { 72 mPinnedShortcuts.put(key, shortcut); 73 } else { 74 mCachedShortcuts.put(key, shortcut); 75 } 76 } 77 } 78