android.util.LruCache Java Examples

The following examples show how to use android.util.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: ViewUtil.java    From sa-sdk-android with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 class name
 */
private static String getCanonicalName(Class clazz) {
    String name = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
        if (sClassNameCache == null) {
            sClassNameCache = new LruCache<Class, String>(100);
        }
        name = sClassNameCache.get(clazz);
    }
    if (TextUtils.isEmpty(name)) {
        name = clazz.getCanonicalName();
        if (TextUtils.isEmpty(name)) {
            name = "Anonymous";
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            synchronized (ViewUtil.class) {
                sClassNameCache.put(clazz, name);
            }
        }
        checkCustomRecyclerView(clazz, name);
    }
    return name;
}
 
Example #2
Source File: WebNodesManager.java    From sa-sdk-android with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
void handlerFailure(String webViewUrl, String message) {
    Dispatch.getInstance().removeCallbacksAndMessages();
    if (!VisualizedAutoTrackService.getInstance().isVisualizedAutoTrackRunning()) {
        return;
    }
    if (TextUtils.isEmpty(message)) {
        return;
    }
    SALog.i(TAG, "handlerFailure url " + webViewUrl + ",msg: " + message);
    mHasH5AlertInfo = true;
    mLastWebNodeMsg = message;
    List<WebNodeInfo.AlertInfo> list = parseAlertResult(message);
    if (list != null && list.size() > 0) {
        if (sWebNodesCache == null) {
            sWebNodesCache = new LruCache<>(LRU_CACHE_MAX_SIZE);
        }
        sWebNodesCache.put(webViewUrl, WebNodeInfo.createWebAlertInfo(list));
    }
}
 
Example #3
Source File: InterestsItemView.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * @param context The view context in which this item will be shown.
 * @param interest The interest to display.
 * @param listener Callback object for when a view is pressed.
 * @param imageCache A cache to store downloaded images.
 * @param drawingData Information about the view size.
 */
InterestsItemView(Context context, Interest interest, InterestsClickListener listener,
        LruCache<String, Promise<Drawable>> imageCache, DrawingData drawingData) {
    super(context);

    mContext = context;
    mListener = listener;
    mImageCache = imageCache;
    mDrawingData = drawingData;

    setTextSize(TypedValue.COMPLEX_UNIT_PX, mDrawingData.mTextSize);
    setMinimumHeight(mDrawingData.mMinHeight);
    setGravity(Gravity.CENTER);
    setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

    setOnClickListener(this);

    reset(interest);
}
 
Example #4
Source File: BitmapCache.java    From android-movies-demo with MIT License 6 votes vote down vote up
public static void init(Context context) {
	sAppContext = context.getApplicationContext();

	// Use 1/4th of the available memory for this memory cache.
	final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / SCALE);
	final int cacheSize = maxMemory / 4;

	Log.i("MovieDemo", "Creating Bitmap cache size of: " + cacheSize + " (total memory " + maxMemory + ")");

	sCache = new LruCache<Integer, Bitmap>(cacheSize) {
		@Override
		protected int sizeOf(Integer key, Bitmap bitmap) {
			return bitmap.getByteCount() / SCALE;
		}
	};
}
 
Example #5
Source File: ImageCache.java    From ImageFrame with Apache License 2.0 6 votes vote down vote up
public ImageCache() {
  mReusableBitmaps =
      Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
  long memCacheSize = Runtime.getRuntime().freeMemory() / 8;
  if (memCacheSize <= 0) {
    memCacheSize = 1;
  }
  // If you're running on Honeycomb or newer, create a
  // synchronized HashSet of references to reusable bitmaps.
  mMemoryCache = new LruCache<String, BitmapDrawable>((int) memCacheSize) {

    // // Notify the removed entry that is no longer being cached.
    // @Override
    // protected void entryRemoved(boolean evicted, String key,
    // BitmapDrawable oldValue, BitmapDrawable newValue) {
    // //Log.i("TAG","mReusableBitmaps add2");
    // //mReusableBitmaps.add(new SoftReference<>(oldValue.getBitmap()));
    // }
    @Override
    protected int sizeOf(String key, BitmapDrawable value) {
      return value.getBitmap().getByteCount();
    }
  };
}
 
