所以我目前正在研究用 Picasso 库替换项目中大量自定义图像加载 AsyncTask
的可能性,这似乎很有希望。但是,有一个问题我不太确定如何使用 Picasso 解决。
在这种情况下,我们正在下载音乐轨道的专辑封面,但是当要显示我们的 ListView 时,我们只有轨道 ID。因此,首先我们必须根据轨道 ID 查找专辑封面 URL,然后将其加载到 ImageView 中。目前我们有一个 AsyncTask
,我们在 doInBackground()
中首先查找图像 URL,然后从中加载一个 Bitmap
,然后将其粘贴到onPostExecute
.
有没有什么方法可以使用 Picasso 进行这种预查找,或者我们是否必须将 Picasso 调用包装在首先执行查找的 AsyncTask
中(感觉有点违背目的)。
更新:现在如何运作:
private class AlbumArtTask extends AsyncTask<String, Bitmap, Bitmap> {
@Override
protected Bitmap doInBackground(String... strings) {
final String id = strings[0];
// This part is what I'm asking for, basically to be able to make an Async
// lookup of the url that will later be used by Picasso
final Uri uri = getAlbumArtUriFromTrackId(id);
// Creating the Bitmap and return it to be used in an ImageView
// This part is handled by Picasso
return bitmap = createBitmapFromUri(uri);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// load image into ImageView
}
}
更新 2:编造我所追求的例子
Picasso.with(mContext)
.load(new UriProvider() {
// Get the actual image URI here
public Uri getImageUri() {
return getAlbumArtUriFromTrackId(id);
}
})
// And load it here
.into(mImageView);
最佳答案
我必须为我的应用解决同样的问题。我使用 OkHTTP 拦截器来重定向请求。
这是我的 picassa 声明:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new PhotoInterceptor());
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(client))
.build();
这是拦截器的基本实现:
public class PhotoInterceptor implements Interceptor {
Gson gson = new Gson();
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.isSuccessful()) {
Photo photo = gson.fromJson(response.body().charStream(), Photo.class);
if (photo!=null) {
request = request.newBuilder()
.url(photo.getPhoto_file_url())
.build();
response = chain.proceed(request);
}
}
return response;
}
}
关于android - 加载前 picasso 图像 url 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30211183/