在顯示圖像之前,我可以使用Picasso下載圖像嗎? 我想先緩存圖像。使用Android Picasso預加載圖像到內存/磁盤
示例場景: 用戶單擊按鈕,看到進度條,以及圖像何時完成加載,用戶在屏幕上查看圖像。
我試圖用「get」方法加載圖像,但沒有緩存圖像。
Thread thread = new Thread()
{
@Override
public void run() {
try {
Picasso picasso = PicassoOwnCache.with(getApplicationContext());
RequestCreator picassoRequest;
for (String imgUrl : imagesUrls) {
picassoRequest = picasso.load(imgUrl);
picassoRequest.get();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
這是我的畢加索單例類
public class PicassoOwnCache {
static Picasso singleton = null;
static Cache cache = null;
public static Picasso with(int cacheSize, Context context) {
if (singleton == null) {
int maxSize = calculateMemoryCacheSize(context);
cache = new LruCache(cacheSize <= maxSize ? cacheSize : maxSize);
singleton = new Picasso.Builder(context)
.memoryCache(cache)
.build();
}
return singleton;
}
public static Picasso with(Context context) {
if (singleton == null) {
cache = new LruCache(calculateMemoryCacheSize(context));
singleton = new Picasso.Builder(context)
.memoryCache(cache)
.build();
}
return singleton;
}
static int calculateMemoryCacheSize(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
int memoryClass = am.getMemoryClass();
if (largeHeap && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);
}
return 1024 * 1024 * memoryClass/10;//7;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class ActivityManagerHoneycomb {
static int getLargeMemoryClass(ActivityManager activityManager) {
return activityManager.getLargeMemoryClass();
}
}
}
下一個節目(緩存)圖像給用戶。
Picasso picasso = PicassoOwnCache.with(getApplicationContext());
picasso.setDebugging(true) ;
RequestCreator picassoRequest;
picassoRequest = picasso.load(imgUrl);
picassoRequest
.placeholder(R.drawable.loading_logo)
.error(R.drawable.no_internet)
.fit() // I tries also without fit()
.into(holder.getImageView());
不幸的是,這是行不通的。 謝謝你的yopur建議!
爲什麼不使用'fetch()'來代替? – dnkoutso
@dnkoutso fetch方法沒有返回任何內容,那麼我將如何獲取位圖? – AndroidDev
我沒有看到你在get()調用中返回的位圖。我強烈建議你在這裏使用'fetch()',讓畢加索爲你處理線程和請求合併。如果一個提取正在進行,並且有一個'into()',它將合併這兩個並傳遞它們。 – dnkoutso