我想使用滑行将图像加载到位图中,但会引发错误
java.lang.IllegalArgumentException:您必须在后台线程上调用此方法 在com.bumptech.glide.util.Util.assertBackgroundThread(Util.java:141) 在com.bumptech.glide.request.RequestFutureTarget.doGet(RequestFutureTarget.java:186) 在com.bumptech.glide.request.RequestFutureTarget.get(RequestFutureTarget.java:108) 在extend.BitmapLoader.loadBitmapFromFile_Glide(BitmapLoader.java:60)
这是我的代码:
_runnable_animation = new Runnable() {
@Override
public void run() {
bm = get_bitmap();
}
};
_handler_animation.postDelayed(_runnable_animation, _RUNNABLE_THREAD_DELAY);
这是我的get_bitmap()方法:
try {
return Glide.with(context)
.asBitmap()
.load(new File(path))
.submit(500, 500)
.get();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
答案 0 :(得分:1)
我正在使用以下方法获取位图
public static void loadBitmapFromServer(Context context, String url, final OnBitmapLoadedListener callback) {
try {
Glide.with(context).load(url)
.asBitmap()
.priority(Priority.IMMEDIATE)
.listener(new RequestListener<String, Bitmap>() {
@Override
public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
// you can do whatever you want to do with Bitamp
callback.onBitmapLoaded(resource);
return false;
}
});
} catch (Exception e) {}
}
像这样声明接口
public interface OnBitmapLoadedListener {
void onBitmapLoaded(Bitmap resource);
}
答案 1 :(得分:0)
确保您像下面那样启动了新线程
mThread = new Thread(_runnable_animation);
mThread.start();
答案 2 :(得分:0)
@NJ答案足够好,但是如果您想让您的方法起作用,请创建后台线程处理程序而不是主线程处理程序。在这里,我修改了您的代码以使其正常工作。
HandlerThread bgThread = new HandlerThread("BitmapLoaderThread");
bgThread.start();
// initialize your _handler_animation like below
Handler _handler_animation = new Handler(bgThread.getLooper());
Runnable _runnable_animation = new Runnable() {
@Override
public void run() {
bm = get_bitmap();
}
};
_handler_animation.postDelayed(_runnable_animation, _RUNNABLE_THREAD_DELAY);
还要进行清理,更好的地方是Activity#onDestroy
@Override
public void onDestroy() {
_handler_animation.getLooper().quit();
super.onDestroy();
}
答案 3 :(得分:0)
您应该像这样全局定义位图变量:
Bitmap bitmap;
Glide.with(context).load(url)
.asBitmap()
.listener(new RequestListener<String, Bitmap>() {
@Override
public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
// After getting bitmap
bitmap = resource
return false;
}
});