android 雙緩衝機制,android緩衝機制

來源:互聯網
上載者:User

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.