Example usage for android.support.v4.util LruCache LruCache

List of usage examples for android.support.v4.util LruCache LruCache

Introduction

In this page you can find the example usage for android.support.v4.util LruCache LruCache.

Prototype

public LruCache(int maxSize) 

Source Link

Usage

From source file:com.DGSD.Teexter.Utils.ContactPhotoManager.java

public ContactPhotoManagerImpl(Context context) {
    mContext = context;//  w  w w .j  av  a 2 s  .c  o  m

    final float cacheSizeAdjustment = 1.0f;
    final int bitmapCacheSize = (int) (cacheSizeAdjustment * BITMAP_CACHE_SIZE);
    mBitmapCache = new LruCache<Object, Bitmap>(bitmapCacheSize) {
        @Override
        protected int sizeOf(Object key, Bitmap value) {
            return value.getByteCount();
        }

        @Override
        protected void entryRemoved(boolean evicted, Object key, Bitmap oldValue, Bitmap newValue) {
        }
    };
    final int holderCacheSize = (int) (cacheSizeAdjustment * HOLDER_CACHE_SIZE);
    mBitmapHolderCache = new LruCache<Object, BitmapHolder>(holderCacheSize) {
        @Override
        protected int sizeOf(Object key, BitmapHolder value) {
            return value.bytes != null ? value.bytes.length : 0;
        }

        @Override
        protected void entryRemoved(boolean evicted, Object key, BitmapHolder oldValue, BitmapHolder newValue) {
        }
    };
    mBitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75);
}

From source file:com.silentcircle.contacts.utils.ExpirableCache.java

/**
 * Creates a new {@link ExpirableCache} with the given maximum size.
 *
 * @param <K> the type of the keys
 * @param <V> the type of the values
 * @return the newly created expirable cache
 *//*from   www  .j a v  a  2s  .  c  om*/
public static <K, V> ExpirableCache<K, V> create(int maxSize) {
    return create(new LruCache<K, CachedValue<V>>(maxSize));
}

From source file:com.afrozaar.jazzfestreporting.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///from  ww  w.j av a 2s.  co  m
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // 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, then
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = 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 SoftRefrence 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;
            }
        };
    }

    // 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();
    }
}

From source file:com.andreadec.musicplayer.MainActivity.java

