gpt4 book ai didi

java - Picasso - 自定义 RequestHandler 不会在磁盘上缓存图像

转载 作者:搜寻专家 更新时间:2023-11-01 07:54:49 31 4
gpt4 key购买 nike

我需要从某些服务加载和缓存图像。例如,没有这样的服务,但它显示了我想要实现的目标。

我的问题是图像没有缓存在磁盘上。没有通常的文件夹/data/data/myapp/cache/picasso-cache。

如何从 RequestHandler 访问缓存。甚至有可能或者编写自定义下载器会更好?

请求处理程序

public class CustomRequestHandler extends RequestHandler {

private static final List<String> PATHS = Arrays.asList("http://somelink/someimage1.png",
"http://somelink/someimage2.png",
"http://somelink/someimage3.png");

private Iterator<String> pathIterator = PATHS.iterator();

@Override
public boolean canHandleRequest(Request data) {
return data.uri.toString().contains("custom");
}

@Override
public Result load(Request request, int networkPolicy) throws IOException {
if (!pathIterator.hasNext()) {
pathIterator = PATHS.iterator();
}

Bitmap bitmap = downloadFullFromUrl(pathIterator.next());
Result result = new Result(bitmap, Picasso.LoadedFrom.NETWORK);
return result;
}

private static Bitmap downloadFullFromUrl(String imageFullURL) {
Bitmap bm = null;
try {
URL url = new URL(imageFullURL);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bm = BitmapFactory.decodeByteArray(baf.toByteArray(), 0,
baf.toByteArray().length);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return bm;
}
}

用法:

Picasso picasso = Picasso.Builder(application)
.addRequestHandler(requestHandler)
.build();

picasso.load("custom").into(imageView);

最佳答案

正如@sashabelonogov 提到的,您需要将带有请求处理程序的 picasso 实例作为单例实例。我只是通过将它添加到我的应用程序类并在所有地方使用 Picasso.with(Context) 来做到这一点。

public class MyApplication extends Application {

public void onCreate() {
super.onCreate();
Picasso picasso = new Picasso.Builder(getApplicationContext())
.addRequestHandler(new MyRequestHandler())
.build();
Picasso.setSingletonInstance(picasso);
}
}

关于java - Picasso - 自定义 RequestHandler 不会在磁盘上缓存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29512008/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com