androidx.collection.LruCache Java Examples

The following examples show how to use androidx.collection.LruCache. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ComponentWarmer.java    From litho with Apache License 2.0 6 votes vote down vote up
DefaultCache(int maxSize, CacheListener cacheListener) {
  mCacheListener = cacheListener;
  mCache =
      new LruCache<String, ComponentTreeHolder>(maxSize) {

        @Override
        protected void entryRemoved(
            boolean evicted,
            @NonNull String key,
            @NonNull ComponentTreeHolder oldValue,
            @Nullable ComponentTreeHolder newValue) {
          if (evicted && mCacheListener != null) {
            mCacheListener.onEntryEvicted(key, oldValue);
          }
        }
      };
}
 
Example #2
Source File: ImageCache.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initialize the cache.
 *
 * @param memCacheSizePercent The cache size as a percent of available app memory.
 */
private void init(float memCacheSizePercent) {
    int memCacheSize = calculateMemCacheSize(memCacheSizePercent);

    // Set up memory cache
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "Memory cache created (size = " + memCacheSize + ")");
    }
    mMemoryCache = new LruCache<String, Bitmap>(memCacheSize) {
        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            final int bitmapSize = getBitmapSize(bitmap) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
}
 
Example #3
Source File: ImageLoader.java    From tindroid with Apache License 2.0 6 votes vote down vote up
ImageLoader(int imageSize, FragmentManager fm) {
    // mResources = context.getResources();
    mImageSize = imageSize > 0 ? imageSize : DEFAULT_IMAGE_SIZE;

    final RetainFragment retainFragment = findOrCreateRetainFragment(fm);
    // See if we already have an ImageCache stored in RetainFragment
    //noinspection unchecked
    mBitmapCache = (LruCache<String, Bitmap>) retainFragment.getObject();
    // No existing ImageCache, create one and store it in RetainFragment
    if (mBitmapCache == null) {
        int maxSize = Math.round(MEMORY_PERCENT * Runtime.getRuntime().maxMemory() / 1024);
        mBitmapCache = new LruCache<String, Bitmap>(maxSize) {
            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(@NonNull String key, @NonNull Bitmap bitmap) {
                final int bitmapSize = bitmap.getByteCount() / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
        retainFragment.saveObject(mBitmapCache);
    }
}
 
Example #4
Source File: CurrentPlaylistAdapter.java    From odyssey with GNU General Public License v3.0 6 votes vote down vote up
public CurrentPlaylistAdapter(Context context, PlaybackServiceConnection playbackServiceConnection) {
    super();

    mContext = context;
    mPlaybackServiceConnection = playbackServiceConnection;

    try {
        mPlaylistSize = mPlaybackServiceConnection.getPBS().getPlaylistSize();
        mCurrentPlayingIndex = mPlaybackServiceConnection.getPBS().getCurrentIndex();
    } catch (RemoteException e) {
        mPlaybackServiceConnection = null;
        e.printStackTrace();
    }

    mArtworkManager = ArtworkManager.getInstance(context.getApplicationContext());
    mTrackCache = new LruCache<>(CACHE_SIZE);
}
 
Example #5
Source File: LruMemoryCache.java    From RxCache with Apache License 2.0 6 votes vote down vote up
public LruMemoryCache(final int cacheSize) {
    memorySizeMap = new HashMap<>();
    timestampMap = new HashMap<>();
    byte to = 0;
    byte t4 = 4;
    occupy = new Occupy(to, to, t4);
    mCache = new LruCache<String, Object>(cacheSize) {
        @Override
        protected int sizeOf(String key, Object value) {
            Integer integer = memorySizeMap.get(key);
            if (integer == null) {
                integer = countSize(value);
                memorySizeMap.put(key, integer);
            }
            return integer;
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, Object oldValue, Object newValue) {
            super.entryRemoved(evicted, key, oldValue, newValue);
            memorySizeMap.remove(key);
            timestampMap.remove(key);
        }
    };
}
 
Example #6
Source File: AccessibilityFocusActionHistory.java    From talkback with Apache License 2.0 6 votes vote down vote up
public AccessibilityFocusActionHistory() {
  focusActionRecordList = new ArrayDeque<>();
  windowIdTitlePairToFocusActionRecordMap =
      new LruCache<Pair<Integer, CharSequence>, FocusActionRecord>(MAXIMUM_WINDOW_MAP_SIZE) {
        /**
         * Recycles the source node in the record when the focus action record is removed from the
         * cache.
         */
        @Override
        protected void entryRemoved(
            boolean evicted,
            Pair<Integer, CharSequence> key,
            FocusActionRecord oldValue,
            FocusActionRecord newValue) {
          if (oldValue != null) {
            oldValue.recycle();
          }
        }
      };
}
 
Example #7
Source File: EhApplication.java    From MHViewer with Apache License 2.0 5 votes vote down vote up
@NonNull
public static LruCache<String, GalleryDetail> getGalleryDetailCache(@NonNull Context context) {
    EhApplication application = ((EhApplication) context.getApplicationContext());
    if (application.mGalleryDetailCache == null) {
        // Max size 25, 3 min timeout
        application.mGalleryDetailCache = new LruCache<>(25);
        getFavouriteStatusRouter().addListener((gid, slot) -> {
            GalleryDetail gd = application.mGalleryDetailCache.get(gid);
            if (gd != null) {
                gd.favoriteSlot = slot;
            }
        });
    }
    return application.mGalleryDetailCache;
}
 
Example #8
Source File: BitmapManager.java    From cloudinary_android with MIT License 5 votes vote down vote up
private void initMemoryCache() {
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;
    memoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return bitmap.getByteCount() / 1024;
        }
    };
}
 
