当前位置:网站首页>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 cloud ecology conference comes with the "peak"!
- Contemporary fairy quotations
- Commonjs export import
- Nacos hand to hand teaching [i] dynamic configuration of Nacos
- How SAP Spartacus redefines login component
- Login and payment arrangement in uniapp
- PG Optimization -- execution plan
- Password input box and coupon and custom soft keyboard
- The IPO of Tuba rabbit was terminated: the annual profit fell by 33%, and Jingwei Sequoia was the shareholder
- Deamnet|filenotfounderror: [winerror 3] the system cannot find the specified path.: '/ Datasettest\\Set12‘
猜你喜欢
![[recognize cloud Nativity] Chapter 4 cloud network section 4.9.4.3 - smart network card usage scenario - network acceleration implementation](/img/9a/b69036bf920706360d8b293dad2a89.png)
[recognize cloud Nativity] Chapter 4 cloud network section 4.9.4.3 - smart network card usage scenario - network acceleration implementation

Specificity and five applications of Worthington alcohol dehydrogenase

Peripherals: interrupt system of keys and CPU

iptables :chains, target

The introduction of 23 Filipino doctors for 18million was a hot topic, and the school teacher responded: expedient
![[development tutorial 10] crazy shell · open source Bluetooth smart health watch OTA image production and download technical documents](/img/97/c4ef281ca14eb68c8a14f18e03c3dd.png)
[development tutorial 10] crazy shell · open source Bluetooth smart health watch OTA image production and download technical documents

Top priority of dry goods: common indicators and terms in data analysis!

How to empty localstorage before closing a page

Talk about resume optimization and interview skills of algorithm post!

Fabric. JS centered element
随机推荐
The cloud ecology conference comes with the "peak"!
Cloud native platform, let edge applications play out!
C traps and defects Chapter 2 lexical "traps" 2.4 switch statements
Interpretation of video generation paper of fed shot video to video (neurips 2019)
Mobile Robotics (3) Kalman filter
Which bank outlet in Zhejiang can buy REITs fund products?
Performance analysis method - Notes on top of performance
[28. Maximum XOR pair]
MySQL Basics (concepts, common instructions)
Web Security Foundation - file upload
From casting sword to defending sword: the way to build the efficiency platform of didi project
Antdb database products were selected into the global database industry map (2022) of the China Academy of communications and communications
Rightmost × Microframe, high quality heif image coding and compression technology
1260. Two dimensional grid migration: simple construction simulation problem
Commonjs export import
[development tutorial 10] crazy shell · open source Bluetooth smart health watch OTA image production and download technical documents
The current situation of the industry is disappointing. After working, I returned to UC Berkeley to study for a doctoral degree
How to implement the server anti blackmail virus system is a problem we have to consider
The difference between sigsuspend and sigwait
Top priority of dry goods: common indicators and terms in data analysis!