@SuppressLint({ "InlinedApi", "NewApi" })
@Override/*ww  w  .j a  va2  s  .  com*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    preferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (preferences.getBoolean(Constants.PREFERENCE_DISABLELOCKSCREEN, Constants.DEFAULT_DISABLELOCKSCREEN)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // Disable lock screen for this activity
    }

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    if (preferences.getBoolean(Constants.PREFERENCE_SHOWHELPOVERLAYMAINACTIVITY, true)) {
        final FrameLayout frameLayout = new FrameLayout(this);
        LayoutInflater layoutInflater = getLayoutInflater();
        layoutInflater.inflate(R.layout.layout_main, frameLayout);
        layoutInflater.inflate(R.layout.layout_helpoverlay_main, frameLayout);
        final View overlayView = frameLayout.getChildAt(1);
        overlayView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                frameLayout.removeView(overlayView);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean(Constants.PREFERENCE_SHOWHELPOVERLAYMAINACTIVITY, false);
                editor.commit();
            }
        });
        setContentView(frameLayout);
    } else {
        setContentView(R.layout.layout_main);
    }

    pages = new String[4];
    pages[PAGE_BROWSER] = getResources().getString(R.string.browser);
    pages[PAGE_PLAYLISTS] = getResources().getString(R.string.playlist);
    pages[PAGE_RADIOS] = getResources().getString(R.string.radio);
    pages[PAGE_PODCASTS] = getResources().getString(R.string.podcasts);
    fragmentManager = getSupportFragmentManager();
    setTitle(pages[currentPage]);

    /* NAVIGATION DRAWER */
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            setTitle(pages[currentPage]);
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            setTitle(getResources().getString(R.string.app_name));
        }
    };
    drawerLayout.setDrawerListener(drawerToggle);
    if (Build.VERSION.SDK_INT >= 11)
        getActionBar().setDisplayHomeAsUpEnabled(true);
    drawerContainer = (RelativeLayout) findViewById(R.id.navigation_container);
    drawerList = (ListView) findViewById(R.id.navigation_list);
    navigationAdapter = new NavigationDrawerArrayAdapter(this, pages);
    drawerList.setAdapter(navigationAdapter);
    drawerList.setOnItemClickListener(new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View view, int position,
                long id) {
            openPage(position);
            drawerLayout.closeDrawer(drawerContainer);
        }
    });
    buttonQuit = findViewById(R.id.navigation_buttonQuit);
    buttonQuit.setOnClickListener(this);

    if (Build.VERSION.SDK_INT >= 19) {
        // Android 4.4+ only
        boolean translucentStatus = preferences.getBoolean(Constants.PREFERENCE_TRANSLUCENTSTATUSBAR,
                Constants.DEFAULT_TRANSLUCENTSTATUSBAR);
        boolean translucentNavigation = preferences.getBoolean(Constants.PREFERENCE_TRANSLUCENTNAVIGATIONBAR,
                Constants.DEFAULT_TRANSLUCENTNAVIGATIONBAR);

        if (translucentStatus)
            getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (translucentNavigation)
            getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        if (translucentStatus) {
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.actionBarBackground);
        }
    }

    textViewArtist = (TextView) findViewById(R.id.textViewArtist);
    textViewTitle = (TextView) findViewById(R.id.textViewTitle);
    textViewTime = (TextView) findViewById(R.id.textViewTime);
    imageViewSongImage = (ImageView) findViewById(R.id.imageViewSongImage);
    imageButtonPrevious = (ImageButton) findViewById(R.id.imageButtonPrevious);
    imageButtonPlayPause = (ImageButton) findViewById(R.id.imageButtonPlayPause);
    imageButtonNext = (ImageButton) findViewById(R.id.imageButtonNext);
    seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
    seekBar2 = (SeekBar) findViewById(R.id.seekBar2);
    imageButtonShowSeekbar2 = (ImageButton) findViewById(R.id.imageButtonShowSeekbar2);
    imageButtonShuffle = (ImageButton) findViewById(R.id.imageButtonShuffle);
    imageButtonRepeat = (ImageButton) findViewById(R.id.imageButtonRepeat);
    imageButtonRepeatAll = (ImageButton) findViewById(R.id.imageButtonRepeatAll);
    buttonBassBoost = (Button) findViewById(R.id.buttonBassBoost);
    buttonEqualizer = (Button) findViewById(R.id.buttonEqualizer);
    buttonShake = (Button) findViewById(R.id.buttonShake);

    imageButtonShuffle.setOnClickListener(this);
    imageButtonRepeat.setOnClickListener(this);
    imageButtonRepeatAll.setOnClickListener(this);
    buttonBassBoost.setOnClickListener(this);
    buttonEqualizer.setOnClickListener(this);
    buttonShake.setOnClickListener(this);

    imageButtonShowSeekbar2.setOnClickListener(this);
    imageButtonPrevious.setOnClickListener(this);
    imageButtonPlayPause.setOnClickListener(this);
    imageButtonNext.setOnClickListener(this);
    seekBar1.setOnSeekBarChangeListener(this);
    seekBar1.setClickable(false);
    seekBar2.setOnSeekBarChangeListener(this);
    textViewTime.setOnClickListener(this);

    showSongImage = preferences.getBoolean(Constants.PREFERENCE_SHOWSONGIMAGE, Constants.DEFAULT_SHOWSONGIMAGE);
    imagesCache = new LruCache<String, Bitmap>(Constants.IMAGES_CACHE_SIZE);

    serviceIntent = new Intent(this, MusicService.class);
    startService(serviceIntent); // Starts the service if it is not running

    if (preferences.getBoolean(Constants.PREFERENCE_OPENLASTPAGEONSTART,
            Constants.DEFAULT_OPENLASTPAGEONSTART)) {
        openPage(preferences.getInt(Constants.PREFERENCE_LASTPAGE, Constants.DEFAULT_LASTPAGE));
    } else {
        openPage(PAGE_BROWSER);
    }
    loadSongFromIntent();

    layoutPlaybackControls = findViewById(R.id.layoutPlaybackControls);
    if (preferences.getBoolean(Constants.PREFERENCE_ENABLEGESTURES, Constants.DEFAULT_ENABLEGESTURES)) {
        final GestureDetectorCompat gestureDetector = new GestureDetectorCompat(this,
                new PlayerGestureListener());
        View layoutTop = findViewById(R.id.layoutTop);
        layoutTop.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });
        if (preferences.getBoolean(Constants.PREFERENCE_SHOWPLAYBACKCONTROLS,
                Constants.DEFAULT_SHOWPLAYBACKCONTROLS)) {
            layoutPlaybackControls.setVisibility(View.VISIBLE);
        }
    } else {
        layoutPlaybackControls.setVisibility(View.VISIBLE);
    }
}

