android - Glide - 如何在runnable中获取位图

标签 android android-glide

我想使用 glide 将我的图像加载到位图中,但它引发了错误

java.lang.IllegalArgumentException: You must call this method on a background thread at com.bumptech.glide.util.Util.assertBackgroundThread(Util.java:141) at com.bumptech.glide.request.RequestFutureTarget.doGet(RequestFutureTarget.java:186) at com.bumptech.glide.request.RequestFutureTarget.get(RequestFutureTarget.java:108) at 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;
        }

最佳答案

@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();
  }

关于android - Glide - 如何在runnable中获取位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51899091/

相关文章:

android - 在 Android 中实现支持向量机

Android Glide : Show a blurred image before loading actual image

android - 使用 Glide 在 MenuItem 中加载远程图像

php - Android:如何使用php在mysql中上传图像

java - Android - 如果内部类是服务,GC 会收集我的外部类吗?

android - 无法让 dokka 在 gradle/android 项目上生成 kotlin 文档

android - 使用 Android Studio (0.8.14) 创建独立的 android 库项目

android - Glide,当缓存大小大于 50 MB 时清除缓存

android - 使用 Glide 库设置完成图像加载后进度条的可见性

android - Glide如何异步加载图片?