/** * 从缓存中获取图片 * * @param url * @return */ public Bitmap getBitmapFromCache(String url) { Bitmap bitmap; // 先从硬引用缓存获取数据 synchronized (mLruCache) { bitmap = mLruCache.get(url); if (bitmap != null) { // 如果找到的话,把元素移到LinkedHashMap的最前面,从而保证在LRU算法中是最后被删除 mLruCache.remove(url); mLruCache.put(url, bitmap); return bitmap; } } // 如果硬引用缓存找不到数据,进入软引用缓存 synchronized (mSoftCache) { SoftReference<Bitmap> bitmapReference = mSoftCache.get(url); if (bitmapReference != null) { bitmap = bitmapReference.get(); if (bitmap != null) { // 将图片移回硬缓存 mLruCache.put(url, bitmap); mSoftCache.remove(url); return bitmap; } else { mSoftCache.remove(url); } } } return null; }
// 从缓存中获取Bitmap数据 public Bitmap getBitmapFromCache(String url) { Bitmap bitmap; // 加上同步锁保证同一时刻只执行一个对象 // 从硬引用获得数据 synchronized (mLruCache) { bitmap = mLruCache.get(url); if (bitmap != null) { // 如果有bitmap对象。则将这个对象从硬引用中先移除在添加。放到前面防止被逐出。 System.out.println("!!!!-----》命中硬存mLrucache"); mLruCache.remove(url); mLruCache.put(url, bitmap); return bitmap; } } // 从软引用获得数据 synchronized (mSoftCache) { SoftReference<Bitmap> bitmapReference = mSoftCache.get(url); if (bitmapReference != null) { bitmap = bitmapReference.get(); if (bitmap != null) { // 把存在的这个图片提升到硬缓存 System.out.println("!!!!命中软缓存mSoftCache"); } else { mSoftCache.remove(url); } } } return null; }
public Bitmap getBitmap(String url) { Bitmap bit = mCache.get(url); if (bit == null) { /** 一级缓存没有拿到,从二级缓存中取 */ if (isDebug) System.out.println(id + "multicache -- 一级缓存没有获取到,准备从二级缓存中获取"); SoftReference<Bitmap> soft = softCache.get(url); if (soft == null) { /** 二级缓存没有拿到,文件中取得 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存没有获取到,准备从文件中获取"); bit = BitmapUtils.readFromFile(fileCache, url); } else { /** 从二级缓存中获得 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存获取到,但不确定是否存在bitmap"); bit = soft.get(); if (bit == null) { /** 二级缓存中被回收,文件中获取 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存获取到但是被回收了,从文件中获取"); bit = BitmapUtils.readFromFile(fileCache, url); } else { /** 确实在二级缓存中,加入一级缓存,从二级缓存中移除 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存获取到加入一级缓存,移除二级缓存"); mCache.put(url, bit); softCache.remove(soft); } } } else { if (isDebug) System.out.println(id + "multicache -- 从一级缓存中获取到"); } if (isDebug) { if (bit == null) System.out.println(id + "multicache -- 最终没有获取到,网络获取"); else System.out.println(id + "multicache -- 最终获取到资源------"); } return bit; }
/** * @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 static synchronized String normalize(String input) { if (normalizationCache == null) { normalizationCache = new LruCache<String, String>(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; }
/** 从缓存中获取图片 */ public Bitmap getBitmapFromCache(String url) { Bitmap bitmap; // 先从硬引用缓存中获取 synchronized (mLruCache) { bitmap = mLruCache.get(url); if (bitmap != null) { // 如果找到的话,把元素移到LinkedHashMap的最前面,从而保证在LRU算法中是最后被删除 mLruCache.remove(url); mLruCache.put(url, bitmap); System.out.println("硬引用中找到了"); return bitmap; } else { System.out.println("硬引用中没找到"); } } // 如果硬引用缓存中找不到,到软引用缓存中找 synchronized (mSoftCache) { SoftReference<Bitmap> bitmapReference = mSoftCache.get(url); if (bitmapReference != null) { bitmap = bitmapReference.get(); if (bitmap != null) { // 将图片移回硬缓存 mLruCache.put(url, bitmap); mSoftCache.remove(url); System.out.println("软引用中找到了"); return bitmap; } else { mSoftCache.remove(url); System.out.println("软引用中没找到"); } } } return null; }
public void addBitmapToCache(String url, Bitmap bitmap) { if (url != null && bitmap != null) { if (mMemoryCache != null && mMemoryCache.get(url) == null) { mMemoryCache.put(url, bitmap); } if (mDiskCache == null) { return; } String str = hashKeyForDisk(url); try { if (mDiskCache.get(str) != null) return; DiskLruCache.Editor editor = mDiskCache.edit(str); if (editor == null) return; OutputStream output = editor.newOutputStream(0); bitmap.compress(mCacheParams.compressFormat, mCacheParams.compressQuality, output); editor.commit(); } catch (IOException e) { LogUtils.LOGE(TAG, "addBitmapToCache - " + e); } } }
private Typeface getTypeface(final String filename) { Typeface typeface = mCache.get(filename); if (typeface == null) { typeface = Typeface.createFromAsset(mAssetManager, "fonts/" + filename); mCache.put(filename, typeface); } return typeface; }
/** * 初始化用户头像缓存 * * @param userIDList 用户ID List * @param length 头像宽高 * @param callBack 缓存回调 */ public void setAvatarCache( final List<String> userIDList, final int length, final cacheAvatarCallBack callBack) { final Handler handler = new Handler() { @Override public void handleMessage(android.os.Message msg) { super.handleMessage(msg); if (msg.getData() != null) { callBack.onCacheAvatarCallBack(msg.getData().getInt("status", -1)); } } }; for (final String userID : userIDList) { // 若为CurrentUser,直接获取本地的头像(CurrentUser本地头像为最新) if (userID.equals(JMessageClient.getMyInfo().getUserName())) { File file = JMessageClient.getMyInfo().getAvatar(); if (file == null || !file.exists()) { continue; } else { Bitmap bitmap = BitmapLoader.getBitmapFromFile(file.getAbsolutePath(), length, length); if (null != bitmap) { mMemoryCache.put(userID, bitmap); } continue; } } else if (mMemoryCache.get(userID) != null) { continue; } else { JMessageClient.getUserInfo( userID, new GetUserInfoCallback(false) { @Override public void gotResult(int i, String s, UserInfo userInfo) { if (i == 0) { File file = userInfo.getAvatar(); if (file != null) { Bitmap bitmap = BitmapLoader.getBitmapFromFile(file.getAbsolutePath(), length, length); addBitmapToMemoryCache(userID, bitmap); } else { // Bitmap bitmap = // BitmapLoader.getBitmapFromFile(getR.drawable.head_icon, length, length); } android.os.Message msg = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putInt("status", 0); msg.setData(bundle); msg.sendToTarget(); } } }); } } }
/** * Adds a bitmap to both memory and disk cache. * * @param data Unique identifier for the bitmap to store * @param bitmap The bitmap to store */ public void addBitmapToCache(String data, Bitmap bitmap) { if (data == null || bitmap == null) { return; } // Add to memory cache if (mMemoryCache != null && mMemoryCache.get(data) == null) { mMemoryCache.put(data, bitmap); } }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mInnerRectF.set(0, 0, canvas.getWidth(), canvas.getHeight()); final int halfBorder = (int) (mStrokePaint.getStrokeWidth() / 2f + 0.5f); mInnerRectF.inset(halfBorder, halfBorder); canvas.drawArc(mInnerRectF, 0, 360, true, mBackgroundPaint); switch (mProgressFillType) { case FILL_TYPE_RADIAL: float sweepAngle = 360 * mProgress / mMax; canvas.drawArc(mInnerRectF, mStartAngle, sweepAngle, true, mProgressPaint); break; case FILL_TYPE_CENTER: float centerX = canvas.getWidth() / 2; float centerY = canvas.getHeight() / 2; float radius = (canvas.getWidth() / 2) * ((float) mProgress / mMax); canvas.drawCircle( centerX, centerY, radius + 0.5f - mStrokePaint.getStrokeWidth(), mProgressPaint); break; default: throw new IllegalArgumentException("Invalid Progress Fill = " + mProgressFillType); } if (!TextUtils.isEmpty(mText) && mShowText) { if (!TextUtils.isEmpty(mTypeface)) { Typeface typeface = sTypefaceCache.get(mTypeface); if (null == typeface && null != getResources()) { AssetManager assets = getResources().getAssets(); if (null != assets) { typeface = Typeface.createFromAsset(assets, mTypeface); sTypefaceCache.put(mTypeface, typeface); } } mTextPaint.setTypeface(typeface); } int xPos = canvas.getWidth() / 2; int yPos = (int) ((canvas.getHeight() / 2) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2)); canvas.drawText(mText, xPos, yPos, mTextPaint); } if (null != mImage && mShowImage) { int drawableSize = mImage.getIntrinsicWidth(); mImageRect.set(0, 0, drawableSize, drawableSize); mImageRect.offset((getWidth() - drawableSize) / 2, (getHeight() - drawableSize) / 2); mImage.setBounds(mImageRect); mImage.draw(canvas); } if (mShowStroke) { canvas.drawOval(mInnerRectF, mStrokePaint); } }
public static void printStatistics() { final int hit = sThumbsCache.hitCount(); final int missed = sThumbsCache.missCount(); final int eviction = sThumbsCache.evictionCount(); final int created = sThumbsCache.createCount(); final int put = sThumbsCache.putCount(); Logger.debug( "hit(%.2f, %d / %d): m(%d), e(%d), c(%d), p(%d)", ((float) hit / (hit + missed)), hit, (hit + missed), missed, eviction, created, put); }
/** Load the {@link Typeface} and apply to a spannable. */ public TypefaceSpan(Context context, String typefaceName) { mTypeface = sTypefaceCache.get(typefaceName); if (mTypeface == null) { mTypeface = Typeface.createFromAsset( context.getApplicationContext().getAssets(), String.format("%s", typefaceName)); // Cache the loaded Typeface sTypefaceCache.put(typefaceName, mTypeface); } }
/** * Adds a bitmap to both memory and disk cache. * * @param data Unique identifier for the bitmap to store * @param bitmap The bitmap to store */ public void addBitmapToCache(String data, Bitmap bitmap) { if (data == null || bitmap == null) { return; } synchronized (mMemoryCache) { // Add to memory cache if (mMemoryCache.get(data) == null) { LOGD(TAG, "Memory cache put - " + data); mMemoryCache.put(data, bitmap); } } }
public void loadImage(View view, MusicDirectory.Entry entry, boolean large, boolean crossfade) { if (largeUnknownImage != null && ((BitmapDrawable) largeUnknownImage).getBitmap().isRecycled()) { createLargeUnknownImage(view.getContext()); } if (entry == null || entry.getCoverArt() == null) { setUnknownImage(view, large); return; } int size = large ? imageSizeLarge : imageSizeDefault; Bitmap bitmap = cache.get(getKey(entry.getCoverArt(), size)); if (bitmap != null && !bitmap.isRecycled()) { final Drawable drawable = Util.createDrawableFromBitmap(this.context, bitmap); setImage(view, drawable, large); if (large) { nowPlaying = bitmap; } return; } if (!large) { setUnknownImage(view, large); } queue.offer( new Task( view.getContext(), entry, size, imageSizeLarge, large, new ViewTaskHandler(view, crossfade))); }
public CacheItem put(final String url, final Object obj, DateTime expiresAt) { if (obj == null) { return null; } Timber.d(String.format("put(%s)", url)); CacheItem d = new CacheItem(obj, expiresAt); if (null != mMemoryCache) { mMemoryCache.put(url, d); } if (null != mDiskCache) { checkNotOnMainThread(); final String key = transformUrlForDiskCacheKey(url); final ReentrantLock lock = getLockForDiskCacheEdit(key); lock.lock(); try { DiskLruCache.Editor editor = mDiskCache.edit(key); writeValueToDisk(editor.newOutputStream(0), obj); writeExpirationToDisk(editor.newOutputStream(1), expiresAt); editor.commit(); } catch (IOException e) { e.printStackTrace(); } finally { lock.unlock(); scheduleDiskCacheFlush(); } } return d; }
/** Shows the dialog box from which to select the sections */ @SuppressWarnings("unchecked") private void showSectionBox() { AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this); String title = mLanguageManager.getSelectSection(); builder.setTitle(title); // get it from the cache lstSection = (List<Section>) sectionCache.get(Global.SECTIONS); if (lstSection != null) { String[] sections = new String[lstSection.size()]; int i = 0; for (Section section : lstSection) { // stores the values into the array sections[i] = section.getSectionName().toString(); // checks if the section id is equal to the section id selected if (section .getSectionName() .toString() .equalsIgnoreCase(Prefs.getKey(Prefs.SECTION_NAME))) { selectionVal = i; } i++; } builder.setSingleChoiceItems(sections, selectionVal, this); builder.show(); } }
public static void addSvgToCache(final int key, final SVG svg) { if (sCache == null) { createCache(); } sCache.put(key, svg); }
public static SVG getSvgFromCache(final int key) { SVG result = null; if (sCache != null) { result = sCache.get(key); } return result; }
/** * 根据key来获取内存中的图片 * * @param key * @return */ public Bitmap getBitmapFromMemCache(String key) { if (key == null) { return null; } else { return mMemoryCache.get(key); } }
// 增加硬缓存对象。 public void addBitmapToCache(String url, Bitmap bitmap) { if (bitmap != null) { synchronized (mLruCache) { mLruCache.put(url, bitmap); } } }
private static Bitmap getBitmapFromMemCache(String key) { if (key == null) { return null; } return _memoryCache.get(key); }
private void addBitmapToCache(String key, BitmapDrawable drawable) { if (drawable != null && getBitmapFromCache(key) == null) { if (RecyclingBitmapDrawable.class.isInstance(drawable)) { ((RecyclingBitmapDrawable) drawable).setIsCached(true); } mMemoryCache.put(key, drawable); Log.d(TAG, "cache size: " + mMemoryCache.size()); } Log.d( TAG, "cache: number of puts: " + mMemoryCache.putCount() + ", number of evicts: " + mMemoryCache.evictionCount()); }
public Bitmap getBitmapFromMemCache(String key) { Bitmap bitmap = mLruCache.get(key); if (bitmap != null && !bitmap.isRecycled()) { return bitmap; } return null; }
public void loadImage( Context context, RemoteControlClient remoteControl, MusicDirectory.Entry entry) { if (largeUnknownImage != null && ((BitmapDrawable) largeUnknownImage).getBitmap().isRecycled()) { createLargeUnknownImage(context); } if (entry == null || entry.getCoverArt() == null) { setUnknownImage(remoteControl); return; } Bitmap bitmap = cache.get(getKey(entry.getCoverArt(), imageSizeLarge)); if (bitmap != null && !bitmap.isRecycled()) { Drawable drawable = Util.createDrawableFromBitmap(this.context, bitmap); setImage(remoteControl, drawable); return; } setUnknownImage(remoteControl); queue.offer( new Task( context, entry, imageSizeLarge, imageSizeLarge, false, new RemoteControlClientTaskHandler(remoteControl))); }
/** 添加图片到缓存 */ public void addBitmapToCache(String url, Bitmap bitmap) { if (bitmap != null) { synchronized (mLruCache) { mLruCache.put(url, bitmap); System.out.println("图片已添加到内存缓存"); } } }
public CacheItem getFromMemoryCache(final String url, boolean checkExpiration) { CacheItem result = null; if (null != mMemoryCache) { synchronized (mMemoryCache) { result = mMemoryCache.get(url); // If we get a value, that has expired if (null != result && result.getExpiresAt().isBeforeNow() && checkExpiration) { mMemoryCache.remove(url); result = null; } } } return result; }
public Bitmap getBitmapFromMemCache(String key) { Bitmap bitmap = null; if (mMemoryCache != null) { bitmap = mMemoryCache.get(key); } return bitmap; }
/** * Clears both the memory and disk cache associated with this ImageCache object. Note that this * includes disk access so this should not be executed on the main/UI thread. */ public void clearCache() { if (mMemoryCache != null) { mMemoryCache.evictAll(); if (BuildConfig.DEBUG) { Log.d(TAG, "Memory cache cleared"); } } }
// 缓å˜bitmap public boolean putBitmap(String key, Bitmap bitmap) { if (bitmap != null) { synchronized (sHardBitmapCache) { sHardBitmapCache.put(key, bitmap); } return true; } return false; }
private static synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (key == null || bitmap == null) { return; } if (getBitmapFromMemCache(key) == null) { _memoryCache.put(key, bitmap); } }