Освободить ресурсы в PagerAdapter - PullRequest
0 голосов
/ 26 октября 2019

У меня есть PagerAdapter, и в instantiateItem я инициализирую ExoPlayer.

У меня вопрос, как мне выпустить плеер?

Я предполагаю, как-то функция *Должно быть задействовано 1007 *, но destroyItem только отображает вид как объект. Как я могу высвободить ресурсы, относящиеся к этому одному элементу PagerAdapter?

Здесь мой источник, если кому-то интересно:

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    [...]
        url.contains(mContext.getString(R.string.video_file_indicator)) -> {

            val exoPlayer = ExoPlayerFactory.newSimpleInstance(mContext)
            videoView.player = exoPlayer

            val dataSourceFactory : DataSource.Factory = DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext, mContext.getString(R.string.app_name)))
            var videoSource : MediaSource = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(url))
            if (url == Helper.getUserProfile().profileVideoUrl) {
                val localFile = File(mContext.getExternalFilesDir(null), Helper.profilePicVideoName)
                videoSource = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(localFile.toUri())                   
            }
            exoPlayer.prepare(videoSource)
            exoPlayer.playWhenReady = true
            exoPlayer.repeatMode = Player.REPEAT_MODE_ONE 
            videoView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
        }          
    }
    container.addView(layout)
    return layout
}

override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
    container.removeView(`object` as View)
}

1 Ответ

1 голос
/ 26 октября 2019

Вам не нужно возвращать View из метода instantiateItem(), вы также можете вернуть упаковщик, содержащий ваши ExoPlayer и ваши View.

например

data class Wrapper(val view: View, val player: ExoPlayer)

И в вашем PagerAdapter:

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    [...]
    return Wrapper(layout, exoPlayer)
}

override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
    val wrapper = `object` as Wrapper
    container.removeView(wrapper.view)
    // Release the player here.
    wrapper.player.doSomething()
}

Если вы хотите вместо этого вернуть представление из instantiateItem(), вы можете присвоить ExoPlayer в качестве тегачтобы получить его позже.

например

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    [...]
    return layout.apply {
        setTag(exoPlayer)
    }
}

override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
    val view = `object` as View
    container.removeView(view)
    // Release the player here.
    val exoPlayer = view.getTag() as ExoPlayer
    exoPlayer.doSomething()
}
...