1

I am writing an Android app where I want to display a consistent stream using the newest Glide 4.11.0. My idea was that I display every 100 ms a new image using a for loop where I call the Glide function. When I start my function loadImageFromURL() it runs through and afterwards display all the images as fast as possible after each other, but I want to get it displayed evenly with a time gap of around 100 ms.

What am I doing wrong? Is there a problem with an internal thread of Glide?

My Code:

public void loadImageFromURL() {
        Glide.get(this).setMemoryCategory(MemoryCategory.HIGH); //use more RAM than normal
        final long Start = System.currentTimeMillis();

        for (int i = 0; i < 5; imageNumber++) {         //for loop for displaying continuously stream
            if (System.currentTimeMillis() > Start + i * 100) {
                Glide.with(this).asBitmap().load(ImageURL).diskCacheStrategy(DiskCacheStrategy.NONE).override(ScreenSizeX, ScreenSizeY).into(new CustomTarget<Bitmap>(){
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        _imageView.setImageBitmap(resource);
                        imageNumber++;
                    }
                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
                i++;
            }
        }
    Glide.get(this).setMemoryCategory(MemoryCategory.NORMAL); //RAM usage back to normal
    }
Zoe
  • 27,060
  • 21
  • 118
  • 148
ChristianYami
  • 586
  • 1
  • 9
  • 17

1 Answers1

1

There are multiple flaws with your code. Glide downloads the images in a separate thread, so it's running the download code independently from your loop. Some issues:

  1. You are manipulating imageNumber from multiple threads. This will cause random time-sensitive issues. You should not increment imageNumber in onResourceReady
  2. The loop will just infinitely loop until the desired time is reached. This will cause heavy CPU load and can be solved by using locks, waits or similar.

My suggestion: Try loading each image after another synchronously with the solution from this answer. When an image has loaded, calculate how much time remains for your "image load break" to pass and use Thread.sleep(milliSeconds) to wait out the remaining time. Then you can update the imageView.

Make sure you run this code in a separate thread and use runOnUIThread when updating the imageView.

You can probably further optimize this by using a ConcurrentQueue where the download of the images all happen at once and a separate consumer thread takes from the queue and waits in between. This will probably have higher memory usage though because the images will be also stored in the queue.

JensV
  • 3,997
  • 2
  • 19
  • 43