Example #6
Source File: BrowserImageActivity.java    From aurora-imui with MIT License 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_browser);
    mPathList = getIntent().getStringArrayListExtra("pathList");
    mMsgIdList = getIntent().getStringArrayListExtra("idList");
    mViewPager = (ImgBrowserViewPager) findViewById(R.id.img_browser_viewpager);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    mWidth = dm.widthPixels;
    mHeight = dm.heightPixels;

    int maxMemory = (int) (Runtime.getRuntime().maxMemory());
    int cacheSize = maxMemory / 4;
    mCache = new LruCache<>(cacheSize);
    mViewPager.setAdapter(pagerAdapter);
    initCurrentItem();
}
 
Example #7
Source File: BitmapLruCache.java    From Presentation with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public BitmapLruCache(Context context) {
    mContext = context;
    mLruCache = new LruCache<>((int) EnvironmentHelper.getMemoryCacheSize());
    mHuabanApp = Huaban.getInstance();

    try {
        mDiskLruCache = new BitmapDiskLruCache(
                EnvironmentHelper.getCacheDir(mContext),
                EnvironmentHelper.getDiskCacheSize(mContext));
    } catch (IOException e) {
        e.printStackTrace();
    }

    mNotAvailableBitmap = getDefaultBitmap();
}
 
Example #8
Source File: ImageLoader.java    From PhotoPicker with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化内存缓存
 */
public void initMemoryCache() {

    // Set up memory cache
    if (mMemoryCache != null) {
        try {
            clearMemoryCache();
        } catch (Throwable e) {
        }
    }
    // find the max memory size of the system
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {

        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            if (bitmap == null) return 0;
            return bitmap.getRowBytes() * bitmap.getHeight();
        }
    };
}
 
Example #9
Source File: FontManager.java    From FontProvider with MIT License 6 votes vote down vote up
public static void init(Context context) {
    if (sFonts != null) {
        return;
    }

    sCache = new LruCache<String, MemoryFile>(FontProviderSettings.getMaxCache()) {
        @Override
        protected void entryRemoved(boolean evicted, String key, MemoryFile oldValue, MemoryFile newValue) {
            if (evicted) {
                oldValue.close();
            }
        }

        @Override
        protected int sizeOf(String key, MemoryFile value) {
            return value.length();
        }
    };

    sFonts = new ArrayList<>();

    for (int res : FONTS_RES) {
        FontInfo font = new Gson().fromJson(new InputStreamReader(context.getResources().openRawResource(res)), FontInfo.class);
        sFonts.add(font);
    }
}
 
Example #10
Source File: ConnectionUtil.java    From imsdk-android with MIT License 6 votes vote down vote up
/**
     * 获取最新用户配置后更新本地数据
     *
     * @param newRemoteConfig
     */
    public static void refreshTheConfig(NewRemoteConfig newRemoteConfig) {
        IMDatabaseManager.getInstance().insertUserConfigVersion(newRemoteConfig.getData().getVersion());
        IMDatabaseManager.getInstance().bulkUserConfig(newRemoteConfig);


        for (int i = 0; i < newRemoteConfig.getData().getClientConfigInfos().size(); i++) {
            if (newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kCollectionCacheKey)) {
//                ConnectionUtil.getInstance().handleMyEmotion(newRemoteConfig.getData().getClientConfigInfos().get(i));
            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kMarkupNames)){
                LruCache<String,String> markups = ConnectionUtil.getInstance().selectMarkupNames();
//                Logger.i("initreload map:" + JsonUtils.getGson().toJson(markups));
                CurrentPreference.getInstance().setMarkupNames(markups);
//                IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.Show_List);
            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kStickJidDic)){
                IMDatabaseManager.getInstance().setConversationTopSession(newRemoteConfig.getData().getClientConfigInfos().get(i));

            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kNoticeStickJidDic)){
                IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.Update_ReMind);
            } else if(newRemoteConfig.getData().getClientConfigInfos().get(i).getKey().equals(CacheDataType.kQuickResponse)) {
                IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.UPDATE_QUICK_REPLY);
            }
        }
        IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.Show_List);
    }
 
Example #11
Source File: AlbumCursorAdapter.java    From AudioAnchor with GNU General Public License v3.0 6 votes vote down vote up
AlbumCursorAdapter(Context context, Cursor c) {
    super(context, c, 0);
    mContext = context;
    // Get the base directory from the shared preferences.
    mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    // Set up the image cache
    // See https://developer.android.com/topic/performance/graphics/cache-bitmap
    // Get max available Java VM memory. Stored in kilobytes as LruCache takes an int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use fraction of the available memory for this memory cache.
    final int cacheSize = maxMemory / 12;

    mImageCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size is measured in kilobytes rather than number of items.
            return bitmap.getByteCount() / 1024;
        }
    };


}
 
