Example usage for android.util LruCache LruCache

List of usage examples for android.util LruCache LruCache

Introduction

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

Prototype

public LruCache(int maxSize) 

Source Link

Usage

From source file:com.squareup.picasso3.PlatformLruCache.java

/** Create a cache with a given maximum size in bytes. */
PlatformLruCache(int maxByteCount) {
    cache = new LruCache<String, BitmapAndSize>(maxByteCount != 0 ? maxByteCount : 1) {
        @Override/*  w  w w  .  j  a  v a2  s  .  c o m*/
        protected int sizeOf(String key, BitmapAndSize value) {
            return value.byteCount;
        }
    };
}

From source file:com.fuzz.emptyhusk.prefab.InlineAdapter.java

public InlineAdapter(int count) {
    this.count = count;
    viewCache = new LruCache<>(4);
}

From source file:com.fuzz.emptyhusk.SimplePagerAdapter.java

public SimplePagerAdapter(@NonNull String[] values) {
    this.values = values;
    viewCache = new LruCache<>(values.length);
}

From source file:jp.tkgktyk.xposed.forcetouchdetector.app.util.IconCache.java

public IconCache(Context context) {
    mIconSize = context.getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);

    //        int max = (int) (Runtime.getRuntime().maxMemory() / 1024); // KB
    //        mMemoryCache = new LruCache<String, Bitmap>(max / 16) {
    //            @Override
    //            protected int sizeOf(String key, Bitmap value) {
    //                return value.getByteCount() / 1024; // KB
    //            }
    ////from  ww w .j  ava  2  s. c o  m
    //            @Override
    //            protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
    //                if (!oldValue.isRecycled()) {
    //                    oldValue.recycle();
    //                }
    //            }
    //        };

    mMemoryCache = new LruCache<String, Bitmap>(30) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return 1;
        }
    };
}

From source file:com.nike.plusgps.nikeplusgallery.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dbHelper = new DBHelper(this); // Creates the database
    dbHelper.deleteAllResponse(); // Clears the JSON response cache
    dbHelper.deleteAllMedia(); // Clears the JSON images cache

    // Get memory class of this device, exceeding this amount will throw an
    // OutOfMemory exception.
    final int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = 1024 * 1024 * memClass / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override/*from www.java  2s . c o m*/
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in bytes rather than number of items.
            return bitmap.getByteCount();
        }
    };

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {

        setContentView(R.layout.activity_main_port);
        GridView view = (GridView) findViewById(R.id.gridView);
        flickrFeedList = new ArrayList<FlickrFeed>();
        new JSONParser()
                .execute("http://api.flickr.com/services/feeds/photos_public.gne?tags=nike&format=json");
        adapter = new FlickrFeedAdapter(getApplicationContext(), R.layout.single_elem_port, flickrFeedList,
                dbHelper, mMemoryCache);
        view.setAdapter(adapter);

    } else {

        setContentView(R.layout.activity_main_land);
        carouselElement = (LinearLayout) findViewById(R.id.carousel);
        // Compute width of a carousel item based on screen width and initial item count
        final DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        final int imageWidth = (int) (displayMetrics.widthPixels / INITIAL_ITEMS_COUNT);

        ImageView imageItem;
        String imgURL;
        for (int i = 0; i < flickrFeedList.size(); ++i) {
            imageItem = new ImageView(this);
            imgURL = flickrFeedList.get(i).getMedia();
            new DownloadImageTask(imageItem).execute(imgURL);
            imageItem.setLayoutParams(new LinearLayout.LayoutParams(imageWidth, imageWidth));
            carouselElement.addView(imageItem);
        }
    }
}

From source file:com.faayda.imageloader.ImageCache.java

/**
 * Initialize the cache.//  w ww.  j  ava  2 s  .c  o m
 *
 * @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;
        }
    };
}

From source file:org.vqeg.viqet.activities.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //set orientation potrait if its phone
    if (getResources().getBoolean(R.bool.portrait_only)) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else {/*from  w  w  w  . j a va2s  .c o m*/
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = 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;
        }
    };

    this.mainPage = findViewById(R.id.drawer_layout);
    this.downloadScreen = findViewById(R.id.downloading_screen);
    this.internetRequiredScreen = findViewById(R.id.internet_required_screen);

    mTitle = mDrawerTitle = "VIQET";
    mOptionsTitles = getResources().getStringArray(R.array.options_array);
    mImageResources = new int[] { R.drawable.home, R.drawable.camera_results_icon,
            R.drawable.photo_quality_results, R.drawable.help, R.drawable.about, R.drawable.setting };
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new CustomDrawerListAdapter(this, mOptionsTitles, mImageResources));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        //todo check
        selectItem(0);
        lastClicked = 0;
    } else {
        int pos = savedInstanceState.getInt("FRAGMENT");
        selectItem(pos);
        lastClicked = pos;
    }

    Button retryDownloadButton = (Button) findViewById(R.id.retryDownload);
    retryDownloadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (SystemInfo.isNetworkPresent(getApplicationContext())) {
                downloadScreen.setVisibility(View.VISIBLE);
                internetRequiredScreen.setVisibility(View.INVISIBLE);
                downloadRemoteInfo(PhotoInspectorService.FETCH_VERSION_ACTION);
            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.noInternetError), Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    //Check remote info
    RemoteInfo remoteInfo = RemoteInfoProvider.getRemoteInfo();

    if (remoteInfo == null) {
        mainPage.setVisibility(View.INVISIBLE);
        if (SystemInfo.isNetworkPresent(getApplicationContext())) {
            downloadScreen.setVisibility(View.VISIBLE);
            internetRequiredScreen.setVisibility(View.INVISIBLE);
            downloadRemoteInfo(PhotoInspectorService.FETCH_VERSION_ACTION);
        } else {
            downloadScreen.setVisibility(View.INVISIBLE);
            internetRequiredScreen.setVisibility(View.VISIBLE);
        }
    } else {
        //downloadRemoteInfo(PhotoInspectorService.FETCH_VERSION_MODEL_CHANGED_ACTION);
        downloadRemoteInfo(PhotoInspectorService.INSPECT_ALL_PENDING_PHOTOS_ACTION);
    }
    checkFirstRun();
}

From source file:com.mimming.sugarglider.MapImageManager.java

private MapImageManager() {
    mapCache = new LruCache<String, Bitmap>(CACHE_SIZE) {
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount() / 1024;
        }/* ww  w .  j  a  v a2 s  .com*/
    };
    mMapType = MapType.HIGH_CONTRAST;
}

From source file:mobi.tattu.utils.image.ImageCache.java

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

    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (Utils.isDebug())
            Logger.d(this, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");

        getReusableBitmaps();

        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.hyphenate.easeui.utils.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *//*from  w ww. jav a2 s  .c  o m*/
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        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;
            }
        };
    }

}