我有從服務器下載圖像或圖像集並顯示它們的功能。這部分工作正常,但我想將它們存儲在緩存中以使用應用程序保存用戶數據。從緩存中存儲和加載圖像,圖像將存儲但不會加載
我跟着this將緩存過程合併到我現有的函數中。
這是我imageload類:
package ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by paul on 15/08/2015.
*/
public class loadImage extends AsyncTask<String, String, Bitmap> {
private Bitmap bitmap = null;
private String type = "";
private ImageView imageView = null;
private ImageButton imageButton = null;
public int size = 0;
public boolean cache = true;
private Map<ImageButton, String> imageViewBtn;
private Map<ImageView, String> imageViewView;
private ExecutorService executorService;
private FileCache fileCache;
private MemoryCache memoryCache;
private String url = "";
public loadImage (String type, Object object, Context context){
memoryCache = new MemoryCache();
if(type.equalsIgnoreCase("imagebutton")){
imageButton = (ImageButton) object;
imageViewBtn = Collections.synchronizedMap(new WeakHashMap<ImageButton, String>());
} else {
imageView = (ImageView) object;
imageViewView = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
}
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//add loader as BG
}
@Override
protected Bitmap doInBackground(String... params) {
//check if cache is true
url = params[0];
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(url).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(size != 0){
image = Bitmap.createScaledBitmap(image, size, size, false);
}
if(type.equalsIgnoreCase("imagebutton")){
imageButton.setImageBitmap(image);
imageViewBtn.put(imageButton, url);
} else {
imageButton.setImageBitmap(image);
imageViewBtn.put(imageButton, url);
}
memoryCache.put(url,image);
}
public boolean cache(String url) {
bitmap = memoryCache.get(url);
if(bitmap != null) {
Log.d("CACHE", "Image loaded from cache");
if(type.equalsIgnoreCase("imagebutton")){
imageButton.setImageBitmap(bitmap);
} else {
imageButton.setImageBitmap(bitmap);
}
return true;
}
return false;
}
}
在我的日誌,它說的是,圖像被存儲在緩存中,但是當我在我的設備設置檢查緩存量永遠不會改變。我如何得到這個工作。
而且該類稱爲是這樣的:
//activity is the activity so ie login.this or whatever activity im currently in
ImageButton pp = (ImageButton) custom.findViewById(R.id.search_pp);
loadImage loadImage = new loadImage("imagebutton", pp, activity);
if (!loadImage.cache(thumb)) {
loadImage.execute(thumb);
}
尼斯畢加索電話,其現在只是1號線叫它 –
Picasso.with (活性).load(拇指).into(PP); –
@PaulLedger,請不要忘記選擇這個答案作爲正確答案,如果是這樣,tnx –