Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> android 雙緩存機制,android緩存機制

android 雙緩存機制,android緩存機制

編輯:關於android開發

android 雙緩存機制,android緩存機制


廢話不多說,直接貼代碼!

所謂的雙緩存,第一就是緩存在內存裡面,第二就是緩存在SD卡裡面,當你需要加載數據時,先去內存緩存中查找,如果沒有再去SD卡中查找,並且用戶可以自選使用哪種緩存!

緩存內存和緩存SD都有一個共同的方法,就是put和get方法(存數據和取數據),因此我們采用工廠模式!

新建一個接口,名字隨便取,用來封裝內存緩存和sd緩存裡面共有的方法,然後新建一個內存緩存類和sd緩存類,雙緩存類並且都實現此接口,注意建雙緩存類只是為了更方便的使用其他兩個緩存,你想想

如果兩個緩存類封裝到一個類中,並且這種類中會有判斷如何使用哪種緩存,這樣就減少了你每次調用哪種緩存就要修改代碼的過程了!

package com.example.imageload;

import android.graphics.Bitmap;

/*接口/

public interface MemoryCache {

public Bitmap get(String url);
public void put(String url ,Bitmap bitmap);
}

/*雙緩存類

* android雙向緩存,
* 先緩存到內存,在緩存到SD卡
* 取的時候先取內存,如果內存沒有就去SD裡面取
*/
public class DoubleCache implements MemoryCache{
private MemoryCache cache = new ImageCache();//內存緩存
private MemoryCache diskCache = new DiskCache();//SD開緩存

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);
}
}

/*內存緩存類/

public class ImageCache implements MemoryCache{
//圖片緩存
LruCache<String, Bitmap> mImageCache;

public ImageCache() {
initImageCache();
}
/**
* bitmap.getRowBytes():計算位圖每一行占用的字節數
*
*/
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卡緩存類/

public class DiskCache implements MemoryCache{
private String cacheDir = "/data/data/com.example.day8_12/files/"; //存儲目錄自己選擇
/**
* @param url 存放圖片的路徑名稱
* @return 返回位圖,如果沒有就返回0
*/
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();
}
}
}
}
}

/*最後就是顯示圖片的類/

public class ImageLoader {

ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private MemoryCache cache = new DiskCache();
private Activity 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() {
//這是為了匹配uri跟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;
}

最後記得加上權限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

在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;
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved