Java Code Examples for android.util.LruCache

The following are top voted examples for showing how to use android.util.LruCache. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: RecyclerViewAdapterHelper.java   View source code 7 votes vote down vote up
/**
 * @param type 数据类型
 * @return 根据type产生loading的头
 */
private T createLoadingHeader(int type) {

    checkLoadingAdapterBind();

    if (mSingleCache == null) {
        mSingleCache = new LruCache<String, T>(mMaxSingleCacheCount);
    }

    String headerKey = getHeaderKey(type);
    T header = mSingleCache.get(headerKey);

    if (header == null) {
        header = mLoadingEntityAdapter.createLoadingHeaderEntity(type);
        mSingleCache.put(headerKey, header);
    }

    mLoadingEntityAdapter.bindLoadingEntity(header, -1);
    return header;
}
 
Example 2
Project: ImageLoaderLibrary   File: MemoryLruCache.java   View source code 6 votes vote down vote up
private MemoryLruCache(){

        int maxMemorySize= (int) (Runtime.getRuntime().maxMemory()/16);
        Log.i(GlobalConfig.TAG,"内存可用的大小:"+maxMemorySize/1024 + "K");

        if (maxMemorySize <= 0){
            maxMemorySize = 10*1024*1024;
        }

        lruCache = new LruCache<String, Bitmap>(maxMemorySize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //一张图片的大小
                return value.getRowBytes()*value.getHeight();
            }
        };
    }
 
Example 3
Project: FriendBook   File: StringAdapter.java   View source code 6 votes vote down vote up
private SparseArray<ArrayList<String>> getSectionData(int section, PageProperty property) {
    SparseArray<ArrayList<String>> pages = null;
    if (map == null) {
        map = new LruCache<>(3);
        pages = loadPages(getPageSource(section), property.textPaint, property.visibleHeight, property.visibleWidth, property.intervalSize, property.paragraphSize);
        map.put(section, pages);
        mPageProperty=property;
    } else {
        if (mPageProperty != null && mPageProperty.equals(property)) {
            pages = map.get(section);
        }
        if (pages == null) {
            pages = loadPages(getPageSource(section), property.textPaint, property.visibleHeight, property.visibleWidth, property.intervalSize, property.paragraphSize);
            map.put(section, pages);
            mPageProperty=property;
        }
    }
    return pages;
}
 
Example 4
Project: godlibrary   File: ImageLoader.java   View source code 6 votes vote down vote up
private ImageLoader(Context mContext, String dirNameByRoot) {
    this.mContext = mContext;
    if (dirNameByRoot != null && dirNameByRoot.length() > 0)
        fileUtils = new FileUtils(mContext, dirNameByRoot);
    else
        fileUtils = new FileUtils(mContext);
    int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // 给LruCache分配1/8 4M
    int mCacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(mCacheSize) {
        // 必须重写此方法,来测量Bitmap的大小
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
}
 
Example 5
Project: yphoto   File: ClusterOverlay.java   View source code 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, Drawable>(80) {
    };
    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);
    setClusterRenderer(this);
    setOnClusterClickListener(this);
    initThreadHandler();
    assignClusters();
}
 
Example 6
Project: MultiTypeRecyclerViewAdapter   File: RecyclerViewAdapterHelper.java   View source code 6 votes vote down vote up
/**
 * @param type 数据类型
 * @return 根据type产生loading的头
 */
private T createLoadingHeader(int type) {

    checkLoadingAdapterBind();

    if (mSingleCache == null) {
        mSingleCache = new LruCache<String, T>(mMaxSingleCacheCount);
    }

    String headerKey = getHeaderKey(type);
    T header = mSingleCache.get(headerKey);

    if (header == null) {
        header = mLoadingEntityAdapter.createLoadingHeaderEntity(type);
        mSingleCache.put(headerKey, header);
    }

    mLoadingEntityAdapter.bindLoadingEntity(header, -1);
    return header;
}
 
Example 7
Project: WearVibrationCenter   File: AppMuteManager.java   View source code 6 votes vote down vote up
public AppMuteManager(NotificationService service) {
    this.service = service;

    googleApiClient = new GoogleApiClient.Builder(service)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    googleApiClient.connect();

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory());
    iconCache = new LruCache<String, Bitmap>(maxMemory / 32) // 1/16th of device's RAM should be far enough for all icons
    {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount();
        }
    };

}
 
