Android dual-Cache Mechanism and android Cache Mechanism
Don't talk nonsense. paste the Code directly!
The so-called dual-Cache: the first is the cache in the memory, and the second is the cache in the SD card. When you need to load data, first go to the memory cache to find the data. If not, go to the SD card to find the data, what kind of cache can users choose!
Cache memory and cache SD both have a common method, namely put and get (store data and retrieve data), so we adopt the factory mode!
Create an interface with the same name. It is used to encapsulate the methods in the memory cache and sd cache. Then, create a memory cache class and sd cache class. The dual cache class also implements this interface, note that the dual cache class is only used to make it easier to use the other two caches.
If the two cache classes are encapsulated in one class, and the class determines how to use the cache, this reduces the process of modifying the code each time you call the cache!
Package com. example. imageload;
Import android. graphics. Bitmap;
/* Interface/
Public interface MemoryCache {
Public Bitmap get (String url );
Public void put (String url, Bitmap bitmap );
}
/* Double Cache
* Android bidirectional cache,
* First cache to memory, then cache to SD card
* Take the memory first. If the memory does not exist, retrieve it from SD.
*/
Public class DoubleCache implements MemoryCache {
Private MemoryCache cache = new ImageCache (); // memory cache
Private MemoryCache diskCache = new DiskCache (); // SD open Cache
Public Bitmap get (String uri ){
Bitmap bm = cache. get (uri );
If (bm = null ){
Bm = diskCache. get (uri );
}
Return bm;
}
Public void put (String url, Bitmap bitmap ){
Cache. put (url, bitmap );
DiskCache. put (url, bitmap );
}
}
/* Memory cache class/
Public class ImageCache implements MemoryCache {
// Image Cache
LruCache <String, Bitmap> mImageCache;
Public ImageCache (){
InitImageCache ();
}
/**
* Bitmap. getRowBytes (): calculates the number of bytes occupied by each row of the bitmap.
*
*/
Private void initImageCache (){
Final int maxMemory = (int) Runtime. getRuntime (). maxMemory ()/1024;
Int cacheSize = maxMemory/4;
MImageCache = new LruCache <String, Bitmap> (cacheSize ){
@ Override
Protected int sizeOf (String key, Bitmap bitmap ){
Return bitmap. getRowBytes () * bitmap. getHeight ()/1024;
}
};
}
Public Bitmap get (String uri ){
Return mImageCache. get (uri );
}
Public void put (String uri, Bitmap bitmap ){
MImageCache. put (uri, bitmap );
}
}
/* SD card cache class/
Public class DiskCache implements MemoryCache {
Private String cacheDir = "/data/com. example. day8_12/files/"; // select the storage directory
/**
* @ Param url: path name for storing images
* @ Return returns the bitmap. If not, 0 is returned.
*/
Public Bitmap get (String url ){
Return BitmapFactory. decodeFile (cacheDir + setUrl (url ));
}
Public String setUrl (String url ){
Int b1 = url. lastIndexOf ("/");
String cc = url. substring (b1 + 1 );
Return cc;
}
Public void put (String url, Bitmap bitmap ){
File settings = new File (cacheDir, setUrl (url ));
If (! Settings. exists ()){
Try {
Settings. createNewFile ();
} Catch (IOException e ){
E. printStackTrace ();
Return;
}
}
FileOutputStream fileInputStream = null;
Try {
FileInputStream = new FileOutputStream (settings );
Bitmap. compress (CompressFormat. PNG, 100, fileInputStream );
FileInputStream. flush ();
} Catch (Exception e ){
Log. I ("TAG", "EEEEE" + e. getMessage ());
E. printStackTrace ();
} Finally {
If (fileInputStream! = Null ){
Try {
FileInputStream. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
}
/* Finally, the class for displaying images/
Public class ImageLoader {
ExecutorService service = Executors. newFixedThreadPool (Runtime. getRuntime (). availableProcessors ());
Private MemoryCache cache = new DiskCache ();
Private Activity;
Public void setImageCache (MemoryCache memoryCache ){
This. cache = memoryCache;
}
Public ImageLoader (Activity activity ){
This. activity = activity;
}
Public void displayImage (final String imageurl, final ImageView imageview ){
Bitmap bmp = cache. get (imageurl );
If (bmp! = Null ){
Imageview. setImageBitmap (bmp );
Return;
}
Imageview. setTag (imageurl );
Service. submit (new Runnable (){
@ Override
Public void run (){
Final Bitmap bitmap = downloadImage (imageurl );
If (bitmap = null ){
Log. I ("TAG", "0000" + bitmap );
Return;
}
Activity. runOnUiThread (new Runnable (){
@ Override
Public void run (){
// This is to match uri and imagview.
If (imageview. getTag (). equals (imageurl )){
Imageview. setImageBitmap (bitmap );
}
Cache. put (imageurl, bitmap );
}
});
}
});
}
Public Bitmap downloadImage (String imageurl ){
Bitmap bitmap = null;
Try {
URL url = new URL (imageurl );
HttpURLConnection connection = (HttpURLConnection) url. openConnection ();
Connection. setConnectTimeout (1000 );
Bitmap = BitmapFactory. decodeStream (connection. getInputStream ());
Connection. disconnect ();
} Catch (Exception e ){
Log. I ("TAG", "123:" + e. getMessage ());
E. printStackTrace ();
}
Return bitmap;
}
Remember to add permissions.
<Uses-permission android: name = "android. permission. INTERNET"/>
<Uses-permission android: name = "android. permission. READ_EXTERNAL_STORAGE"/>
The following is called in MainActivity:
Public class MainActivity extends Activity {
Private ImageView iamge;
Private List <String> list = new ArrayList <String> ();
Private ImageLoader imageLoader = new ImageLoader (MainActivity. this );
Private Button button1;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
// Drawable image = getResources (). getDrawable (R. drawable. ic_launcher );
Button1 = (Button) findViewById (R. id. button1 );
Iamge = (ImageView) findViewById (R. id. iamge );
ImageLoader. setImageCache (new DoubleCache ());
List. add ("http: // 192.168.58.112: 1918/hotel/public/upload/video/dy009.jpg ");
List. add ("http: // 192.168.58.112: 1918/hotel/public/upload/video/dy011.jpg ");
List. add ("http: // 192.168.58.112: 1918/hotel/public/upload/video/dy085.jpg ");
List. add ("http: // 192.168.58.112: 1918/hotel/public/upload/video/dy064.jpg ");
List. add ("http: // 192.168.58.112: 1918/hotel/public/upload/video/dy026.jpg ");
List. add ("http: // 192.168.58.112: 1918/hotel/public/upload/video/dy150.jpg ");
List. add ("http: // 192.168.58.112: 1918/hotel/public/upload/video/dy050.jpg ");
Button1.setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
Intent intent = new Intent (MainActivity. this, AMainActivity. class );
StartActivity (intent );
}
});
}
@ Override
Protected void onResume (){
// TODO Auto-generated method stub
Super. onResume ();
ImageLoader. displayImage (list. get (0), iamge );
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// Inflate the menu; this adds items to the action bar if it is present.
GetMenuInflater (). inflate (R. menu. main, menu );
Return true;
}