Example #9
Source File: EhApplication.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
@NonNull
public static LruCache<Long, GalleryDetail> getGalleryDetailCache(@NonNull Context context) {
    EhApplication application = ((EhApplication) context.getApplicationContext());
    if (application.mGalleryDetailCache == null) {
        // Max size 25, 3 min timeout
        application.mGalleryDetailCache = new LruCache<>(25);
        getFavouriteStatusRouter().addListener((gid, slot) -> {
            GalleryDetail gd = application.mGalleryDetailCache.get(gid);
            if (gd != null) {
                gd.favoriteSlot = slot;
            }
        });
    }
    return application.mGalleryDetailCache;
}
 
Example #10
Source File: StringUtils.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
/**
 * @param input A non-null string
 * @return a canonical version of the passed in string that is lower cased and has removed diacritical marks
 * like accents.
 */
@SuppressLint("NewApi")
public synchronized static String normalize(String input) {
    if (normalizationCache == null) {
        normalizationCache = new LruCache<>(cacheSize);

        diacritics = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
    }
    String cachedString = normalizationCache.get(input);
    if (cachedString != null) {
        return cachedString;
    }

    //Initialized the normalized string (If we can, we'll use the Normalizer API on it)
    String normalized = input;

    //If we're above gingerbread we'll normalize this in NFD form 
    //which helps a lot. Otherwise we won't be able to clear up some of those
    //issues, but we can at least still eliminate diacritics.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        normalized = Normalizer.normalize(input, Normalizer.Form.NFD);
    } else {
        //TODO: I doubt it's worth it, but in theory we could run
        //some other normalization for the minority of pre-API9
        //devices.
    }

    String output = diacritics.matcher(normalized).replaceAll("").toLowerCase();

    normalizationCache.put(input, output);

    return output;
}
 
Example #11
Source File: VolleyMemoryCache.java    From fresco with MIT License 5 votes vote down vote up
public VolleyMemoryCache(int maxSize) {
  mLruCache =
      new LruCache<String, Bitmap>(maxSize) {
        protected int sizeOf(final String key, final Bitmap value) {
          return value.getRowBytes() * value.getHeight();
        }
      };
}
 
Example #12
Source File: ApplicationsCache.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
ApplicationsCache()
{
    applicationsList = new ArrayList<>();
    applicationIconsLru = new LruCache<>(5 * 1024 * 1024); //Max is 5MB
    applicationsNoShortcutsList = new ArrayList<>();
    applicationNoShortcutIconsLru = new LruCache<>(5 * 1024 * 1024); //Max is 5MB
    cached = false;
}
 
Example #13
Source File: AbsCache.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化内存缓存
 */
protected void initMemoryCache() {
  if (!useMemory) {
    return;
  }
  // 获取应用程序最大可用内存
  mMaxMemory = (int) Runtime.getRuntime().maxMemory();
  // 设置图片缓存大小为程序最大可用内存的1/8
  mMemoryCache = new LruCache<>(mMaxMemory / 8);
}
 
Example #14
Source File: BitmapCache.java    From odyssey with GNU General Public License v3.0 5 votes vote down vote up
private BitmapCache() {
    mCache = new LruCache<String, Bitmap>(mCacheSize) {
        @Override
        protected int sizeOf(@NonNull String key, @NonNull Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return bitmap.getByteCount() / 1024;
        }

    };
}
 
