簡體   English   中英

在 PagerAdapter 中釋放資源

[英]Release resources in PagerAdapter

我有一個 PagerAdapter,並在instantiateItem中初始化一個ExoPlayer

我的問題是,如何釋放播放器?

我認為,應該以某種方式涉及 function destroyItem ,但destroyItem僅將視圖視為 object。 如何釋放特定於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)
}

您不需要從方法instantiateItem()返回View ,您還可以返回包含ExoPlayerView的包裝器。

例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM