2013-06-05 39 views
8

我使用通用图像加载器在列表视图中显示我的应用程序中的图像。我正在使用UnlimitedDiscCache,因为根据文档,这是最快的缓存机制。通用图像加载器 - 手动清除缓存

但是,我想在应用程序关闭时清除光盘缓存(例如在onStop()中),但只应删除超过给定限制的最旧缓存文件(如TotalSizeLimitedDiscCache)。

我知道ImageLoader.clearDiscCache()但对我来说这一点,因为我之前使用UnlimitedDiscCache清除缓存完整...

所以我希望能有最快的缓存机制,当用户加载和滚动列表视图并在用户不再与应用程序交互时清除缓存缓存。

任何想法,我可以如何实现这一点?

+0

当调用'onStop()'时,您无法保证应用程序正在停止。这只表示当前活动正在停止。与执行另一个缓存机制所花费的时间相比,性能损失非常小(这可能会降低应用的速度)。 –

+0

@jeff_bordon您是否有任何用于构建ImageLoader实例的代码? @Androidy是的,你可以区分应用即将完成,比如'if(isFinishing()){do something}' –

+0

@jeff_bordon你可以拥有BoB(两者中最好的)。在这里查看源代码https://github.com/nostra13/Android-Universal-Image-Loader/blob/master/library/src/com/nostra13/universalimageloader/cache/disc/impl/LimitedAgeDiscCache.java Writing UnlimitedAgeDiskCache将会非常直截了当。所有你必须知道的是现在和之后的日期和区别。我认为它不会降低ListViews的速度,如果它是很少ifs的话。 –

回答

1

检查这从这里https://stackoverflow.com/a/7763725/1023248可以帮助你..

@Override 
protected void onDestroy() { 
// closing Entire Application 
android.os.Process.killProcess(android.os.Process.myPid()); 
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit(); 
editor.clear(); 
editor.commit(); 
trimCache(this); 
super.onDestroy(); 
} 


public static void trimCache(Context context) { 
try { 
    File dir = context.getCacheDir(); 
    if (dir != null && dir.isDirectory()) { 
     deleteDir(dir); 

    } 
} catch (Exception e) { 
    // TODO: handle exception 
} 
} 


public static boolean deleteDir(File dir) { 
if (dir != null && dir.isDirectory()) { 
    String[] children = dir.list(); 
    for (int i = 0; i < children.length; i++) { 
     boolean success = deleteDir(new File(dir, children[i])); 
     if (!success) { 
      return false; 
     } 
    } 
} 

// <uses-permission 
// android:name="android.permission.CLEAR_APP_CACHE"></uses-permission> 
// The directory is now empty so delete it 

return dir.delete(); 
} 
0

如果你想从内存中清除缓存,可以使用下面的代码:

MemoryCacheUtils.removeFromCache(imageUri, ImageLoader.getInstance().getMemoryCache()); 

如果你也想要清除磁盘中的缓存,可以使用以下代码:

DiscCacheUtils.removeFromCache(imageUri, ImageLoader.getInstance().getDiscCache()); 

这是一种更简单的方法o f清除缓存。 您可以在此线程找到类似的答案:

How to force a cache clearing using Universal Image Loader Android?

我希望这个信息是有益的。 :)