I'm using Glide
to load animated GIF animation into ImageView
. It works as intended, looping indefinitely:
GlideApp.with(getContext())
.load(R.raw.my_gif_animation)
.into(this)
I want to add vibration every time the GIF animation cycle starts (or ends), but I couldn't find any callback, listener or frame counter, which I could use to learn when the animation cycle has started (or ended). Answers welcomed both in Java
and Kotlin
.
I found a solution to the problem, it turns out that we have access to frames of the GIF animation after the resource was loaded. Using this information inside a running Thread
, I was able not only to listen to the end/start of the animation but event to adjust very precisely the timing with respect to the frame of the animation.
Here is my working code in Kotlin
(in Java
it would be very similar):
GlideApp.with(getContext())
.asGif()
.load(R.raw. my_gif_animation)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.listener(object : RequestListener<GifDrawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any,
target: Target<GifDrawable>,
isFirstResource: Boolean
): Boolean {
return false
}
override fun onResourceReady(
resource: GifDrawable?,
model: Any,
target: Target<GifDrawable>,
dataSource: DataSource,
isFirstResource: Boolean
): Boolean {
myThread = Thread(Runnable {
while (true) {
if (resource?.isRunning == true) {
if (resource.frameIndex == 10).toInt()) {
// This code will be executed every time the 10th frame of the GIF animation is played..
}
if (Thread.interrupted()) break
}
}
})
myThread?.start()
return false
}
})
.into(this)