滑行断言:java.lang.IllegalArgumentException:您必须在主线程上调用此方法 [英] Glide assert: java.lang.IllegalArgumentException: You must call this method on the main thread
问题描述
有人使用Glide从后台线程获取图像吗?我不断得到这个断言:
Has anyone used Glide to fetch images from a background thread? I keep getting this assert:
java.lang.IllegalArgumentException: You must call this method on the main thread
但是根据此线程,它应该可以工作:
but according to this thread, it should work:
https://github.com/bumptech/glide/issues/310
但是,除非我从主线程调用它,否则我无法使其正常工作.
Yet, I cannot get it to work, unless I call it from the main thread.
这是我要从主线程执行的操作:
Here's is what I am trying to do from the main thread:
Glide.get(mContext);
loadUserImage(userImageUrl);
// wait 5 seconds before trying again
int imageLoadingTimeOut = mContext.getResources().getInteger(R.integer.image_loading_time_out);
if (imageLoadingTimeOut > 0) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!mUserImageLoaded) {
loadUserImage(userImageUrl);
}
}
}, imageLoadingTimeOut);
}
}
和loadUserImage:
and the loadUserImage:
private boolean mUserImageLoaded = false;
private void loadUserImage(String userImageUrl) {
if (userImageUrl != null && !userImageUrl.isEmpty() && !mUserImageLoaded) {
Glide.with(mContext).using(Cloudinary.getUrlLoader(mContext)).load(userImageUrl).crossFade().listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
mImageMessageContent.invalidate();
mUserImageLoaded = true;
return false;
}
}).into(mImageMessageContent);
} else {
mImageMessageContent.setVisibility(View.GONE);
}
}
mContext只是活动"this"指针.
and mContext is just the activity "this" pointer.
无论如何,我可以从不同于main的线程中使用Glide吗?
Anyway, can I use Glide from a thread different than main?
推荐答案
Glide
的into(ImageView)
方法要求您仅在主线程上调用它,但是当您将加载传递给Timer时,它将在以下位置执行background
线程.
The into(ImageView)
method of Glide
requires you to call it only on main thread, but when you pass the loading to a Timer it will be executed in a background
thread.
您可以做的是通过调用get()
而不是into()
来检索位图,然后通过调用setImageBitmap()
在ImageView
上设置bitmap
.
What you can do is to retrieve a bitmap by calling get()
instead of into()
and then set that bitmap
on the ImageView
by calling setImageBitmap()
.
Glide.with(getApplicationContext())
.load("your url")
.asBitmap()
.into(new BitmapImageViewTarget(imgView) {
@Override
protected void setResource(Bitmap resource) {
//Play with bitmap
super.setResource(resource);
}
});
您还可以查看此文档了解更多信息.
You can also take a look at this document for more information.
这篇关于滑行断言:java.lang.IllegalArgumentException:您必须在主线程上调用此方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!