Example #15
Source File: ImageLoader.java    From Audinaut with GNU General Public License v3.0 5 votes vote down vote up
public ImageLoader(Context context) {
    this.context = context;
    handler = new Handler(Looper.getMainLooper());
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    cacheSize = maxMemory / 4;

    // Determine the density-dependent image sizes.
    imageSizeDefault = context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight();
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    imageSizeLarge = Math.round(Math.min(metrics.widthPixels, metrics.heightPixels));

    cache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, Bitmap oldBitmap, Bitmap newBitmap) {
            if (evicted) {
                if ((oldBitmap != nowPlaying && oldBitmap != nowPlayingSmall) || clearingCache) {
                    oldBitmap.recycle();
                } else if (oldBitmap != newBitmap) {
                    cache.put(key, oldBitmap);
                }
            }
        }
    };
}
 
Example #16
Source File: LocalImageLoader.java    From AppOpsX with MIT License 5 votes vote down vote up
private static void init(Context context) {
  if (sLruCache == null) {

    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    int maxSize = Math.round(am.getMemoryClass() * 1024 * 1024 * 0.3f);

    sLruCache = new LruCache<String, Drawable>(maxSize) {
      @Override
      protected int sizeOf(String key, Drawable drawable) {
        if (drawable != null) {
          if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap().getAllocationByteCount();
          } else {
            return drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight() * 2;
          }
        }
        return super.sizeOf(key, drawable);
      }

      @Override
      protected void entryRemoved(boolean evicted, String key, Drawable oldValue,
          Drawable newValue) {
        super.entryRemoved(evicted, key, oldValue, newValue);

      }
    };
  }
}
 
Example #17
Source File: ImageCache.java    From RoMote with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 */
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps =
                    Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key,
                    BitmapDrawable oldValue, BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable

                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the bitmap
                        // to a SoftReference set for possible use with inBitmap later
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
    //END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}
 
Example #18
Source File: ThetaDeviceApplication.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
public LruCache<String, byte[]> getCache() {
    return mThumbnailCache;
}
 
Example #19
Source File: BoxBrowseController.java    From box-android-browse-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public LruCache<File, Bitmap> getThumbnailCache() {
    return mThumbnailCache;
}
 
Example #20
Source File: BoxBrowseController.java    From box-android-browse-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public LruCache<Integer, Bitmap> getIconResourceCache() {
    return mIconResCache;
}
 
Example #21
Source File: ImageCache.java    From graphics-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 */
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        mReusableBitmaps =
                Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(
                    boolean evicted,
                    @NonNull String key,
                    @NonNull BitmapDrawable oldValue,
                    BitmapDrawable newValue
            ) {
                if (oldValue instanceof RecyclingBitmapDrawable) {
                    // The removed entry is a recycling drawable, so notify it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable.
                    // Add the bitmap to a SoftReference set for possible use with inBitmap
                    // later.
                    mReusableBitmaps.add(new SoftReference<>(oldValue.getBitmap()));
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(@NonNull String key, @NonNull BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
    //END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}
 
Example #22
Source File: PlaybackSeekAsyncDataProvider.java    From tv-samples with Apache License 2.0 4 votes vote down vote up
public PlaybackSeekAsyncDataProvider(int cacheSize, int prefetchCacheSize) {
    mCache = new LruCache<Integer, Bitmap>(cacheSize);
    mPrefetchCache = new LruCache<Integer, Bitmap>(prefetchCacheSize);
}
 
Example #23
Source File: PreviewDataBinder.java    From ChromeLikeTabSwitcher with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new data binder, which allows to asynchronously render preview images of tabs and
 * display them afterwards.
 *
 * @param parent
 *         The parent view of the tab switcher, the tabs belong to, as an instance of the class
 *         {@link ViewGroup}. The parent may not be null
 * @param contentViewRecycler
 *         The view recycler, which should be used to inflate the views, which are associated
 *         with tabs, as an instance of the class ViewRecycler. The view recycler may not be
 *         null
 * @param model
 *         The model of the tab switcher, the tabs belong to, as an instance of the type {@link
 *         Model}. The model may not be null
 */
public PreviewDataBinder(@NonNull final ViewGroup parent,
                         @NonNull final ViewRecycler<Tab, Void> contentViewRecycler,
                         @NonNull final Model model) {
    super(parent.getContext().getApplicationContext(), new LruCache<Tab, Bitmap>(7));
    Condition.INSTANCE.ensureNotNull(parent, "The parent may not be null");
    Condition.INSTANCE
            .ensureNotNull(contentViewRecycler, "The content view recycler may not be null");
    this.parent = parent;
    this.contentViewRecycler = contentViewRecycler;
    this.model = model;
}
 
Example #24
Source File: BrowseController.java    From box-android-browse-sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Gets thumbnail cache.
 *
 * @return the thumbnail cache
 */
LruCache<File, Bitmap> getThumbnailCache();
 
Example #25
Source File: BrowseController.java    From box-android-browse-sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Gets icon resource cache.
 *
 * @return the icon resource cache
 */
LruCache<Integer, Bitmap> getIconResourceCache();