Example #12
Source File: DaVinci.java    From DaVinci with Apache License 2.0 6 votes vote down vote up
/**
 * Initialise DaVinci, muse have a googleApiClient to retrieve Bitmaps from Smartphone
 *
 * @param context the application context
 * @param size    the number of entry on the cache
 */
private DaVinci(Context context, int size) {

    Log.d(TAG, "====================================");

    this.mSize = size;
    this.mContext = context;
    this.mImagesCache = new LruCache<>(mSize);
    this.mDiskImageCache= new DiskLruImageCache(mContext, TAG, cacheSize, Bitmap.CompressFormat.PNG, 100);

    this.mPlaceHolder = new ColorDrawable(Color.TRANSPARENT);

    mApiClient = new GoogleApiClient.Builder(context)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    mApiClient.connect();
    //TODO disconnect when the application close
}
 
Example #13
Source File: AvatarService.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public void clear(Conversation conversation) {
	if (conversation.getMode() == Conversation.MODE_SINGLE) {
		clear(conversation.getContact());
	} else {
		clear(conversation.getMucOptions());
		synchronized (this.conversationDependentKeys) {
			Set<String> keys = this.conversationDependentKeys.get(conversation.getUuid());
			if (keys == null) {
				return;
			}
			LruCache<String, Bitmap> cache = this.mXmppConnectionService.getBitmapCache();
			for (String key : keys) {
				cache.remove(key);
			}
			keys.clear();
		}
	}
}
 
Example #14
Source File: AvatarService.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
public void clear(Conversation conversation) {
    if (conversation.getMode() == Conversation.MODE_SINGLE) {
        clear(conversation.getContact());
    } else {
        clear(conversation.getMucOptions());
        synchronized (this.conversationDependentKeys) {
            Set<String> keys = this.conversationDependentKeys.get(conversation.getUuid());
            if (keys == null) {
                return;
            }
            LruCache<String, Bitmap> cache = this.mXmppConnectionService.getBitmapCache();
            for (String key : keys) {
                cache.remove(key);
            }
            keys.clear();
        }
    }
}
 
Example #15
Source File: ImageCache.java    From clevertap-android-sdk with MIT License 6 votes vote down vote up
public static void init(){
    synchronized (ImageCache.class) {
        if(mMemoryCache == null) {
            Logger.v("CleverTap.ImageCache: init with max device memory: " + maxMemory + "KB and allocated cache size: " + cacheSize + "KB");
            try {
                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.
                        int size = getImageSizeInKB(bitmap);
                        Logger.v( "CleverTap.ImageCache: have image of size: "+size + "KB for key: " + key);
                        return size;
                    }
                };
            } catch (Throwable t) {
                Logger.v( "CleverTap.ImageCache: unable to initialize cache: ", t.getCause());
            }
        }
    }
}
 
Example #16
Source File: ValidateNotificationPeople.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void initialize(Context context, NotificationUsageStats usageStats) {
    if (DEBUG) Slog.d(TAG, "Initializing  " + getClass().getSimpleName() + ".");
    mUserToContextMap = new ArrayMap<>();
    mBaseContext = context;
    mUsageStats = usageStats;
    mPeopleCache = new LruCache<String, LookupResult>(PEOPLE_CACHE_SIZE);
    mEnabled = ENABLE_PEOPLE_VALIDATOR && 1 == Settings.Global.getInt(
            mBaseContext.getContentResolver(), SETTING_ENABLE_PEOPLE_VALIDATOR, 1);
    if (mEnabled) {
        mHandler = new Handler();
        mObserver = new ContentObserver(mHandler) {
            @Override
            public void onChange(boolean selfChange, Uri uri, int userId) {
                super.onChange(selfChange, uri, userId);
                if (DEBUG || mEvictionCount % 100 == 0) {
                    if (VERBOSE) Slog.i(TAG, "mEvictionCount: " + mEvictionCount);
                }
                mPeopleCache.evictAll();
                mEvictionCount++;
            }
        };
        mBaseContext.getContentResolver().registerContentObserver(Contacts.CONTENT_URI, true,
                mObserver, UserHandle.USER_ALL);
    }
}
 