Example 8
Project: WearVibrationCenter   File: AppPickerFragment.java   View source code 6 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    systemApps = getArguments().getBoolean("systemApps", false);

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    iconCache = new LruCache<String, Bitmap>(maxMemory / 16) // 1/16th of device's RAM should be far enough for all icons
    {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount() / 1024;
        }

    };

    adapter = new AppListAdapter();
}
 
Example 9
Project: grid-video-viewer   File: BitmapLruCache.java   View source code 6 votes vote down vote up
public BitmapLruCache(int cacheSize) {
    mCache = new LruCache<T, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(T id, Bitmap value) {
            return value.getByteCount();
        }

        @Override
        protected void entryRemoved(boolean evicted, T key, Bitmap oldValue,
                                    Bitmap newValue) {

            if (oldValue.isMutable()) {
                oldValue.recycle();
            }
        }
    };
}
 
Example 10
Project: FontProvider   File: FontManager.java   View source code 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 11
Project: ImageFrame   File: ImageCache.java   View source code 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 12
Project: ObjectCache   File: MemCache.java   View source code 6 votes vote down vote up
private MemCache() {
    // Find out maximum memory available to application
    // 1024 is used because LruCache constructor takes int in kilobytes
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/16th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 16;
    Log.d(getClass().getName(), "max memory " + maxMemory + " cache size " + cacheSize);

    this.memCache = new LruCache<String, Entry>(cacheSize) {
        @Override
        protected int sizeOf(String key, Entry value) {
            return super.sizeOf(key, value);
        }
    };
}
 
Example 13
Project: ImageCarouselView   File: ImageLoader.java   View source code 6 votes vote down vote up
protected ImageLoader() {
    // 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 / LRU_CACHE_SIZE_FACTOR;

    memCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap image) {
            return image.getByteCount()/1024;
        }
    };
}
 
Example 14
Project: DailyStudy   File: ImageLoader.java   View source code 6 votes vote down vote up
private ImageLoader(Context context) {
    mContext = context.getApplicationContext();
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight() / 1024;
        }
    };
    File diskCacheDir = getDiskCacheDir(mContext, "bitmap");
    if (!diskCacheDir.exists()) {
        diskCacheDir.mkdirs();
    }

    if (getUsableSpace(diskCacheDir) > DISK_CACHE_SIZE) {
        try {
            mDiskLruCache = DiskLruCache.open(diskCacheDir, 1, 1, DISK_CACHE_SIZE);
            mIsDiskLruCacheCreated = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 
Example 15
Project: ReadInJoy-And-Train   File: RecyclerViewActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recycler_view);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    if (getIntent() != null) {
        handleIntent(getIntent());
    }

    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    VerticalDividerItemDecoration verticalDividerItemDecoration = new VerticalDividerItemDecoration(10);
    recyclerView.addItemDecoration(verticalDividerItemDecoration);

    this.bitmapLruCache = new LruCache<String, Bitmap>(cacheSize) {
    };

    adapter = new BookAdapter(bookList, bitmapLruCache);
    recyclerView.setAdapter(adapter);

}
 
Example 16
Project: MyRepository   File: ImageLoader.java   View source code 6 votes vote down vote up
/**
     * 初始化
     *
     * @param threadCount
     * @param type
     */
    private void init(int threadCount, Type type) {
        initBackThread();

        // 获取我们应用的最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheMemory = maxMemory / 8;
        mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
//                return value.getRowBytes() * value.getHeight();
                return value.getByteCount();
            }

        };

        // 创建线程池
        mThreadPool = Executors.newFixedThreadPool(threadCount);
        mTaskQueue = new LinkedList<Runnable>();
        mType = type;
        mSemaphoreThreadPool = new Semaphore(threadCount);
    }
 
