編輯:關於Android編程
關於的圖片緩存官方文檔:
https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#memory-cache
在你的應用程序的UI界面加載一張圖片是一件很簡單的事情,但是當你需要在界面上加載一大堆圖片的時候,情況就變得復雜起來。在很多情況下,(比如使用ListView, GridView 或者 ViewPager 這樣的組件),屏幕上顯示的圖片可以通過滑動屏幕等事件不斷地增加,最終會導致OOM。
為了保證內存的使用始終維持在一個合理的范圍,通常會把被移除屏幕的圖片進行回收處理。此時垃圾回收器也會認為你不再持有這些圖片的引用,從而對這些圖片進行GC操作。用這種思路來解決問題是非常好的,可是為了能讓程序快速運行,在界面上迅速地加載圖片,你又必須要考慮到某些圖片被回收之後,用戶又將它重新滑入屏幕這種情況。這時重新去加載一遍剛剛加載過的圖片無疑是性能的瓶頸,你需要想辦法去避免這個情況的發生。這個時候,使用內存緩存和磁盤緩存可以很好的解決這個問題,它可以讓組件快速地重新加載和處理圖片。
首先來看一下內存緩存:
內存緩存提供對圖片的快速訪問,其代價是占用應用程序的寶貴內存。其中最核心的類是LruCache (android-support-v4也有,兼容到level4) 。這個類非常適合用來緩存圖片,它的主要算法原理是把最近使用的對象用強引用存儲在 LinkedHashMap 中,並且把最近最少使用的對象在緩存值達到預設定值之前從內存中移除。
在過去,我們經常會使用一種非常流行的內存緩存技術的實現,即軟引用或弱引用 (SoftReference or WeakReference)。但是現在已經不再推薦使用這種方式了,因為從 Android 2.3 (API Level 9)開始,垃圾回收器會更傾向於回收持有軟引用或弱引用的對象,這讓軟引用和弱引用變得不再可靠。另外,Android 3.0 (API Level 11)之前,圖片的數據會存儲在本地的內存當中,因而無法用一種可預見的方式將其釋放,從而可能導致應用程序短暫超過其內存限制而崩潰。
為了能夠選擇一個合適的緩存大小給LruCache, 有以下多個因素應該放入考慮范圍內,例如:
你的設備可以為每個應用程序分配多大的內存?設備屏幕上一次最多能顯示多少張圖片?有多少圖片需要進行預加載,因為有可能很快也會顯示在屏幕上?你的設備的屏幕大小和分辨率分別是多少?一個超高分辨率的設備(例如 Galaxy Nexus) 比起一個較低分辨率的設備(例如 Nexus S),在持有相同數量圖片的時候,需要更大的緩存空間。圖片的尺寸和大小,還有每張圖片會占據多少內存空間。圖片被訪問的頻率有多高?會不會有一些圖片的訪問頻率比其它圖片要高?如果有的話,你也許應該讓一些圖片常駐在內存當中,或者使用多個LruCache 對象來區分不同組的圖片。你能維持好數量和質量之間的平衡嗎?有些時候,存儲多個低像素的圖片,而在後台去開線程加載高像素的圖片會更加的有效。並沒有一個指定的緩存大小可以滿足所有的應用程序,這是由你決定的。你應該去分析程序內存的使用情況,然後制定出一個合適的解決方案。一個太小的緩存空間,有可能造成圖片頻繁地被釋放和重新加載,這並沒有好處。而一個太大的緩存空間,則有可能還是會引起Java.lang.OutOfMemory 的異常。
下面就看一個demo,如何使用LruCache:
package cj.com.memorycache;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
private LruCache mMemoryCache;
private ImageView image;
private final static String TAG = "memorycache";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
int memoryCacheSize = 0;
ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = activityManager.getMemoryClass();
if(hasHoneycomb()&&isLargeHeap(this)){
memoryClass = activityManager.getLargeMemoryClass();
}
memoryCacheSize = (memoryClass*1024*1024)/8;//八分之一的內存作為內存緩存 單位是byte
Log.d(TAG,"memoryCacheSize="+memoryCacheSize);
mMemoryCache = new LruCache(memoryCacheSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
}
public void click(View v){
Log.d(TAG,"click");
loadBitmap(R.drawable.bigwheel,image);
}
private boolean hasHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
private static boolean isLargeHeap(Context context) {
return (context.getApplicationInfo().flags & ApplicationInfo.FLAG_LARGE_HEAP) != 0;
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
Log.d(TAG,"addBitmapToMemoryCache");
if (getBitmapFromMemCache(key) == null) {
Log.d(TAG,"memorycache has no this bitmap");
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
public void loadBitmap(int resId, ImageView imageView) {
final String imageKey = String.valueOf(resId);
final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
Log.d(TAG,"bitmap has in memorycache");
imageView.setImageBitmap(bitmap);
} else {
Log.d(TAG,"bitmap is not in memorycache");
imageView.setImageResource(R.mipmap.ic_launcher);
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
task.execute(resId);
}
}
class BitmapWorkerTask extends AsyncTask {
private final WeakReference imageViewReference;
private int data = 0;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference(imageView);
}
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), data, 100, 100);
if(bitmap != null){
addBitmapToMemoryCache(String.valueOf(data),bitmap);
return bitmap;
}
return null;
}
// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
private Bitmap decodeSampledBitmapFromResource(Resources res , int resId, int targetWidth, int tartgetHegiht){
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, targetWidth, tartgetHegiht);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
private int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
String imageType = options.outMimeType;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
int memoryCacheSize = 0;
ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = activityManager.getMemoryClass();
if(hasHoneycomb()&&isLargeHeap(this)){
memoryClass = activityManager.getLargeMemoryClass();
}
memoryCacheSize = (memoryClass*1024*1024)/8;//八分之一的內存作為內存緩存 單位是byte
Log.d(TAG,"memoryCacheSize="+memoryCacheSize);
這篇文章已經提到了。
mMemoryCache = new LruCache創建內存緩存對象LruCache,傳入的參數就是內存緩存的大小,重寫sizeOf函數,返回的該圖片的字節數。(memoryCacheSize){ @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); } };
public void click(View v){
Log.d(TAG,"click");
loadBitmap(R.drawable.bigwheel,image);
}
public void loadBitmap(int resId, ImageView imageView) {
final String imageKey = String.valueOf(resId);
final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
Log.d(TAG,"bitmap has in memorycache");
imageView.setImageBitmap(bitmap);
} else {
Log.d(TAG,"bitmap is not in memorycache");
imageView.setImageResource(R.mipmap.ic_launcher);
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
task.execute(resId);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
class BitmapWorkerTask extends AsyncTask{ private final WeakReference imageViewReference; private int data = 0; public BitmapWorkerTask(ImageView imageView) { // Use a WeakReference to ensure the ImageView can be garbage collected imageViewReference = new WeakReference (imageView); } // Decode image in background. @Override protected Bitmap doInBackground(Integer... params) { data = params[0]; Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), data, 100, 100); if(bitmap != null){ addBitmapToMemoryCache(String.valueOf(data),bitmap); return bitmap; } return null; } // Once complete, see if ImageView is still around and set bitmap. @Override protected void onPostExecute(Bitmap bitmap) { if (imageViewReference != null && bitmap != null) { final ImageView imageView = imageViewReference.get(); if (imageView != null) { imageView.setImageBitmap(bitmap); } } } }
decodeSampledBitmapFromResource()
加載完成後,將圖片添加到內存緩存中
if(bitmap != null){
addBitmapToMemoryCache(String.valueOf(data),bitmap);
return bitmap;
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
Log.d(TAG,"addBitmapToMemoryCache");
if (getBitmapFromMemCache(key) == null) {
Log.d(TAG,"memorycache has no this bitmap");
mMemoryCache.put(key, bitmap);
}
}
看一下log:
D/memorycache: memoryCacheSize=50331648
D/OpenGLRenderer: Render dirty regions requested: true
[ 10-18 08:03:48.339 3055: 3055 D/ ]
HostConnection::get() New Host Connection established 0x7feda1de3900, tid 3055
D/Atlas: Validating map...
[ 10-18 08:03:48.410 3055: 3148 D/ ]
HostConnection::get() New Host Connection established 0x7feda4433180, tid 3148
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Enabling debug mode 0
D/memorycache: click
D/memorycache: bitmap is not in memorycache
D/memorycache: addBitmapToMemoryCache
D/memorycache: memorycache has no this bitmap
D/memorycache: click
D/memorycache: bitmap has in memorycache
Application terminated.
Android基於service實現音樂的後台播放功能示例
本文實例講述了Android基於service實現音樂的後台播放功能。分享給大家供大家參考,具體如下:Service是一個生命周期長且沒有用戶界面的程序,當程序在各個ac
Android使用PullToRefresh完成ListView下拉刷新和左滑刪除
吹在前面的話:ListView下刷新刷功能相信從事Android開發的猿友們並不陌生,包括現在Google親兒子SwipeRefreshLayout實現效果在一些APP上
Android App架構設計
前言Web的架構經過多年的發展已經非常成熟了,我們常用的SSM,SSH等等,架構都非常標准。個人認為,Web服務邏輯比較清晰,目的明確,流程也相對固定,從服務器收到請求開
當ListView有Header時 onItemClick裡的position不正確的原因
當ListView實例addheaderView()或者addFooterView後,再通過setAdapter來添加適配器,此時在ListView實例變量裡保存的適配器