[Android] Caching mechanism

Source: Internet
Author: User

Mobile development is essentially a communication between a mobile phone and a server, which requires data to be fetched from the service side. It is time-consuming to get data over the network repeatedly, especially when the access is more, it will greatly affect the performance, and the cache mechanism can reduce the frequent network operation, reduce the traffic and improve the performance in Android.

Implementation principle

Cache data that does not need to be updated in real time, by time or other factors to determine whether it is read cache or network request, this can alleviate the server pressure, to some extent, improve the application response speed, and support offline reading.
  

Cache of Bitmap

In many cases (such as a ListView, GridView, or viewpager) we need to load a large number of images at once, the pictures displayed on the screen and all the images to be displayed may need to be scrolled and toggled on the screen without any restrictions at once.

Such components as the ListView, GridView, and their subkeys when not visible, the memory consumed is reclaimed for use by the foreground display subkey. The garbage collector also frees up the memory that you have loaded for pictures. If you want your UI to run smoothly, you should not reload the image every time you display it. It becomes necessary to keep some memory and file caches.

Use memory Cache

By pre-consuming a bit of memory in your application to store data, you can quickly provide data to components in your application, which is a typical space-for- time strategy.
The LruCache class (available in the Android V4 Support Library class Library) is ideal for image caching tasks, which can be used to save recently used objects using a strong linkedhashmap reference. And when the object it holds occupies more memory than the maximum memory is designed for it, the infrequently used object members are kicked out for recycling by the garbage collector.

To set a suitable memory size for LRUCache, consider the following factors:

    • How much memory is left for your activity or app use
    • How many pictures and how many pictures are waiting to be displayed on the screen at once
    • What is the size and density of the phone (the higher the density of the device requires the larger the cache)
    • The size of the picture (which determines the amount of memory consumed)
    • The frequency with which the picture is accessed (high frequency is kept in memory)
    • Save the quality of the picture (different pixels are displayed under different circumstances)

Specific to the application of the picture to use the specific circumstances to find a suitable solution, a set of LruCache example:

