List of usage examples for android.support.v4.util LruCache LruCache
public LruCache(int maxSize)
From source file:com.yooiistudios.newskit.core.cache.volley.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache *//*from w ww . ja v a 2 s . c om*/ private void init(Resources resources, ImageCacheParams cacheParams) { mResources = resources; mCacheParams = cacheParams; //BEGIN_INCLUDE(init_memory_cache) // Set up memory cache if (mCacheParams.memoryCacheEnabled) { NLLog.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 (Device.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 (Device.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<>(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:ca.ualberta.cmput301w14t08.geochan.managers.ThreadManager.java
/** * Private constructor due to singleton pattern. *//*from ww w . j a v a 2 s . com*/ private ThreadManager() { commentListCache = new LruCache<String, CommentList>(MAXIMUM_CACHE_SIZE); getImageCache = new LruCache<String, Bitmap>(MAXIMUM_CACHE_SIZE); getPOICache = new LruCache<String, String>(MAXIMUM_CACHE_SIZE); getCommentListRunnableQueue = new LinkedBlockingQueue<Runnable>(); getCommentsRunnableQueue = new LinkedBlockingQueue<Runnable>(); postImageRunnableQueue = new LinkedBlockingQueue<Runnable>(); postRunnableQueue = new LinkedBlockingQueue<Runnable>(); updateRunnableQueue = new LinkedBlockingQueue<Runnable>(); getImageRunnableQueue = new LinkedBlockingQueue<Runnable>(); getThreadCommentsRunnableQueue = new LinkedBlockingQueue<Runnable>(); getPOIRunnableQueue = new LinkedBlockingQueue<Runnable>(); getCommentsTaskQueue = new LinkedBlockingQueue<GetCommentsTask>(); postTaskQueue = new LinkedBlockingQueue<PostTask>(); getImageTaskQueue = new LinkedBlockingQueue<GetImageTask>(); getThreadCommentsTaskQueue = new LinkedBlockingQueue<GetThreadCommentsTask>(); getPOITaskQueue = new LinkedBlockingQueue<GetPOITask>(); getCommentListPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, getCommentListRunnableQueue); getCommentsPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, getCommentsRunnableQueue); postImagePool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, postImageRunnableQueue); postPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, postRunnableQueue); updatePool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, updateRunnableQueue); getImagePool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, getImageRunnableQueue); getThreadCommentsPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, getThreadCommentsRunnableQueue); getPOIPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, getPOIRunnableQueue); handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message inputMessage) { switch (inputMessage.what) { case POST_TASK_COMPLETE: PostTask postTaskComplete = (PostTask) inputMessage.obj; if (postTaskComplete.getDialog() != null) { postTaskComplete.getDialog().dismiss(); } ThreadComment threadComment = postTaskComplete.getThreadComment(); if (threadComment != null) { if (!postTaskComplete.isEdit()) { // Update the model and sort accordingly ThreadList.addThread(threadComment); SortUtil.sortThreads(PreferencesManager.getInstance().getThreadSort(), ThreadList.getThreads()); } FragmentActivity activity = (FragmentActivity) context; ThreadListFragment fragment = (ThreadListFragment) activity.getSupportFragmentManager() .findFragmentByTag("threadListFrag"); if (fragment != null) { fragment.finishReload(); } } break; case GET_THREADS_COMPLETE: GetThreadCommentsTask threadTask = (GetThreadCommentsTask) inputMessage.obj; threadTask.getFragment().finishReload(); recycleGetThreadCommentsTask(threadTask); break; case GET_THREADS_FAILED: GetThreadCommentsTask threadTaskFail = (GetThreadCommentsTask) inputMessage.obj; threadTaskFail.getFragment().finishReload(); recycleGetThreadCommentsTask(threadTaskFail); break; case GET_COMMENTS_COMPLETE: GetCommentsTask task = (GetCommentsTask) inputMessage.obj; task.getFragment().finishReload(); recycleCommentsTask(task); break; case GET_COMMENTS_FAILED: GetCommentsTask taskFail = (GetCommentsTask) inputMessage.obj; taskFail.getFragment().finishReload(); recycleCommentsTask(taskFail); break; case GET_COMMENT_LIST_RUNNING: break; case GET_COMMENT_LIST_FAILED: GetCommentsTask taskListFail = (GetCommentsTask) inputMessage.obj; taskListFail.getFragment().finishReload(); recycleCommentsTask(taskListFail); break; case GET_IMAGE_RUNNING: GetImageTask imageTask = (GetImageTask) inputMessage.obj; if (imageTask.getDialog() != null) { imageTask.getDialog().show(); } break; case GET_IMAGE_FAILED: GetImageTask imageTaskFail = (GetImageTask) inputMessage.obj; if (imageTaskFail.getDialog() != null) { imageTaskFail.getDialog().dismiss(); } recycleGetImageTask(imageTaskFail); break; case GET_IMAGE_COMPLETE: GetImageTask imageTaskComplete = (GetImageTask) inputMessage.obj; if (imageTaskComplete.getDialog() != null) { imageTaskComplete.getDialog().dismiss(); } Bitmap bitmap = imageTaskComplete.getImageCache(); String id = imageTaskComplete.getId(); ImageView view = imageTaskComplete.getmImageWeakRef().get(); if (view != null) { view.setImageBitmap(bitmap); } CacheManager.getInstance().serializeImage(bitmap, id); recycleGetImageTask(imageTaskComplete); break; case GET_POI_RUNNING: GetPOITask poiTaskRunning = (GetPOITask) inputMessage.obj; if (poiTaskRunning.getDialog() != null) { poiTaskRunning.getDialog().show(); } break; case GET_POI_COMPLETE: GetPOITask poiTaskComplete = (GetPOITask) inputMessage.obj; if (poiTaskComplete.getDialog() != null) { poiTaskComplete.getDialog().dismiss(); } if (poiTaskComplete.getMarker() != null) { poiTaskComplete.getMarker().setSubDescription((poiTaskComplete.getPOICache())); poiTaskComplete.getMarker().showInfoWindow(); } poiTaskComplete.getLocation().setLocationDescription(poiTaskComplete.getPOICache()); recycleGetPOITask(poiTaskComplete); break; case GET_POI_FAILED: GetPOITask poiTaskFailed = (GetPOITask) inputMessage.obj; if (poiTaskFailed.getDialog() != null) { poiTaskFailed.getDialog().dismiss(); } if (poiTaskFailed.getMarker() != null) { poiTaskFailed.getMarker().setSubDescription(("Unknown Location")); poiTaskFailed.getMarker().showInfoWindow(); } poiTaskFailed.getLocation().setLocationDescription("Unknown Location"); recycleGetPOITask(poiTaskFailed); break; case POST_GET_POI_RUNNING: PostTask postPoiTaskRunning = (PostTask) inputMessage.obj; if (postPoiTaskRunning.getDialog() != null) { postPoiTaskRunning.getDialog().show(); } break; case POST_GET_POI_COMPLETE: PostTask postPoiTaskComplete = (PostTask) inputMessage.obj; if (postPoiTaskComplete.getDialog() != null) { postPoiTaskComplete.getDialog().setMessage("Posting to Server"); } break; case POST_GET_POI_FAILED: PostTask postPoiTaskFailed = (PostTask) inputMessage.obj; if (postPoiTaskFailed.getDialog() != null) { postPoiTaskFailed.getDialog().dismiss(); } break; case UPDATE_FAILED: PostTask postTaskUpdateFailed = (PostTask) inputMessage.obj; if (postTaskUpdateFailed.getDialog() != null) { postTaskUpdateFailed.getDialog().dismiss(); } break; case POST_FAILED: PostTask postTaskFailed = (PostTask) inputMessage.obj; if (postTaskFailed.getDialog() != null) { postTaskFailed.getDialog().dismiss(); } break; case POST_RUNNING: PostTask postTaskRun = (PostTask) inputMessage.obj; if (postTaskRun.getDialog() != null && !postTaskRun.getDialog().isShowing()) { postTaskRun.getDialog().show(); } break; case POST_IMAGE_FAILED: PostTask postTaskImageFailed = (PostTask) inputMessage.obj; if (postTaskImageFailed.getDialog() != null) { postTaskImageFailed.getDialog().dismiss(); } break; default: super.handleMessage(inputMessage); break; } } }; }
From source file:com.yineng.ynmessager.cache.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams//w w w .j a v a 2 s .co m * 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(); } }
From source file:me.onemobile.client.image.ImageCache.java
/** * Initialize the cache, providing all parameters. * //from www. j av a 2 s. c o 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); // Set up disk cache if (cacheParams.diskCacheEnabled) { mDiskCache = DiskLruCache.openCache(context, diskCacheDir, cacheParams.diskCacheSize); if (mDiskCache != null) { mDiskCache.setCompressParams(cacheParams.compressFormat, cacheParams.compressQuality); if (cacheParams.clearDiskCacheOnStart) { mDiskCache.clearCache(); } } } // 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:ru.freshartapp.automarka.utils.ImageCache.java
/** * Initialize the cache, providing all parameters. * //from ww w .ja v a 2 s .com * @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); // Set up disk cache if (cacheParams.diskCacheEnabled) { this.mDiskCache = DiskLruCache.openCache(context, diskCacheDir, cacheParams.diskCacheSize); this.mDiskCache.setCompressParams(cacheParams.compressFormat, cacheParams.compressQuality); if (cacheParams.clearDiskCacheOnStart) { this.mDiskCache.clearCache(); } } // Set up memory cache if (cacheParams.memoryCacheEnabled) { this.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.rivbird.guichecker.bitmapfun.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache *///from w w w . ja v a 2 s .c o m 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(); } }
From source file:com.vishwa.pinit.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); mFrameLayout = new FrameLayout(this); if (getResources().getBoolean(R.bool.portrait_only)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }/*from www . java 2 s . c o m*/ setContentView(mFrameLayout); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.activity_main, mFrameLayout); inflater.inflate(R.layout.splash_screen, mFrameLayout); mHandler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { Animation fadeOutAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out); fadeOutAnimation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { mFrameLayout.removeViewAt(1); if (PinItUtils.isUsersFirstLogin(mCurrentUsername, getApplicationContext())) { if (!DEBUG) { handleUsersFirstTime(); } } } }); mFrameLayout.getChildAt(1).startAnimation(fadeOutAnimation); } }; mHandler.postDelayed(runnable, 2300); mCurrentUsername = ParseUser.getCurrentUser().getUsername(); final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 10; RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getSupportFragmentManager()); mMemoryCache = mRetainFragment.mRetainedCache; if (mMemoryCache == null) { mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getByteCount() / 1024; } }; mRetainFragment.mRetainedCache = mMemoryCache; } mAllNotesButton = (Button) findViewById(R.id.main_all_notes_button); mYourNotesButton = (Button) findViewById(R.id.main_your_notes_button); setProgressBarIndeterminateVisibility(false); mAllNotesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LatLngBounds mapBounds = mMap.getProjection().getVisibleRegion().latLngBounds; LatLng southwest = mapBounds.southwest; LatLng northeast = mapBounds.northeast; mMapViewMode = MapViewMode.ALL_NOTES; for (Marker marker : mMarkerList) { marker.remove(); } mMarkerList.clear(); mNoteStore.clear(); mReverseNoteStore.clear(); LatLngTuple tuple = new LatLngTuple(southwest, northeast); LoadNotesTask currentUserNotesTask = new LoadNotesTask(tuple, false); currentUserNotesTask.execute(); setProgressBarIndeterminateVisibility(true); } }); mYourNotesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LatLngBounds mapBounds = mMap.getProjection().getVisibleRegion().latLngBounds; LatLng southwest = mapBounds.southwest; LatLng northeast = mapBounds.northeast; for (Marker marker : mMarkerList) { marker.remove(); } mMarkerList.clear(); mNoteStore.clear(); mReverseNoteStore.clear(); mMapViewMode = MapViewMode.YOUR_NOTES; LatLngTuple tuple = new LatLngTuple(southwest, northeast); LoadNotesTask currentUserNotesTask = new LoadNotesTask(tuple, true); currentUserNotesTask.execute(); setProgressBarIndeterminateVisibility(true); } }); try { MapsInitializer.initialize(this); if (!PinItUtils.isOnline(getApplicationContext())) { PinItUtils.createAlert("Internet connection not found.", "Connect to the Internet and press the refresh button at the top", this); mHasInternet = false; } else { mHasInternet = true; loadMapWhenOnline(); } } catch (GooglePlayServicesNotAvailableException e) { PinItUtils.createAlert("We're sorry", "It seems that your phone doesn't have Google Play" + "services installed, or is missing the maps application. Please download both of" + "these and then try running this application", MainActivity.this); } }
From source file:com.azilen.waiterpad.managers.language.LanguageManager.java
public LanguageManager() { languageCache = new LruCache<String, Object>(maxSize); }
From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java
/** * Search a cached bitmap from an url./*w ww .j a v a 2s . co m*/ * rotationAngle is set to Integer.MAX_VALUE when undefined : the EXIF metadata must be checked. * * @param baseFile the base file * @param url the media url * @param rotation the bitmap rotation * @param mimeType the mime type * @return the cached bitmap */ public static Bitmap bitmapForURL(Context context, File baseFile, String url, int rotation, String mimeType) { Bitmap bitmap = null; // sanity check if (null != url) { if (null == mBitmapByUrlCache) { int lruSize = Math.min(20 * 1024 * 1024, (int) Runtime.getRuntime().maxMemory() / 8); Log.d(LOG_TAG, "bitmapForURL lruSize : " + lruSize); mBitmapByUrlCache = new LruCache<String, Bitmap>(lruSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight(); // size in bytes } }; } // the image is downloading in background if (null != getMediaDownloadWorkerTask(url)) { return null; } // the url is invalid if (isMediaUrlUnreachable(url)) { return null; } synchronized (mSyncObject) { bitmap = mBitmapByUrlCache.get(url); } // check if the image has not been saved in file system if ((null == bitmap) && (null != baseFile)) { String filename = null; // the url is a file one if (url.startsWith("file:")) { // try to parse it try { Uri uri = Uri.parse(url); filename = uri.getPath(); } catch (Exception e) { Log.e(LOG_TAG, "bitmapForURL #1 : " + e.getLocalizedMessage()); } // cannot extract the filename -> sorry if (null == filename) { return null; } } // not a valid file name if (null == filename) { filename = buildFileName(url, mimeType); } try { File file = filename.startsWith(File.separator) ? new File(filename) : new File(baseFile, filename); if (!file.exists()) { Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist"); return null; } InputStream fis = new FileInputStream(file); // read the metadata if (Integer.MAX_VALUE == rotation) { rotation = ImageUtils.getRotationAngleForBitmap(context, Uri.fromFile(file)); } if (null != fis) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; try { bitmap = BitmapFactory.decodeStream(fis, null, options); } catch (OutOfMemoryError error) { System.gc(); Log.e(LOG_TAG, "bitmapForURL() : Out of memory 1 " + error); } // try again if (null == bitmap) { try { bitmap = BitmapFactory.decodeStream(fis, null, options); } catch (OutOfMemoryError error) { Log.e(LOG_TAG, "bitmapForURL() Out of memory 2" + error); } } if (null != bitmap) { synchronized (mSyncObject) { if (0 != rotation) { try { android.graphics.Matrix bitmapMatrix = new android.graphics.Matrix(); bitmapMatrix.postRotate(rotation); Bitmap transformedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix, false); bitmap.recycle(); bitmap = transformedBitmap; } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "bitmapForURL rotation error : " + ex.getLocalizedMessage()); } } // cache only small images // caching large images does not make sense // it would replace small ones. // let assume that the application must be faster when showing the chat history. if ((bitmap.getWidth() < 1000) && (bitmap.getHeight() < 1000)) { mBitmapByUrlCache.put(url, bitmap); } } } fis.close(); } } catch (FileNotFoundException e) { Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist"); } catch (Exception e) { Log.e(LOG_TAG, "bitmapForURL() " + e); } } } return bitmap; }
From source file:com.hippo.ehviewer.EhApplication.java
@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); }//from ww w. j ava2s . c o m return application.mGalleryDetailCache; }