From source file:com.nostra13.universalimageloader.core.decode.ContentImageDecoder.java

private static LruCache<String, Integer> getRotationCache() {
    if (sRotationCache == null) {
        sRotationCache = new LruCache<String, Integer>(1 * K);
    }//from  w ww.  java 2 s.c  o m
    return sRotationCache;
}

From source file:com.trovebox.android.app.bitmapfun.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 * /* ww w .j  a  v a 2 s .  co m*/
 * @param context The context to use
 * @param cacheParams The cache parameters to initialize the cache
 */
private void init(Context context, ImageCacheParams cacheParams) {
    final File diskCacheDir = DiskLruCache.getDiskCacheDir(context, cacheParams.uniqueName);
    this.cacheParams = cacheParams;
    // Set up disk cache
    if (cacheParams.diskCacheEnabled) {
        mDiskCache = DiskLruCache.openCache(context, diskCacheDir, cacheParams.diskCacheSize,
                cacheParams.diskCacheMaxItemSize);
        // Issue #259 fix. Sometimes previous step returns null
        if (mDiskCache != null) {
            mDiskCache.setCompressParams(cacheParams.compressFormat, cacheParams.compressQuality);
            if (cacheParams.clearDiskCacheOnStart) {
                mDiskCache.clearCache();
            }
        } else {
            CommonUtils.debug(TAG, "Couldn't create disk cache");
            TrackerUtils.trackBackgroundEvent("unsuccessfullDiskCacheCreation", diskCacheDir.getAbsolutePath());
        }
    }

    // Set up memory cache
    if (cacheParams.memoryCacheEnabled) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more
             * practical for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return Utils.getBitmapSize(bitmap);
            }
        };
    }
}

From source file:com.nostra13.universalimageloader.core.decode.ContentImageDecoder.java

private static LruCache<String, Boolean> getVideoCache() {
    if (sVideoCache == null) {
        sVideoCache = new LruCache<String, Boolean>(1 * K);
    }/* w  ww  . j  av a2 s . c o m*/
    return sVideoCache;
}

From source file:com.therealjoshua.essentials.bitmaploader.BitmapLoader.java

/**
 * Constructor/*w w w.  j  a va  2  s. co  m*/
 * 
 * @param context - a standard context 
 * @param memCache - a cache used where the calls happen on the UI thread. This cache needs to be fast
 * @param diskCache - a cache used where the calls happen on a background thread. This cache can be slower. 
 *       While you can pass in any type of Cache<String, Bitmap> object you'd like, {DiskLruCacheFascade} is 
 *       recommended.
 */
@SuppressLint("NewApi")
public BitmapLoader(Context context, Cache<String, Bitmap> memCache, Cache<String, Bitmap> diskCache) {
    this.memCache = memCache;
    this.diskCache = diskCache;
    errors = new LruCache<String, BitmapLoader.ErrorLog>(200);
    errorLogFactory = new ErrorLogFactoryImpl(60 * 1000);

    if (!(context instanceof Service)) {
        appContext = context.getApplicationContext();
    } else {
        appContext = context;
    }

    PackageManager pm = context.getPackageManager();
    int hasPerm = pm.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE,
            context.getPackageName());
    if (hasPerm != PackageManager.PERMISSION_GRANTED) {
        canAccessNetworkState = true;
    }
    connectionFactory = new ConnectionFactoryImpl();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        executor = PortedAsyncTask.PENTA_THREAD_EXECUTOR;
    } else {
        executor = PortedAsyncTask.DUAL_THREAD_EXECUTOR;
    }
}

From source file:com.gelakinetic.mtgfam.helpers.lruCache.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///  w  w w .j  av  a 2s . co m
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {

        // 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();
    }
}

From source file:com.eamonndunne.londontraffic.view.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///from w  w w. j a  v  a2 s. com
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {

        // 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();
    }
}