Example #17
Source File: ClusterOverlay.java    From android-cluster-marker with Apache License 2.0 6 votes vote down vote up
/**
     * 构造函数,批量添加聚合元素时,调用此构造函数
     *
     * @param amap
     * @param clusterItems 聚合元素
     * @param clusterSize
     * @param context
     */
    public ClusterOverlay(AMap amap, List<ClusterItem> clusterItems,
                          int clusterSize, Context context) {
//默认最多会缓存80张图片作为聚合显示元素图片,根据自己显示需求和app使用内存情况,可以修改数量
        mLruCache = new LruCache<Integer, BitmapDescriptor>(80) {
            protected void entryRemoved(boolean evicted, Integer key, BitmapDescriptor oldValue, BitmapDescriptor newValue) {
                oldValue.getBitmap().recycle();
            }
        };
        if (clusterItems != null) {
            mClusterItems = clusterItems;
        } else {
            mClusterItems = new ArrayList<ClusterItem>();
        }
        mContext = context;
        mClusters = new ArrayList<Cluster>();
        this.mAMap = amap;
        mClusterSize = clusterSize;
        mPXInMeters = mAMap.getScalePerPixel();
        mClusterDistance = mPXInMeters * mClusterSize;
        amap.setOnCameraChangeListener(this);
        amap.setOnMarkerClickListener(this);
        initThreadHandler();
        assignClusters();
    }
 
Example #18
Source File: BitmapCache.java    From android-advanced-light with MIT License 5 votes vote down vote up
public BitmapCache() {
    int maxSize = 8 * 1024 * 1024;
    mCache = new LruCache<String, Bitmap>(maxSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight();
        }
    };
}
 
Example #19
Source File: IconCache.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
private IconCache(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    final int memClass = am.getMemoryClass();
    final int cacheSize = (1024 * 1024 * memClass) / 8;

    drawables = new LruCache<String, BitmapDrawable>(cacheSize) {
        @Override
        protected int sizeOf(String key, BitmapDrawable value) {
            return value.getBitmap().getByteCount();
        }
    };
}
 
Example #20
Source File: DrawableLoder.java    From GreenDamFileExploere with Apache License 2.0 5 votes vote down vote up
private DrawableLoder() {
    // 获取应用程序最大可用内存
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheSize = maxMemory / 8;
    // 设置图片缓存大小为程序最大可用内存的1/8
    mMemoryCache = new LruCache<String, Drawable>(cacheSize);
}
 
Example #21
Source File: RecordCache.java    From PlayerBase with Apache License 2.0 5 votes vote down vote up
public RecordCache(int maxCacheCount){
    mLruCache = new LruCache<String,Integer>(maxCacheCount * 4){
        @Override
        protected int sizeOf(String key, Integer value) {
            return 4;
        }
    };
}
 
Example #22
Source File: RestVolleyImageCache.java    From RestVolley with Apache License 2.0 5 votes vote down vote up
/**
 * constructor with the specified config.
 * @param context {@link Context}
 * @param maxMemCacheSize max memory cache size.
 * @param maxDiskCacheSize max disk cache size.
 * @param diskCacheDir disk cache dir.
 */
public RestVolleyImageCache(Context context, long maxMemCacheSize, long maxDiskCacheSize, String diskCacheDir) {
    MEM_CACHE_SIZE = maxMemCacheSize > 0 ? maxMemCacheSize : getDefaultCacheSize(context, PAGE_CACHE_COUNT);
    MAX_BITMAP_CACHE_SIZE = getMaxBitmapCacheSize(context);
    DISK_CACHE_SIZE = maxDiskCacheSize > 0 ? maxDiskCacheSize : DEF_DISK_CACHE_SIZE;
    String cacheDirStr = TextUtils.isEmpty(diskCacheDir) ? DISK_CACHE_DIR : diskCacheDir;

    //create mem cache
    mMemCache = new LruCache<String, Bitmap>((int) MEM_CACHE_SIZE) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return getBitmapSize(value);
        }
    };

    //create disk cache dir
    mCacheDir = getDiskCacheDir(context, cacheDirStr);
    if (!mCacheDir.exists()) {
        mCacheDir.mkdirs();
    }

    //create disk cache
    try {
        mDiskCache = DiskLruCache.open(mCacheDir, 1, 1, DISK_CACHE_SIZE);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #23
Source File: LiveWallpaperView.java    From LiveWallpaper with Apache License 2.0 5 votes vote down vote up
private void initCacheConfig() {
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    this.mMemoryCache = new LruCache<String, Bitmap>(maxMemory / 8) {

        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
}
 
Example #24
Source File: PickerCategoryView.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * A helper function for initializing the PickerCategoryView.
 * @param context The context to use.
 */
@SuppressWarnings("unchecked") // mSelectableListLayout
private void postConstruction(Context context) {
    mContext = context;

    mDecoderServiceHost = new DecoderServiceHost(this);
    mDecoderServiceHost.bind(mContext);

    enumerateBitmaps();

    mSelectionDelegate = new SelectionDelegate<PickerBitmap>();

    View root = LayoutInflater.from(context).inflate(R.layout.photo_picker_dialog, this);
    mSelectableListLayout =
            (SelectableListLayout<PickerBitmap>) root.findViewById(R.id.selectable_list);

    mPickerAdapter = new PickerAdapter(this);
    mRecyclerView = mSelectableListLayout.initializeRecyclerView(mPickerAdapter);
    PhotoPickerToolbar toolbar = (PhotoPickerToolbar) mSelectableListLayout.initializeToolbar(
            R.layout.photo_picker_toolbar, mSelectionDelegate,
            R.string.photo_picker_select_images, null, 0, 0, R.color.default_primary_color,
            null);
    toolbar.setNavigationOnClickListener(this);
    Button doneButton = (Button) toolbar.findViewById(R.id.done);
    doneButton.setOnClickListener(this);

    calculateGridMetrics();

    mLayoutManager = new GridLayoutManager(mContext, mColumns);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mSpacingDecoration = new GridSpacingItemDecoration(mColumns, mPadding);
    mRecyclerView.addItemDecoration(mSpacingDecoration);

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / KILOBYTE);
    final int cacheSizeLarge = maxMemory / 2; // 1/2 of the available memory.
    final int cacheSizeSmall = maxMemory / 8; // 1/8th of the available memory.
    mLowResBitmaps = new LruCache<String, Bitmap>(cacheSizeSmall);
    mHighResBitmaps = new LruCache<String, Bitmap>(cacheSizeLarge);
}
 
Example #25
Source File: MemoryCache.java    From XImageLoader with Apache License 2.0 5 votes vote down vote up
public MemoryCache() {
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 4;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }
    };
}
 
