当前位置:网站首页>Android memory optimized disk cache
Android memory optimized disk cache
2022-07-25 01:42:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack .
Preface :
stay Last article Memory caching is introduced in , The advantage of memory cache is very fast . But it has shortcomings :
- Small space , The memory cache cannot be very large ;
- Memory may be cleared when it is tight ;
- It will disappear when the application exits , Can't do offline .
Based on the above shortcomings, sometimes we need a second cache , That is disk cache . Everyone should have used news client, Many have offline functions , The realization of this function is disk cache .
DiskLruCache:
stay Android The disk cache used in is mostly based on DiskLruCache Realized , How to use it in detail ?
- Create a disk cache object :
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize);open() Method accepts four parameters . The first parameter is the cache file address of the data , The second parameter is the version of the current application , The third parameter is the same key How many cache files can be matched . It's usually a biography 1, The fourth parameter is the maximum number of bytes of data that can be cached ,10M?
- Get cache path :
// Creates a unique subdirectory of the designated app cache directory. Tries to use external
// but if not mounted, falls back on internal storage.
// Create disk cache file . The preferred sdcard, hypothesis sdcard Not mounted or not sdcard Get the default cache Folder
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}- Get software version :
public int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return 1;
}- Complete code, such as the following :
DiskLruCache mDiskLruCache = null;
try {
File cacheDir = getDiskCacheDir(context, "thumbnails");
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 10 * 1024 * 1024);
} catch (IOException e) {
e.printStackTrace();
}- How to use the disk cache created above in detail, such as the following :
// Join the cache
public void addBitmapToCache(String key, Bitmap bitmap) {
// Add to memory cache as before, Put the cache into the memory cache
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
// Also add to disk cache, Put the cache into the disk cache
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null && mDiskLruCache.get(key) == null) {
mDiskLruCache.put(key, bitmap);
}
}
}
// Access to the cache
public Bitmap getBitmapFromDiskCache(String key) {
synchronized (mDiskCacheLock) {
// Wait while disk cache is started from background thread
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mDiskLruCache != null) {
return mDiskLruCache.get(key);
}
}
return null;
}summary :
The above is the creation and usage of disk cache . In practice Memory cache And disk cache are used together . Generally, first read data from the memory cache , Assume no more reads from the disk cache .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/108572.html Link to the original text :https://javaforall.cn
边栏推荐
- The two supply chain centers of HEMA launched the "background" of innovative research and development of multi format commodities
- [summer daily question] output of Luogu p1157 combination
- [summer daily question] Luogu P7550 [coci2020-2021 6] bold
- Beijing Zhun electric clock, Beidou clock server, GPS network time server, NTP satellite timing system
- Password input box and coupon and custom soft keyboard
- 10 commonly used data visualization tool software
- [programmer interview classic] 01.09 string rotation
- Worthington cytochrome c digestion study carboxypeptidase B scheme
- MySQL series | log module
- Multi species tissue slide prosci pancreatic tissue solution
猜你喜欢

iptables :chains, target

A string "0" was actually the culprit of the collapse of station b

Dynamic memory development

From casting sword to defending sword: the way to build the efficiency platform of didi project

Open source demo | release of open source example of arcall applet

Turn: emotional internal friction is the biggest source of inefficiency in your life

Hcip - BGP - border gateway protocol

What does it operation and maintenance management mean? How to establish an effective IT operation and maintenance management system?

Tiktok iqiyi announced cooperation, long and short video handshake and reconciliation?

Several application scenarios of NAT
随机推荐
On let variable promotion
Peripherals: timer, watchdog and RTC
How can arm access the Internet through a laptop?
Specificity and five applications of Worthington alcohol dehydrogenase
Hbuilderx developed by uni app connects to night God simulator
Fraud detection using CSP
Several schemes of traffic exposure in kubernetes cluster
Promise basic use
Boutique solution | Haitai cloud password application service solution to create secure and compliant Cloud Applications
Management mode of agricultural science data center based on life cycle theory
The position of the nth occurrence of MySQL in the string
Password input box and coupon and custom soft keyboard
Shell judges whether the file exists and whether the file size is 0
Three modes of executing programs, memory and cache
Download files and web pages with WGet
Nacos hand to hand teaching [i] dynamic configuration of Nacos
How to implement a state machine?
Brush questions of binary tree (5)
[C + + primer notes] Chapter 8 IO Library
Rightmost × Microframe, high quality heif image coding and compression technology