PrivateLrucache<string, bitmap> Mmemorycache;@Overrideprotected void onCreate(Bundle savedinstancestate) {    ...//gain maximum memory provided by virtual function, exceeding this size will throw OutOfMemory exception    Final intMaxMemory = (int) (Runtime.getruntime (). MaxMemory ()/1024x768);//Use 1/8 memory size as memory cache    Final intCacheSize = maxmemory/8; Mmemorycache =NewLrucache<string, bitmap> (cacheSize) {@Override        protected int sizeOf(String key, Bitmap Bitmap) {//is not the number of items returned here, it is the size of the cache (1024 bytes per unit)            returnBitmap.getbytecount ()/1024x768;    }    }; ...} Public void Addbitmaptomemorycache(String key, Bitmap Bitmap) {if(Getbitmapfrommemcache (key) = =NULL) {Mmemorycache.put (key, bitmap); }} PublicBitmapGetbitmapfrommemcache(String key) {returnMmemorycache.get (key);}

When loading a picture for ImageView, we will first look at the LRUCache to see if there is a cached image, and if so, update it directly to ImageView, and if not, a background thread will be triggered to load the image.

publicvoidloadBitmap(int resId, ImageView imageView) {    final String imageKey = String.valueOf(resId);    // 查看下内存缓存中是否缓存了这张图片    final Bitmap bitmap = getBitmapFromMemCache(imageKey);    ifnull) {        mImageView.setImageBitmap(bitmap);    else {        new BitmapWorkerTask(mImageView);        task.execute(resId);    }}

In the task that the picture loads, the loaded picture needs to be added to the in-memory cache.

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {    ...    // 在后台完成    @Override    protected Bitmap doInBackground(Integer... params) {        final Bitmap bitmap = decodeSampledBitmapFromResource(                getResources(), params[0100100));    addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);        return bitmap;    }    ...}
Using Disk caching

The memory cache is able to quickly get to the most recently displayed picture, but it is not necessarily available. It is easy to fill up the memory cache (such as the GridView) when the data set is too large. Your application may also be interrupted by other tasks (such as incoming calls) into the background, the background application may be killed, then the corresponding memory cache objects will be destroyed. When your app returns to the foreground, your app needs a single image to load.

Disk File cache can be used to handle these situations, save the processed pictures, when the memory cache is not available, directly read the saved pictures on the hard disk, this can effectively reduce the number of pictures loaded. Reading a disk file is slower than reading directly from the in-memory cache and needs to be done in a thread outside the main UI, because the disk's read speed is not guaranteed, and the disk file cache is obviously a space-time-changing strategy.

If the picture is used very frequently, a contentprovider may be more suitable instead of storing cached images, compared to tablet gallery applications.

Here is a partial code for a disklrucache:

PrivateDisklrucache Mdisklrucache;Private FinalObject Mdiskcachelock =NewObject ();Private BooleanMdiskcachestarting =true;Private Static Final intDisk_cache_size =1024x768*1024x768*Ten;//10MBPrivate Static FinalString Disk_cache_subdir ="Thumbnails"; @Overrideprotected voidOnCreate (Bundle savedinstancestate) {...//Initialize memory cache...//Initialize the disk cache in a background threadFile Cachedir = Getdiskcachedir ( This, Disk_cache_subdir);NewInitdiskcachetask (). Execute (CACHEDIR); ...} class initdiskcachetask extends asynctask<File, Void, Void> {@OverrideprotectedVoid doinbackground (File ... params) {synchronized (mdiskcachelock) {File Cachedir = params[0];  Mdisklrucache = Disklrucache.open (Cachedir, disk_cache_size); Mdiskcachestarting =false;//End of initializationMdiskcachelock.notifyall ();//wake-up waiting thread}return NULL; }} class bitmapworkertask extends asynctask<Integer, Void , Bitmap> {...//Parse pictures in the background@OverrideprotectedBitmap doinbackground (Integer ... params) {FinalString ImageKey = string.valueof (params[0]);//Detect disk cache in a background threadBitmap Bitmap = Getbitmapfromdiskcache (ImageKey);if(Bitmap = =NULL) {//No pictures found in the disk cache FinalBitmap Bitmap = Decodesampledbitmapfromresource (Getresources (), params[0], -, -)); }//Add this final type of bitmap to the cacheAddbitmaptocache (ImageKey, bitmap);returnBitmap }    ...} Public voidAddbitmaptocache (String key, Bitmap Bitmap) {//Add to memory cache first    if(Getbitmapfrommemcache (key) = =NULL) {Mmemorycache.put (key, bitmap); }//Add to disk cacheSynchronized (Mdiskcachelock) {if(Mdisklrucache! =NULL&& mdisklrucache.get (key) = =NULL) {Mdisklrucache.put (key, bitmap); }    }} PublicBitmap Getbitmapfromdiskcache (String key) {synchronized (Mdiskcachelock) {//Wait for disk cache to open from background thread         while(mdiskcachestarting) {Try{mdiskcachelock.wait (); }Catch(Interruptedexception e) {}        }if(Mdisklrucache! =NULL) {returnMdisklrucache.get (key); }    }return NULL;} Public StaticFile Getdiskcachedir (Context context, String UniqueName) {//Prioritize the use of an out-of-cache path, and use an internal cache path if there is no out-of-mount storageFinalString CachePath = Environment.MEDIA_MOUNTED.equals (Environment.getexternalstoragestate ()) | |! Isexternalstorageremovable ()? Getexternalcachedir (context). GetPath (): Context.getcachedir (). GetPath ();return NewFile (CachePath + file.separator + uniqueName);}

This cannot be done in the main thread of the UI, because initializing the disk cache also requires operations on the disk. In the program fragment above, a lock object ensures that the disk cache does not have access to the disk cache until the initialization is complete.

The memory cache is instrumented in the UI thread, and the disk cache is detected in threads outside the main thread of the UI, and when the picture processing is complete, it is stored in the memory cache and the disk cache, respectively.

Load problem when device configuration parameter is changed

Since the device configuration parameters may change when the application is running, such as the device facing changes, it will cause Android to destroy your activity and then restart it according to the new configuration, in which case we have to avoid reloading the processing of all the images, so that users can have a smooth experience.

Use fragment to pass a memory cache object to a new activity instance, calling Setretaininstance (true)) to preserve the fragment instance. When the activity is re-created, the retained fragment is attached to the activity and the existing memory cache object can be obtained by fragment, so that the image can be quickly obtained and set to ImageView. Give the user a smooth experience.

Here is a sample program fragment:

PrivateLrucache<string, bitmap> Mmemorycache;@Overrideprotected void onCreate(Bundle savedinstancestate) {    ...    Retainfragment mretainfragment = retainfragment.findorcreateretainfragment (Getfragmentmanager ()); Mmemorycache = Retainfragment.mretainedcache;if(Mmemorycache = =NULL) {Mmemorycache =NewLrucache<string, bitmap> (cacheSize) {...//Initialize the cache as in the example above} Mretainfragment.mretainedcache = Mmemorycache; }    ...} Class Retainfragment extends Fragment {Private Static FinalString TAG ="Retainfragment"; PublicLrucache<string, bitmap> Mretainedcache; Public retainfragment() {} Public StaticRetainfragmentfindorcreateretainfragment(Fragmentmanager FM) {Retainfragment fragment = (retainfragment) fm.findfragmentbytag (TAG);if(Fragment = =NULL) {fragment =NewRetainfragment (); }returnFragment }@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//So that fragment can be preserved after the activity is destroyed .Setretaininstance (true); }}

You can rotate the device screen without the fragment (service class fragment without the interface). In the case of preserving the cache, you should be able to see that the fill image is almost instantaneous from memory in the activity without any sense of delay. Any picture takes precedence from the memory cache, no words to the hard disk cache, if not, then load the image in a normal way.
  
Reference:

Caching Bitmaps

LruCache

Using SQLite for caching

After the network request data is completed, the relevant information of the file (such as the URL (generally as a unique identifier), download time, expiration time) and so on to the database. The next time you load the query from the database according to the URL, if the query and time has not expired, according to the path to read local files, so as to achieve the effect of caching.

Note: The cached database is stored in the/data/data//databases/directory, is occupied memory space, if the cache accumulated, easy to waste memory, need to clean up the cache in a timely manner.

File cache

Thinking and the general cache, the need to store the data in the file, the next time the load to determine whether the file exists and expire (using the file.lastmodified () method to get the last modification time of the file, and the current time to judge), there is no expiration of the data in the loading file, Otherwise the request server is re-downloaded.

Note that there is no network environment in which the file cache is read by default.

[Android] Caching mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.