问题描述
图像将不会出现在设备内部存储和缓存崩溃无需外部SD卡。我曾尝试我所知道的并没有什么工作。这里是ImageCache.java
包com.minecraftpix.android.bitmapfun.util; 进口com.minecraftpix.BuildConfig;进口android.annotation.TargetApi;
进口android.content.Context;
进口android.graphics.Bitmap;
进口android.graphics.Bitmap.Com pressFormat;
进口android.graphics.BitmapFactory;
进口android.graphics.drawable.BitmapDrawable;
进口android.os.Bundle;
进口android.os.Environment;
进口android.os.StatFs;
进口android.support.v4.app.Fragment;
进口android.support.v4.app.FragmentManager;
进口android.support.v4.util.LruCache;
进口android.util.Log;进口的java.io.File;
进口java.io.FileDescriptor中;
进口java.io.FileInputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口java.lang.ref.SoftReference;
进口java.security.MessageDigest中;
进口java.security.NoSuchAlgorithmException;
进口java.util.HashSet中;
进口java.util.Iterator的;
公共类ImageCache {
私有静态最后弦乐TAG =ImageCache;以千字节//默认内存缓存大小
私有静态最终诠释DEFAULT_MEM_CACHE_SIZE = 1024 * 5; // 5MB以字节为单位//默认磁盘缓存大小
私有静态最终诠释DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB//写映像磁盘缓存时的COM pression设置
私有静态最后的COM pressFormat DEFAULT_COM preSS_FORMAT = com的pressFormat.JPEG;
私有静态最终诠释DEFAULT_COM preSS_QUALITY = 70;
私有静态最终诠释DISK_CACHE_INDEX = 0;//常量轻松切换各种缓存
私有静态最终布尔DEFAULT_MEM_CACHE_ENABLED = TRUE;
私有静态最终布尔DEFAULT_DISK_CACHE_ENABLED = TRUE;
私有静态最终布尔DEFAULT_INIT_DISK_CACHE_ON_CREATE = FALSE;私人DiskLruCache mDiskLruCache;
私人LruCache<弦乐,BitmapDrawable> mMemoryCache;
私人ImageCacheParams mCacheParams;
私人最终对象mDiskCacheLock =新的对象();
私人布尔mDiskCacheStarting = TRUE;私人的HashSet<&SoftReference的LT;位图>> mReusableBitmaps;/ **
*创建使用指定的参数的新ImageCache对象。这不应该
*由其他类直接调用,而是使用
* {@link ImageCache#的getInstance(FragmentManager,ImageCacheParams)}获取一个ImageCache
*实例。
*
* @参数cacheParams缓存参数来使用,以初始化缓存
* /
私人ImageCache(ImageCacheParams cacheParams){
的init(cacheParams);
}/ **
*返回一个{@link ImageCache}实例。 A {@link RetainFragment}用于保留
*跨配置变化,如设备方向的变化ImageCache对象。
*
* @参数fragmentManager片段经理与所保留的片段打交道时使用。
* @参数cacheParams缓存参数,如果需要ImageCache实例使用。
返回:现有保留ImageCache对象或一个新的,如果一个不存在
* /
公共静态ImageCache的getInstance(
FragmentManager fragmentManager,ImageCacheParams cacheParams){ //搜索,或者创建非UI RetainFragment的一个实例
最后RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager); //看看我们是否已经存储在RetainFragment的ImageCache
ImageCache imageCache =(ImageCache)mRetainFragment.getObject(); //没有现成的ImageCache,创建一个并将其存储在RetainFragment
如果(imageCache == NULL){
imageCache =新ImageCache(cacheParams);
mRetainFragment.setObject(imageCache);
} 返回imageCache;
}/ **
*初始化缓存,提供所有的参数。
*
* @参数cacheParams缓存参数初始化缓存
* /
私人无效的init(ImageCacheParams cacheParams){
mCacheParams = cacheParams; //设置内存缓存
如果(mCacheParams.memoryCacheEnabled){
如果(BuildConfig.DEBUG){
Log.d(TAG,创建存储器缓存(大小=+ mCacheParams.memCacheSize +));
} //如果我们在Honeycomb或更高版本上运行,那么
如果(Utils.hasHoneycomb()){
mReusableBitmaps =新的HashSet<&SoftReference的LT;位图>>();
} mMemoryCache =新LruCache<弦乐,BitmapDrawable>(mCacheParams.memCacheSize){ / **
*通知不再被缓存条目中删除
* /
@覆盖
保护无效entryRemoved(布尔拆迁户,串键,
BitmapDrawable属性oldValue,BitmapDrawable为newValue){
如果(RecyclingBitmapDrawable.class.isInstance(属性oldValue)){
//去除的条目是一个循环绘制,所以它通知
//它已经从内存中缓存中删除
((RecyclingBitmapDrawable)的属性oldValue).setIsCached(假);
}其他{
//去除的入口是一个标准的BitmapDrawable 如果(Utils.hasHoneycomb()){
//我们在Honeycomb上运行或更高版本,所以加位图
//为可能使用设定inBitmap后来SoftRefrence
mReusableBitmaps.add(新SoftReference的&所述;位图>(oldValue.getBitmap()));
}
}
} / **
*测量项目的大小以KB为单位,而不是单位是更实用
*为位图缓存
* /
@覆盖
保护INT整型尺寸(字符串键,BitmapDrawable值){
最终诠释bitmapSize = getBitmapSize(值)/ 1024;
返回bitmapSize == 0? 1:bitmapSize;
}
};
} //默认情况下,磁盘缓存这里没有初始化,因为它应该被初始化
//在单独的线程由于磁盘访问。
如果(cacheParams.initDiskCacheOnCreate){
//设置磁盘缓存
initDiskCache();
}
}/ **
*初始化磁盘缓存。注意,这包括磁盘访问,因此这不应该是
*主/ UI线程执行。默认情况下的ImageCache不初始化磁盘
*高速缓存被创建时,而应该叫initDiskCache()来初始化它在一个
*后台线程。
* /
公共无效initDiskCache(){
//设置磁盘缓存
同步(mDiskCacheLock){
如果(mDiskLruCache == NULL || mDiskLruCache.isClosed()){
文件diskCacheDir = mCacheParams.diskCacheDir;
如果(mCacheParams.diskCacheEnabled&安培;&安培;!diskCacheDir = NULL){
如果(!diskCacheDir.exists()){
diskCacheDir.mkdirs();
}
如果(getUsableSpace(diskCacheDir)GT; mCacheParams.diskCacheSize){
尝试{
mDiskLruCache = DiskLruCache.open(
diskCacheDir,1,1,mCacheParams.diskCacheSize);
如果(BuildConfig.DEBUG){
Log.d(TAG,磁盘缓存初始化);
}
}赶上(最终IOException异常五){
mCacheParams.diskCacheDir = NULL;
Log.e(TAGinitDiskCache - + E);
}
}
}
}
mDiskCacheStarting = FALSE;
mDiskCacheLock.notifyAll();
}
}/ **
*添加一个位图到内存和磁盘缓存。
* @参数数据的唯一标识符位图存储
*参数值的位图绘制存储
* /
公共无效addBitmapToCache(字符串数据,BitmapDrawable值){
如果(数据== NULL ||值== NULL){
返回;
} //添加到内存缓存
如果(mMemoryCache!= NULL){
如果(RecyclingBitmapDrawable.class.isInstance(值)){
//去除的条目是一个循环绘制,所以它通知
//它已被加入到所述存储器缓存
((RecyclingBitmapDrawable)值).setIsCached(真);
}
mMemoryCache.put(数据值);
} 同步(mDiskCacheLock){
//添加到磁盘缓存
如果(mDiskLruCache!= NULL){
最终字符串键= hashKeyForDisk(数据);
出的OutputStream = NULL;
尝试{
DiskLruCache.Snapshot快照= mDiskLruCache.get(键);
如果(快照== NULL){
最后DiskLruCache.Editor编辑= mDiskLruCache.edit(键);
如果(编辑!= NULL){
OUT = editor.newOutputStream(DISK_CACHE_INDEX);
value.getBitmap()。com preSS(
mCacheParams.com pressFormat,mCacheParams.com pressQuality,出);
editor.commit();
out.close();
}
}其他{
snapshot.getInputStream(DISK_CACHE_INDEX).close();
}
}赶上(最终IOException异常五){
Log.e(TAGaddBitmapToCache - + E);
}赶上(例外五){
Log.e(TAGaddBitmapToCache - + E);
} {最后
尝试{
如果(满分!= NULL){
out.close();
}
}赶上(IOException异常五){}
}
}
}
}/ **
*从内存缓存中获取。
*
* @参数数据的唯一标识符哪个项目获得
返回:位图绘制如果缓存中找到,否则返回null
* /
公共BitmapDrawable getBitmapFromMemCache(字符串数据){
BitmapDrawable memValue = NULL; 如果(mMemoryCache!= NULL){
memValue = mMemoryCache.get(数据);
} 如果(BuildConfig.DEBUG&安培;&安培;!memValue = NULL){
Log.d(TAG内存高速缓存命中);
} 返回memValue;
}/ **
*从磁盘缓存获取。
*
* @参数数据的唯一标识符哪个项目获得
返回:位图如果缓存中找到,否则返回null
* /
公共位图getBitmapFromDiskCache(字符串数据){
最终字符串键= hashKeyForDisk(数据);
位图位图= NULL; 同步(mDiskCacheLock){
而(mDiskCacheStarting){
尝试{
mDiskCacheLock.wait();
}赶上(InterruptedException的E){}
}
如果(mDiskLruCache!= NULL){
为InputStream的InputStream = NULL;
尝试{
最后DiskLruCache.Snapshot快照= mDiskLruCache.get(键);
如果(快照!= NULL){
如果(BuildConfig.DEBUG){
Log.d(TAG,磁盘高速缓存命中);
}
的InputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
如果(的InputStream!= NULL){
FD的FileDescriptor =((的FileInputStream)的InputStream).getFD(); //德code位图,但我们不希望品尝所以放弃
// MAX_VALUE为目标尺寸
位= ImageResizer.de codeSampledBitmapFromDescriptor(
FD,是Integer.MAX_VALUE,Integer.MAX_VALUE的,这一点);
}
}
}赶上(最终IOException异常五){
Log.e(TAGgetBitmapFromDiskCache - + E);
} {最后
尝试{
如果(的InputStream!= NULL){
inputStream.close();
}
}赶上(IOException异常五){}
}
}
返回位图;
}
}/ **
* @参数选项 - BitmapFactory.Options与填充了*选项
这种情况下,被用于inBitmap * @返回位图
* /
保护位图getBitmapFromReusableSet(BitmapFactory.Options选项){
位图位图= NULL; 如果(mReusableBitmaps =空&放大器;!&放大器;!mReusableBitmaps.isEmpty()){
最后的迭代器<&SoftReference的LT;位图>>迭代= mReusableBitmaps.iterator();
位图项目; 而(iterator.hasNext()){
项目= iterator.next()获得()。 如果(空=项目和放大器;!&安培; item.isMutable()){
//检查它的项目可用于inBitmap
如果(canUseForInBitmap(项目,期权)){
位=项目; //从可重复使用的集中删除,因此无法再次使用
iterator.remove();
打破;
}
}其他{
如果参考已被清除从设定//删除。
iterator.remove();
}
}
} 返回位图;
}/ **
*同时清除与此ImageCache对象关联的内存和磁盘高速缓存。注意
*这包括所以这应该不是主要/ UI线程上执行磁盘访问。
* /
公共无效clearCache(){
如果(mMemoryCache!= NULL){
mMemoryCache.evictAll();
如果(BuildConfig.DEBUG){
Log.d(TAG内存缓存中清除);
}
} 同步(mDiskCacheLock){
mDiskCacheStarting = TRUE;
如果(mDiskLruCache =空&放大器;!&放大器;!mDiskLruCache.isClosed()){
尝试{
mDiskLruCache.delete();
如果(BuildConfig.DEBUG){
Log.d(TAG,磁盘缓存中清除);
}
}赶上(IOException异常五){
Log.e(TAGclearCache - + E);
}
mDiskLruCache = NULL;
initDiskCache();
}
}
}/ **
*刷新与此ImageCache对象关联的磁盘缓存。注意,这包括
*所以这个磁盘访问应该不是主/ UI线程上执行。
* /
公共无效的flush(){
同步(mDiskCacheLock){
如果(mDiskLruCache!= NULL){
尝试{
mDiskLruCache.flush();
如果(BuildConfig.DEBUG){
Log.d(TAG,磁盘高速缓存刷新);
}
}赶上(IOException异常五){
Log.e(TAG,刷新 - + E);
}
}
}
}/ **
*关闭与此ImageCache对象关联的磁盘缓存。注意,这包括
*所以这个磁盘访问应该不是主/ UI线程上执行。
* /
公共无效的close(){
同步(mDiskCacheLock){
如果(mDiskLruCache!= NULL){
尝试{
如果(!mDiskLruCache.isClosed()){
mDiskLruCache.close();
mDiskLruCache = NULL;
如果(BuildConfig.DEBUG){
Log.d(TAG,磁盘缓存关闭);
}
}
}赶上(IOException异常五){
Log.e(TAG,关闭 - + E);
}
}
}
}/ **
*包含缓存参数holder类。
* /
公共静态类ImageCacheParams {
公众诠释memCacheSize = DEFAULT_MEM_CACHE_SIZE;
公众诠释diskCacheSize = DEFAULT_DISK_CACHE_SIZE;
公共文件diskCacheDir;
公众的COM pressFormat COM pressFormat = DEFAULT_COM preSS_FORMAT;
公众诠释COM pressQuality = DEFAULT_COM preSS_QUALITY;
公共布尔memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;
公共布尔diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED;
公共布尔initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE; / **
*创建的一组图像的缓存参数可被提供给
* {@link ImageCache#的getInstance(FragmentManager,ImageCacheParams)}或
* {@link ImageWorker#addImageCache(FragmentManager,ImageCacheParams)}。
* @参数上下文中的上下文中使用。
* @参数diskCacheDirectoryName将被附加到一个独特的子目录名称
*应用程序缓存目录中。通常缓存或图像
* 足够了。
* /
公共ImageCacheParams(上下文的背景下,字符串diskCacheDirectoryName){
diskCacheDir = getDiskCacheDir(背景下,diskCacheDirectoryName);
} / **
*设置基础上,最大可用VM内存百分比的内存缓存大小。
*如:设置%至0.2将内存缓存设置为可用的五分之一
*内存。抛出{@link}抛出:IllegalArgumentException如果百分比为< 0.05或GT; 0.8。
* memCacheSize存储在千字节而不是字节,因为这最终会通过
*构建LruCache这需要一个int在其构造。
*
*此值应选择仔细根据许多因素
*请参阅更多的讨论相应的Android培训类:
* http://developer.android.com/training/displaying-bitmaps/
*
*可用的应用程序内存的百分之@param百分比使用大小内存缓存
* /
公共无效setMemCacheSizePercent(浮动百分比){
如果(百分号< 0.05f ||%的> 0.8f){
抛出新抛出:IllegalArgumentException(setMemCacheSizePercent - 百分比必须
+)0.05和0.8(含)之间的;
}
memCacheSize = Math.round(百分比*调用Runtime.getRuntime()maxMemory()/ 1024);
}
}/ **
* @参数候选人 - 位图检查
* @参数targetOptions - 具有出*值填充选项
* @返回true,如果< code>候选LT; / code>可用于与inBitmap再利用
*< code基targetOptions< / code>
* /
私有静态布尔canUseForInBitmap(
位图候选人,BitmapFactory.Options targetOptions){
INT宽度= targetOptions.outWidth / targetOptions.inSampleSize;
INT高度= targetOptions.outHeight / targetOptions.inSampleSize; 返回candidate.getWidth()==宽度放大器;&放大器; candidate.getHeight()==高度;
}/ **
*获得一个可用的缓存目录(外部如果可用,否则内部)。
*
* @参数上下文中使用的上下文
* @参数uniqueName唯一的目录名称追加到缓存目录
返回:缓存目录
* /
公共静态文件getDiskCacheDir(上下文的背景下,字符串uniqueName){
//检查介质安装或存储是内置的,如果是的话,尽量使用外部缓存目录
//否则使用内部缓存目录
最后弦乐cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())||
!isExternalStorageRemovable()? getExternalCacheDir(上下文).getPath():
context.getCacheDir()的getPath()。 返回新的文件(cachePath +文件分割符+ uniqueName);
}/ **
*改变一个字符串(如URL)为哈希适合用作一个散列法
*磁盘文件名。
* /
公共静态字符串hashKeyForDisk(字符串键){
串cacheKey;
尝试{
最后消息摘要mDigest = MessageDigest.getInstance(MD5);
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
}赶上(抛出:NoSuchAlgorithmException E){
cacheKey =将String.valueOf(key.hash code());
}
返回cacheKey;
}私人静态字符串bytesToHexString(字节[]字节){
// http://stackoverflow.com/questions/332079
StringBuilder的SB =新的StringBuilder();
的for(int i = 0; I< bytes.length;我++){
十六进制的字符串= Integer.toHexString(0xFF的&安培;字节[I]);
如果(hex.length()== 1){
sb.append('0');
}
sb.append(十六进制);
}
返回sb.toString();
}/ **
*在一个BitmapDrawable位图字节获取的大小。
* @参数值
以字节为单位* @返回大小
* /
@TargetApi(12)
公共静态INT getBitmapSize(BitmapDrawable值){
位图的位图= value.getBitmap(); 如果(Utils.hasHoneycombMR1()){
返回bitmap.getByteCount();
}
// pre HC-MR1
返回bitmap.getRowBytes()* bitmap.getHeight();
}/ **
*检查外部存储内置或可移除的。
*
*如果外部存储是可移动的(如SD卡),假@返回真
* 除此以外。
* /
@TargetApi(9)
公共静态布尔isExternalStorageRemovable(){
如果(Utils.hasGingerbread()){
返回Environment.isExternalStorageRemovable();
}
返回true;
}/ **
*获取外部应用程序缓存目录。
*
* @参数上下文中使用的上下文
* @返回外部缓存目录
* /
@TargetApi(8)
公共静态文件getExternalCacheDir(上下文的背景下){
如果(Utils.hasFroyo()){
返回context.getExternalCacheDir();
} //升级Froyo之前,我们需要构建外部缓存目录自己
最后弦乐cacheDir =/ Android的/数据/+ context.getPackageName()+/缓存/;
返回新的文件(Environment.getExternalStorageDirectory()的getPath()+ cacheDir);
}/ **
*检查多少可用空间可在给定的路径。
*
* @参数路径检查路径
* @返回以字节为单位的可用空间
* /
@TargetApi(9)
公共静态长getUsableSpace(文件路径){
如果(Utils.hasGingerbread()){
返回path.getUsableSpace();
}
最终体statfs统计=新体statfs(path.getPath());
返回(长)stats.getBlockSize()*(长)stats.getAvailableBlocks();
}/ **
*找到该片段的现有实例,或者如果没有找到,创建和
*使用FragmentManager添加。
*
* @参数调频FragmentManager管理器使用。
* @返回片段或新的实例,如果只是在现有实例
*创建。
* /
私有静态RetainFragment findOrCreateRetainFragment(FragmentManager FM){
//检查是否我们保留了工人的片段。
RetainFragment mRetainFragment =(RetainFragment)fm.findFragmentByTag(TAG); //如果不保留(或第一次运行),我们需要创建并添加它。
如果(mRetainFragment == NULL){
mRetainFragment =新RetainFragment();
。fm.beginTransaction()加(mRetainFragment,TAG).commitAllowingStateLoss();
} 返回mRetainFragment;
}/ **
*存储一个对象,并保留在配置一个简单的非UI片段
*变化。它将被用于保持ImageCache对象。
* /
公共静态类RetainFragment扩展片段{
私有对象mObject; / **
*空构造函数按照文档片段
* /
公共RetainFragment(){} @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState); //确保这个片段被保留在配置变化
setRetainInstance(真);
} / **
*存放在这个片段中单个对象。
*
* @参数对象的对象存储
* /
公共无效的setObject(Object对象){
mObject =对象;
} / **
*获取存储的对象。
*
返回:存储的对象
* /
公共对象的getObject(){
返回mObject;
}
}}
这是谷歌开发者控制台
堆栈跟踪 了java.lang.RuntimeException:无法启动活动ComponentInfo {com.minecraftpix / com.minecraftpix.pics.ImageGridActivity}:显示java.lang.NullPointerException
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
在android.app.ActivityThread.access $ 2300(ActivityThread.java:125)
在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2033)
在android.os.Handler.dispatchMessage(Handler.java:99)
在android.os.Looper.loop(Looper.java:123)
在android.app.ActivityThread.main(ActivityThread.java:4627)
在java.lang.reflect.Method.invokeNative(本机方法)
在java.lang.reflect.Method.invoke(Method.java:521)
在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:858)
在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
在dalvik.system.NativeStart.main(本机方法)
显示java.lang.NullPointerException:产生的原因
在com.minecraftpix.android.bitmapfun.util.ImageCache.getDiskCacheDir(ImageCache.java:514)
在com.minecraftpix.android.bitmapfun.util.ImageCache$ImageCacheParams.<init>(ImageCache.java:463)
在com.minecraftpix.pics.ImageGridFragment.onCreate(ImageGridFragment.java:80)
在android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
在android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
在android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1131)
在android.app.Activity.performStart(Activity.java:3781)
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2636)
... 11更多
这
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())||
!isExternalStorageRemovable()?
getExternalCacheDir(上下文).getPath():context.getCacheDir()的getPath();
是犯罪嫌疑人,!isExternalStorageRemovable()
检查覆盖 MEDIA_MOUNTED
检查。仅仅因为外部存储设备是不可拆卸的,并不意味着它不能被卸载。例如,在老版本的Android,默认行为是挂载外部存储的主机上的USB大容量存储。这将其卸载,并使其无法使用你的应用程序,无论存储介质可以被物理删除或没有。
在外部存储是不可拆卸的,但没有安装的情况下, getExternalCacheDir()
将返回null。
这是假设背景
非空也。
The images will not cache on internal storage and crashes on devices without an External SD Card. I have tried what I know and nothing worked. Here is the ImageCache.java
package com.minecraftpix.android.bitmapfun.util;
import com.minecraftpix.BuildConfig;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import android.util.Log;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Iterator;
public class ImageCache {
private static final String TAG = "ImageCache";
// Default memory cache size in kilobytes
private static final int DEFAULT_MEM_CACHE_SIZE = 1024 * 5; // 5MB
// Default disk cache size in bytes
private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
// Compression settings when writing images to disk cache
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
private static final int DEFAULT_COMPRESS_QUALITY = 70;
private static final int DISK_CACHE_INDEX = 0;
// Constants to easily toggle various caches
private static final boolean DEFAULT_MEM_CACHE_ENABLED = true;
private static final boolean DEFAULT_DISK_CACHE_ENABLED = true;
private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false;
private DiskLruCache mDiskLruCache;
private LruCache<String, BitmapDrawable> mMemoryCache;
private ImageCacheParams mCacheParams;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;
private HashSet<SoftReference<Bitmap>> mReusableBitmaps;
/**
* Create a new ImageCache object using the specified parameters. This should not be
* called directly by other classes, instead use
* {@link ImageCache#getInstance(FragmentManager, ImageCacheParams)} to fetch an ImageCache
* instance.
*
* @param cacheParams The cache parameters to use to initialize the cache
*/
private ImageCache(ImageCacheParams cacheParams) {
init(cacheParams);
}
/**
* Return an {@link ImageCache} instance. A {@link RetainFragment} is used to retain the
* ImageCache object across configuration changes such as a change in device orientation.
*
* @param fragmentManager The fragment manager to use when dealing with the retained fragment.
* @param cacheParams The cache parameters to use if the ImageCache needs instantiation.
* @return An existing retained ImageCache object or a new one if one did not exist
*/
public static ImageCache getInstance(
FragmentManager fragmentManager, ImageCacheParams cacheParams) {
// Search for, or create an instance of the non-UI RetainFragment
final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager);
// See if we already have an ImageCache stored in RetainFragment
ImageCache imageCache = (ImageCache) mRetainFragment.getObject();
// No existing ImageCache, create one and store it in RetainFragment
if (imageCache == null) {
imageCache = new ImageCache(cacheParams);
mRetainFragment.setObject(imageCache);
}
return imageCache;
}
/**
* Initialize the cache, providing all parameters.
*
* @param cacheParams The cache parameters to initialize the cache
*/
private void init(ImageCacheParams cacheParams) {
mCacheParams = cacheParams;
// Set up memory cache
if (mCacheParams.memoryCacheEnabled) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
}
// If we're running on Honeycomb or newer, then
if (Utils.hasHoneycomb()) {
mReusableBitmaps = new HashSet<SoftReference<Bitmap>>();
}
mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {
/**
* Notify the removed entry that is no longer being cached
*/
@Override
protected void entryRemoved(boolean evicted, String key,
BitmapDrawable oldValue, BitmapDrawable newValue) {
if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
// The removed entry is a recycling drawable, so notify it
// that it has been removed from the memory cache
((RecyclingBitmapDrawable) oldValue).setIsCached(false);
} else {
// The removed entry is a standard BitmapDrawable
if (Utils.hasHoneycomb()) {
// We're running on Honeycomb or later, so add the bitmap
// to a SoftRefrence set for possible use with inBitmap later
mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
}
}
}
/**
* Measure item size in kilobytes rather than units which is more practical
* for a bitmap cache
*/
@Override
protected int sizeOf(String key, BitmapDrawable value) {
final int bitmapSize = getBitmapSize(value) / 1024;
return bitmapSize == 0 ? 1 : bitmapSize;
}
};
}
// By default the disk cache is not initialized here as it should be initialized
// on a separate thread due to disk access.
if (cacheParams.initDiskCacheOnCreate) {
// Set up disk cache
initDiskCache();
}
}
/**
* Initializes the disk cache. Note that this includes disk access so this should not be
* executed on the main/UI thread. By default an ImageCache does not initialize the disk
* cache when it is created, instead you should call initDiskCache() to initialize it on a
* background thread.
*/
public void initDiskCache() {
// Set up disk cache
synchronized (mDiskCacheLock) {
if (mDiskLruCache == null || mDiskLruCache.isClosed()) {
File diskCacheDir = mCacheParams.diskCacheDir;
if (mCacheParams.diskCacheEnabled && diskCacheDir != null) {
if (!diskCacheDir.exists()) {
diskCacheDir.mkdirs();
}
if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) {
try {
mDiskLruCache = DiskLruCache.open(
diskCacheDir, 1, 1, mCacheParams.diskCacheSize);
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache initialized");
}
} catch (final IOException e) {
mCacheParams.diskCacheDir = null;
Log.e(TAG, "initDiskCache - " + e);
}
}
}
}
mDiskCacheStarting = false;
mDiskCacheLock.notifyAll();
}
}
/**
* Adds a bitmap to both memory and disk cache.
* @param data Unique identifier for the bitmap to store
* @param value The bitmap drawable to store
*/
public void addBitmapToCache(String data, BitmapDrawable value) {
if (data == null || value == null) {
return;
}
// Add to memory cache
if (mMemoryCache != null) {
if (RecyclingBitmapDrawable.class.isInstance(value)) {
// The removed entry is a recycling drawable, so notify it
// that it has been added into the memory cache
((RecyclingBitmapDrawable) value).setIsCached(true);
}
mMemoryCache.put(data, value);
}
synchronized (mDiskCacheLock) {
// Add to disk cache
if (mDiskLruCache != null) {
final String key = hashKeyForDisk(data);
OutputStream out = null;
try {
DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot == null) {
final DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if (editor != null) {
out = editor.newOutputStream(DISK_CACHE_INDEX);
value.getBitmap().compress(
mCacheParams.compressFormat, mCacheParams.compressQuality, out);
editor.commit();
out.close();
}
} else {
snapshot.getInputStream(DISK_CACHE_INDEX).close();
}
} catch (final IOException e) {
Log.e(TAG, "addBitmapToCache - " + e);
} catch (Exception e) {
Log.e(TAG, "addBitmapToCache - " + e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {}
}
}
}
}
/**
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap drawable if found in cache, null otherwise
*/
public BitmapDrawable getBitmapFromMemCache(String data) {
BitmapDrawable memValue = null;
if (mMemoryCache != null) {
memValue = mMemoryCache.get(data);
}
if (BuildConfig.DEBUG && memValue != null) {
Log.d(TAG, "Memory cache hit");
}
return memValue;
}
/**
* Get from disk cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromDiskCache(String data) {
final String key = hashKeyForDisk(data);
Bitmap bitmap = null;
synchronized (mDiskCacheLock) {
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mDiskLruCache != null) {
InputStream inputStream = null;
try {
final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot != null) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache hit");
}
inputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
if (inputStream != null) {
FileDescriptor fd = ((FileInputStream) inputStream).getFD();
// Decode bitmap, but we don't want to sample so give
// MAX_VALUE as the target dimensions
bitmap = ImageResizer.decodeSampledBitmapFromDescriptor(
fd, Integer.MAX_VALUE, Integer.MAX_VALUE, this);
}
}
} catch (final IOException e) {
Log.e(TAG, "getBitmapFromDiskCache - " + e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {}
}
}
return bitmap;
}
}
/**
* @param options - BitmapFactory.Options with out* options populated
* @return Bitmap that case be used for inBitmap
*/
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
Bitmap bitmap = null;
if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
final Iterator<SoftReference<Bitmap>> iterator = mReusableBitmaps.iterator();
Bitmap item;
while (iterator.hasNext()) {
item = iterator.next().get();
if (null != item && item.isMutable()) {
// Check to see it the item can be used for inBitmap
if (canUseForInBitmap(item, options)) {
bitmap = item;
// Remove from reusable set so it can't be used again
iterator.remove();
break;
}
} else {
// Remove from the set if the reference has been cleared.
iterator.remove();
}
}
}
return bitmap;
}
/**
* Clears both the memory and disk cache associated with this ImageCache object. Note that
* this includes disk access so this should not be executed on the main/UI thread.
*/
public void clearCache() {
if (mMemoryCache != null) {
mMemoryCache.evictAll();
if (BuildConfig.DEBUG) {
Log.d(TAG, "Memory cache cleared");
}
}
synchronized (mDiskCacheLock) {
mDiskCacheStarting = true;
if (mDiskLruCache != null && !mDiskLruCache.isClosed()) {
try {
mDiskLruCache.delete();
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache cleared");
}
} catch (IOException e) {
Log.e(TAG, "clearCache - " + e);
}
mDiskLruCache = null;
initDiskCache();
}
}
}
/**
* Flushes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void flush() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
mDiskLruCache.flush();
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache flushed");
}
} catch (IOException e) {
Log.e(TAG, "flush - " + e);
}
}
}
}
/**
* Closes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void close() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
if (!mDiskLruCache.isClosed()) {
mDiskLruCache.close();
mDiskLruCache = null;
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache closed");
}
}
} catch (IOException e) {
Log.e(TAG, "close - " + e);
}
}
}
}
/**
* A holder class that contains cache parameters.
*/
public static class ImageCacheParams {
public int memCacheSize = DEFAULT_MEM_CACHE_SIZE;
public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE;
public File diskCacheDir;
public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
public int compressQuality = DEFAULT_COMPRESS_QUALITY;
public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;
public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED;
public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE;
/**
* Create a set of image cache parameters that can be provided to
* {@link ImageCache#getInstance(FragmentManager, ImageCacheParams)} or
* {@link ImageWorker#addImageCache(FragmentManager, ImageCacheParams)}.
* @param context A context to use.
* @param diskCacheDirectoryName A unique subdirectory name that will be appended to the
* application cache directory. Usually "cache" or "images"
* is sufficient.
*/
public ImageCacheParams(Context context, String diskCacheDirectoryName) {
diskCacheDir = getDiskCacheDir(context, diskCacheDirectoryName);
}
/**
* Sets the memory cache size based on a percentage of the max available VM memory.
* Eg. setting percent to 0.2 would set the memory cache to one fifth of the available
* memory. Throws {@link IllegalArgumentException} if percent is < 0.05 or > .8.
* memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed
* to construct a LruCache which takes an int in its constructor.
*
* This value should be chosen carefully based on a number of factors
* Refer to the corresponding Android Training class for more discussion:
* http://developer.android.com/training/displaying-bitmaps/
*
* @param percent Percent of available app memory to use to size memory cache
*/
public void setMemCacheSizePercent(float percent) {
if (percent < 0.05f || percent > 0.8f) {
throw new IllegalArgumentException("setMemCacheSizePercent - percent must be "
+ "between 0.05 and 0.8 (inclusive)");
}
memCacheSize = Math.round(percent * Runtime.getRuntime().maxMemory() / 1024);
}
}
/**
* @param candidate - Bitmap to check
* @param targetOptions - Options that have the out* value populated
* @return true if <code>candidate</code> can be used for inBitmap re-use with
* <code>targetOptions</code>
*/
private static boolean canUseForInBitmap(
Bitmap candidate, BitmapFactory.Options targetOptions) {
int width = targetOptions.outWidth / targetOptions.inSampleSize;
int height = targetOptions.outHeight / targetOptions.inSampleSize;
return candidate.getWidth() == width && candidate.getHeight() == height;
}
/**
* Get a usable cache directory (external if available, internal otherwise).
*
* @param context The context to use
* @param uniqueName A unique directory name to append to the cache dir
* @return The cache dir
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable for using as a
* disk filename.
*/
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* Get the size in bytes of a bitmap in a BitmapDrawable.
* @param value
* @return size in bytes
*/
@TargetApi(12)
public static int getBitmapSize(BitmapDrawable value) {
Bitmap bitmap = value.getBitmap();
if (Utils.hasHoneycombMR1()) {
return bitmap.getByteCount();
}
// Pre HC-MR1
return bitmap.getRowBytes() * bitmap.getHeight();
}
/**
* Check if external storage is built-in or removable.
*
* @return True if external storage is removable (like an SD card), false
* otherwise.
*/
@TargetApi(9)
public static boolean isExternalStorageRemovable() {
if (Utils.hasGingerbread()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
/**
* Get the external app cache directory.
*
* @param context The context to use
* @return The external cache dir
*/
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
if (Utils.hasFroyo()) {
return context.getExternalCacheDir();
}
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}
/**
* Check how much usable space is available at a given path.
*
* @param path The path to check
* @return The space available in bytes
*/
@TargetApi(9)
public static long getUsableSpace(File path) {
if (Utils.hasGingerbread()) {
return path.getUsableSpace();
}
final StatFs stats = new StatFs(path.getPath());
return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
/**
* Locate an existing instance of this Fragment or if not found, create and
* add it using FragmentManager.
*
* @param fm The FragmentManager manager to use.
* @return The existing instance of the Fragment or the new instance if just
* created.
*/
private static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
// Check to see if we have retained the worker fragment.
RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(TAG);
// If not retained (or first time running), we need to create and add it.
if (mRetainFragment == null) {
mRetainFragment = new RetainFragment();
fm.beginTransaction().add(mRetainFragment, TAG).commitAllowingStateLoss();
}
return mRetainFragment;
}
/**
* A simple non-UI Fragment that stores a single Object and is retained over configuration
* changes. It will be used to retain the ImageCache object.
*/
public static class RetainFragment extends Fragment {
private Object mObject;
/**
* Empty constructor as per the Fragment documentation
*/
public RetainFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this Fragment.
*
* @param object The object to store
*/
public void setObject(Object object) {
mObject = object;
}
/**
* Get the stored object.
*
* @return The stored object
*/
public Object getObject() {
return mObject;
}
}
}
And here is the stack trace from Google Developer Console
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.minecraftpix/com.minecraftpix.pics.ImageGridActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.minecraftpix.android.bitmapfun.util.ImageCache.getDiskCacheDir(ImageCache.java:514)
at com.minecraftpix.android.bitmapfun.util.ImageCache$ImageCacheParams.<init>(ImageCache.java:463)
at com.minecraftpix.pics.ImageGridFragment.onCreate(ImageGridFragment.java:80)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1131)
at android.app.Activity.performStart(Activity.java:3781)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2636)
... 11 more
This:
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!isExternalStorageRemovable() ?
getExternalCacheDir(context).getPath() : context.getCacheDir().getPath();
is suspect, the !isExternalStorageRemovable()
check overrides the MEDIA_MOUNTED
check. Just because external storage is not removable, does not mean it cannot be unmounted. For example, on older versions of android, the default behavior was to mount the external storage as USB mass storage on the host computer. This would unmount it and make it unavailable to your application, regardless of whether the storage media could be physically removed or not.
In the case that external storage was not removable, yet not mounted, getExternalCacheDir()
will return null.
This is assuming that context
is non-null as well.
这篇关于位图缓存外部无SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!