Example 17
Project: android-cluster-marker-master   File: ClusterOverlay.java   View source code 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<>();
    }
    mContext = context;
    mClusters = new ArrayList<>();
    this.mAMap = amap;
    mClusterSize = clusterSize;
    mPXInMeters = mAMap.getScalePerPixel();
    mClusterDistance = mPXInMeters * mClusterSize;
    amap.setOnCameraChangeListener(this);
    amap.setOnMarkerClickListener(this);
    initThreadHandler();
    assignClusters();
}
 
Example 18
Project: Tester   File: PhotoDiskLruCacheAdapter.java   View source code 6 votes vote down vote up
public PhotoDiskLruCacheAdapter(Context context, String[] images, GridView view) {
    this.mContext = context;
    this.images = images;
    this.mPhotoView = view;
    this.taskCollection = new HashSet<>();

    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount();
        }
    };

    try {
        File cacheDir = getDiskCacheDir(context, "DiskCache");
        if (!cacheDir.exists()) {
            cacheDir.mkdir();
        }
        mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 10 * 1024 * 1024);
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 19
Project: Tester   File: PhotoLruCacheAdapter.java   View source code 6 votes vote down vote up
public PhotoLruCacheAdapter(Context context, String[] images, GridView view) {
    this.mContext = context;
    this.images = images;
    this.mPhotoView = view;
    this.mPhotoView.setOnScrollListener(this);
    this.taskCollection = new HashSet<>();

    // 获取到可用内存的最大值,使用内存超出这个值会引起OutOfMemory异常。
    int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // LruCache通过构造函数传入缓存值,以KB为单位,使用最大可用内存值的1/8作为缓存的大小。
    int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            // 重写此方法来衡量每张图片的大小
            return value.getByteCount() / 1024;
        }
    };
}
 
Example 20
Project: android_packages_apps_tv   File: ImageCache.java   View source code 6 votes vote down vote up
/**
 * Creates a new ImageCache object with a given cache size percent.
 *
 * @param memCacheSizePercent The cache size as a percent of available app memory.
 */
private ImageCache(float memCacheSizePercent) {
    int memCacheSize = calculateMemCacheSize(memCacheSizePercent);

    // Set up memory cache
    if (DEBUG) {
        Log.d(TAG, "Memory cache created (size = " + memCacheSize + " Kbytes)");
    }
    mMemoryCache = new LruCache<String, ScaledBitmapInfo>(memCacheSize) {
        /**
         * Measure item size in kilobytes rather than units which is more practical for a bitmap
         * cache
         */
        @Override
        protected int sizeOf(String key, ScaledBitmapInfo bitmapInfo) {
            return (bitmapInfo.bitmap.getByteCount() + 1023) / 1024;
        }
    };
}
 
Example 21
Project: Android-High-Performance-Programming   File: BitmapCache.java   View source code 6 votes vote down vote up
public BitmapCache() {
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    lruCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount();
        }

        @Override
        protected void entryRemoved(boolean evicted, String key,
                                    Bitmap oldValue, Bitmap newValue) {
            bitmapsPool.add(new SoftReference<>(oldValue));
        }
    };
    bitmapsPool = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
}
 
Example 22
Project: PlatePicks-Android   File: ListAdapter.java   View source code 6 votes vote down vote up
public ListAdapter(Context context, ArrayList<ListItemClass> data) {
    super(context, 0, data);
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);  // maxMemory for LruCache
    final int cacheSize = maxMemory / 8;    // Use 1/8th of the available memory for this memory cache.

    mCtx = context; //<-- fill it with the Context you are passed
    this.data = data;
    accessCache = new ReentrantLock();
    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;
        }
    };
}
 
Example 23
Project: android101   File: Level1CacheLayer.java   View source code 6 votes vote down vote up
public Level1CacheLayer() {
    int maxSize = RetroImageLoader.getInstance().getConfiguration().getMaximumMemoryCacheSize();
    bitmapLruCache = new LruCache<String, CacheableBitmap>(maxSize) {
            protected void entryRemoved(
                    boolean evicted, String key,
                    CacheableBitmap oldValue, CacheableBitmap newValue) {
                oldValue.setCached(false);
            }

            @Override
            protected int sizeOf(String key, CacheableBitmap value) {
                final int bitmapSize = value.getBitmapSize() / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
    };
}
 
Example 24
Project: android-cluster-marker   File: ClusterOverlay.java   View source code 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 25
Project: Madad_SOS   File: Helper.java   View source code 6 votes vote down vote up
static void init() {
    if(mMemoryCache!=null)
        return;
    // 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;
        }
    };
}
 
