Android 无法在后台播放gif

Android 无法在后台播放gif,android,kotlin,gif,Android,Kotlin,Gif,我正在尝试在我的应用程序的背景中播放gif。我试过Glide,但我搞不清楚安装过程。我试图制作一个动画xml,但只能得到要显示的第一帧。目前正在尝试使用PlayGifView,但出现渲染错误,我的应用程序崩溃。如果有人对这些过程有更好的经验,请帮助我将其付诸实施。另外,请尽可能多地将代码保存在Kotlin中,因为我认为一些错误可能来自尝试从Java转换 PlayGiffiew package com.example.AppName import android.annotation.Suppr

我正在尝试在我的应用程序的背景中播放gif。我试过Glide,但我搞不清楚安装过程。我试图制作一个动画xml,但只能得到要显示的第一帧。目前正在尝试使用PlayGifView,但出现渲染错误,我的应用程序崩溃。如果有人对这些过程有更好的经验,请帮助我将其付诸实施。另外,请尽可能多地将代码保存在Kotlin中,因为我认为一些错误可能来自尝试从Java转换

PlayGiffiew

package com.example.AppName

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Movie
import android.os.SystemClock
import android.util.AttributeSet
import android.view.View

@Suppress("DEPRECATION")
class PlayGifView @SuppressLint("NewApi") constructor(context: Context?, attrs: AttributeSet?) :
View(context, attrs) {
private var mMovieResourceId = 0
private var mMovie: Movie? = null
private var mMovieStart: Long = 0
private var mCurrentAnimationTime = 0
fun setImageResource(mvId: Int) {
    mMovieResourceId = mvId
    mMovie = Movie.decodeStream(resources.openRawResource(mMovieResourceId))
    requestLayout()
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    if (mMovie != null) {
        setMeasuredDimension(mMovie!!.width(), mMovie!!.height())
    } else {
        setMeasuredDimension(suggestedMinimumWidth, suggestedMinimumHeight)
    }
}

override fun onDraw(canvas: Canvas) {
    if (mMovie != null) {
        updateAnimationTime()
        drawGif(canvas)
        invalidate()
    } else {
        drawGif(canvas)
    }
}

private fun updateAnimationTime() {
    val now = SystemClock.uptimeMillis()
    if (mMovieStart == 0L) {
        mMovieStart = now
    }
    var dur = mMovie!!.duration()
    if (dur == 0) {
        dur = DEFAULT_MOVIEW_DURATION
    }
    this.mCurrentAnimationTime = ((now - mMovieStart) % dur).toInt()
}

private fun drawGif(canvas: Canvas) {
    mMovie!!.setTime(mCurrentAnimationTime)
    mMovie!!.draw(canvas, 0f, 0f)
    canvas.restore()
}

companion object {
    private const val DEFAULT_MOVIEW_DURATION = 1000
}

init {
    setLayerType(LAYER_TYPE_SOFTWARE, null)
}
}
主要活动

val bgGif = findViewById<PlayGifView>(R.id.viewGif)
    bgGif.setImageResource(R.drawable.background_gif)
val bgGif=findviewbyd(R.id.viewGif)
bgGif.setImageResource(R.drawable.background\u gif)
XML布局

<com.example.AppName.PlayGifView
    android:id="@+id/viewGif"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_gravity="center"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />