当前位置:网站首页>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
边栏推荐
- Top priority of dry goods: common indicators and terms in data analysis!
- Grpc sets connection lifetime and server health check
- Some of my understanding about anti shake and throttling
- Hbuilderx developed by uni app connects to night God simulator
- Point to point copy and paste of web pages
- Deamnet|filenotfounderror: [winerror 3] the system cannot find the specified path.: '/ Datasettest\\Set12‘
- 【Power Shell】Invoke-Expression ,Invoke-Expression -Command $activateCommand; Error or power shell failed to activate the virtual environment
- Shell judges whether the file exists and whether the file size is 0
- Brush questions of binary tree (5)
- [development tutorial 10] crazy shell · open source Bluetooth smart health watch OTA image production and download technical documents
猜你喜欢

Service address dynamic awareness of Nacos registry
![[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

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

Start to build a three node Eureka cluster

Take C language from 0 to 1 - program structure and use examples

Hcip - BGP - border gateway protocol

Pychart exits pytest mode (run pytest in mode)

Leetcode - number of palindromes

【Appium】Failed to create session. An unknown server-side error occurred while processing the command

What are the important trends revealed by the release of "operator data viability index"?
随机推荐
Academicians said: researchers should also support their families. They can only do short-term and fast research if they are not promoted
Open source demo | release of open source example of arcall applet
Prosci anti-CD22 antibody epratuzum28 flow cytometry display
Peripherals: timer, watchdog and RTC
10 commonly used data visualization tool software
[27. Expression evaluation (infix expression)]
Performance analysis method - Notes on top of performance
Hbuilderx developed by uni app connects to night God simulator
Young people who lost the IPO
How to implement a state machine?
[28. Maximum XOR pair]
Scientific data center resources and user access control system
Sort out some scattered knowledge points by yourself
What are the important trends revealed by the release of "operator data viability index"?
[29. DFS depth is preferred]
[linear DP] Digital triangle
Point to point copy and paste of web pages
Three modes of executing programs, memory and cache
The cloud ecology conference comes with the "peak"!
Specificity and five applications of Worthington alcohol dehydrogenase