Example 26
Project: AndroidBasicCommonDemos   File: ImageLoader.java   View source code 6 votes vote down vote up
public ImageLoader(ListView listView){
    mListView = listView;
    mTask = new HashSet<>();

    //获取当前可以利用最大内存
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheSize = maxMemory/4;
    //初始化
    mCaches = new LruCache<String,Bitmap>(cacheSize){
        @Override
        protected int sizeOf(String key, Bitmap value) {
            //在每次存入缓存的时候调用,告诉每次缓存图片的大小
            return value.getByteCount();
        }
    };
}
 
Example 27
Project: morscout-android   File: MorScout.java   View source code 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    preferences = getSharedPreferences("org.team1515.morscout", MODE_PRIVATE);

    queue = Volley.newRequestQueue(this);
    imageLoader = new CookieImageLoader(queue, new ImageLoader.ImageCache() {
        private final LruCache<String, Bitmap> cache = new LruCache<>(50);

        @Override
        public Bitmap getBitmap(String url) {
            return cache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            cache.put(url, bitmap);
        }
    });
}
 
Example 28
Project: ExhibitionCenter   File: LruCacheDispatcher.java   View source code 6 votes vote down vote up
/**
 * 禁止创建实例对象,请不要使用反射创建实例
 */
private LruCacheDispatcher() {

    maxCacheMemory = Runtime.getRuntime().maxMemory() / 8;// 设置最大Cache占用应用总内存1/8
    mMemoryCache = new LruCache<String, Bitmap>((int) maxCacheMemory) {

        /**
         * 计算返回每一个Bitmap的占用的内存大小
         */
        @Override
        protected int sizeOf(String key, Bitmap value) {

            //计算图片占用空间
            return value.getRowBytes() * value.getHeight();

        }

    };

}
 
Example 29
Project: photopicker   File: ImageLoader.java   View source code 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 30
Project: tazapp-android   File: PageIndexFragment.java   View source code 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    //setRetainInstance(true);
    final int maxMemory = (int) (Runtime.getRuntime()
                                        .maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {

        @SuppressLint("NewApi")
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;
        }
    };
    //init(mReaderCallback.getPaper());
}
 
Example 31
Project: DevNews   File: ImageLoader.java   View source code 6 votes vote down vote up
/**
 * 创建 LruCache && DiskLruCache
 */
public ImageLoader(Context context) {
    mContext = context.getApplicationContext();
    int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }
    };
    File diskCacheDir = getDiskCacheDir(mContext, "bitmap");
    if (!diskCacheDir.exists()) {
        diskCacheDir.mkdirs();
    }
    if (getUsableSpace(diskCacheDir) > DISK_CACHE_SIZE) {
        try {
            mDiskLruCache = DiskLruCache.open(diskCacheDir, 1, 1, DISK_CACHE_SIZE);
            mIsDiskLruCacheCreated = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 32
Project: Android-Component-By-Lyx   File: PictureWallAdapter.java   View source code 6 votes vote down vote up
public PictureWallAdapter(Context context, int resource, String[] objects, GridView gridView) {
    super(context, resource, objects);
    mGridView = gridView;
    mTasks = new HashSet<BitmapWorkerTask>();
    //get max useful memory size
    int maxMemory = (int) (Runtime.getRuntime().maxMemory()/8);
    //use 1/8 as cache size
    int cacheSize = (int) maxMemory/8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount();
        }
    };
    mGridView.setOnScrollListener(this);
}
 
Example 33
Project: HaveUSeenTheLastEpisode   File: BitmapMemoryCache.java   View source code 6 votes vote down vote up
public BitmapMemoryCache() {
    // 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);
    Log.d("HUSTLE", "max memory: " + maxMemory);

    final int cacheSize = maxMemory / 4;

    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;
        }
    };
}
 