Example #26
Source File: ElapsedTimeAxisFormatter.java    From science-journal with Apache License 2.0 5 votes vote down vote up
private ElapsedTimeAxisFormatter(Context context) {
  Resources res = context.getResources();
  extraSmallFormat = res.getString(R.string.elapsed_time_axis_format_extra_small);
  smallFormat = res.getString(R.string.elapsed_time_axis_format_small);
  largeFormat = res.getString(R.string.elapsed_time_axis_format_large);
  smallFormatTenths = res.getString(R.string.elapsed_time_axis_format_small_tenths);
  largeFormatTenths = res.getString(R.string.elapsed_time_axis_format_large_tenths);

  formatter = new ReusableFormatter();

  cacheWithTenths = new LruCache<>(128 /* entries */);
  cacheWithoutTenths = new LruCache<>(128 /* entries */);
}
 
Example #27
Source File: AlbumArtCache.java    From react-native-streaming-audio-player with MIT License 5 votes vote down vote up
private AlbumArtCache() {
    // Holds no more than MAX_ALBUM_ART_CACHE_SIZE bytes, bounded by maxmemory/4 and
    // Integer.MAX_VALUE:
    int maxSize = Math.min(MAX_ALBUM_ART_CACHE_SIZE,
        (int) (Math.min(Integer.MAX_VALUE, Runtime.getRuntime().maxMemory()/4)));
    mCache = new LruCache<String, Bitmap[]>(maxSize) {
        @Override
        protected int sizeOf(String key, Bitmap[] value) {
            return value[BIG_BITMAP_INDEX].getByteCount()
                + value[ICON_BITMAP_INDEX].getByteCount();
        }
    };
}
 
Example #28
Source File: CacheUtil.java    From StickyDecoration with Apache License 2.0 5 votes vote down vote up
private void initLruCache() {
    mLruCache = new LruCache<Integer, T>(2 * 1024 * 1024) {
        @Override
        protected void entryRemoved(boolean evicted, Integer key, T oldValue, T newValue) {
            super.entryRemoved(evicted, key, oldValue, newValue);
        }
    };
}
 
Example #29
Source File: VMBitmapCache.java    From VMLibrary with Apache License 2.0 5 votes vote down vote up
/**
 * 构造函数,初始化缓存
 */
private VMBitmapCache() {
    cache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
}
 
Example #30
Source File: ImageCache.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
public void init(final Context context) {
    final ActivityManager activityManager = (ActivityManager)context
            .getSystemService(Context.ACTIVITY_SERVICE);
    final int lruCacheSize = Math.round(0.25f * activityManager.getMemoryClass()
            * 1024 * 1024);
    mLruCache = new LruCache<String, Bitmap>(lruCacheSize) {
        @Override
        protected int sizeOf(final String paramString, final Bitmap paramBitmap) {
            return paramBitmap.getByteCount();
        }

    };
}