Example 34
Project: WhatsThat   File: RiddleManager.java   View source code 6 votes vote down vote up
public static void addToCache(Riddle riddle, Bitmap image) {
    if (riddle == null || image == null) {
        return;
    }
    if (mMemoryCache == null) {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 20;

        mMemoryCache = new LruCache<Riddle, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(Riddle key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }
        };
    }
    mMemoryCache.put(riddle, image);
}
 
Example 35
Project: WhatsThat   File: ImageBitmapSource.java   View source code 6 votes vote down vote up
public ImageBitmapSource(Resources res, Map<String, Image> images) {
    mRes = res;
    mImages = images;
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 10;

    mBitmapCache = new LruCache<String, List<Bitmap>>(cacheSize) {
        @Override
        protected int sizeOf(String key, List<Bitmap> bitmaps) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            int size = 0;
            for (Bitmap bitmap : bitmaps) {
                size += bitmap.getByteCount() / 1024;
            }
            return size;
        }
    };
}
 
Example 36
Project: Pix-Art-Messenger   File: AvatarService.java   View source code 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 37
Project: Fo.dex   File: CacheImageManager.java   View source code 6 votes vote down vote up
private CacheImageManager() {
    BlockingQueue<Runnable> cacheQueue = new LinkedBlockingQueue<>();
    final int maxMemory = (int) Runtime.getRuntime().maxMemory() / 1024;
    final int cacheSize = maxMemory / 8;
    mCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount() / 1024;
        }
    };

    mCacheThreadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE,
            KEEP_ALIVE_TIME,
            KEEP_ALIVE_TIME_UNIT,
            cacheQueue);
}
 
Example 38
Project: digcsdn   File: ImageLoading.java   View source code 6 votes vote down vote up
public synchronized static ImageLoading getInstance(){
    if (imageLoading == null) {
        imageLoading = new ImageLoading(new ImageLoader(VolleyUtil.getQueue(), new ImageCache() {

            LruCache<String, Bitmap> mCache= new LruCache<String,Bitmap>(maxSize){//缓存总大小
                @Override//匿名内部类继承LruCache类,即缓存池
                protected int sizeOf(String key, Bitmap value) {
                    return value.getRowBytes()*value.getHeight();//返回图片大小
                }
            };

            public Bitmap getBitmap(String url) {
                return mCache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                mCache.put(url, bitmap);
            }
        }));
    }
    return imageLoading;
}
 
Example 39
Project: Atlas-Android   File: AtlasCellFactory.java   View source code 6 votes vote down vote up
/**
 * Returns previously parsed content for this Message, or calls parseContent() if it has not
 * been previously parsed.
 *
 * @param message Message to return parsed content object for.
 * @return Parsed content object for the given Message.
 */
public Tcache getParsedContent(LayerClient layerClient, Message message) {
    if (mCache == null) {
        mCache = new LruCache<String, Tcache>(mCacheBytes) {
            @Override
            protected int sizeOf(String key, Tcache value) {
                return value.sizeOf();
            }
        };
    }

    String id = message.getId().toString();
    Tcache value = mCache.get(id);
    if (value != null) return value;
    value = parseContent(layerClient, message);
    if (value != null) mCache.put(id, value);
    return value;
}
 
Example 40
Project: S1-Go   File: ImageLoaderxxx.java   View source code 6 votes vote down vote up
/**
 * 在构造方法里初始化配置
 */
private ImageLoaderxxx() {
	//获取系统分配给每个应用程序的最大内存
	int maxMemory = (int) Runtime.getRuntime().maxMemory();
	//给lrucache分配程序能获得的最大内存的1/8
	mLruCache = new LruCache<String, Bitmap>(maxMemory / 8);
	//创建线程队列
	mDataBaseTaskQueue = new HashMap<String, DataBaseRunnable>();
	mNetWorkTaskQueue = new HashMap<String, NetWorkRunnable>();
	//创建线程池
	mDataBaseThreadPoll = Executors.newFixedThreadPool(ImageLoaderxxx.THREADPOLL_NUM);
	mNetworkThreadPoll = Executors.newFixedThreadPool(ImageLoaderxxx.THREADPOLL_NUM);
	//创建缓存文件夹 PICTURE_CACHE
	mCacherFileDir = SysUtils.createFileDir(DIR_CACHE);
	//无法访问的Url集合
	mFaildUrl = new HashMap<>();
}