如何在android lifecycleobserver中获取上下文和视图?

时间:2019-11-12 06:52:55

标签: android lifecycle exoplayer

我想将处理exoplayer的代码放入lifecycleOberserver类中,但是要初始化exoplayer,我需要编写这样的代码

    void prepareExoPlayer(Context context, PlayerView exoPlayerView) {
        if (context == null || exoPlayerView == null) {
            return;
        }
        if (player == null) {
            TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory();
            TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
            player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
            DataSource.Factory dataSourceFactory =
                    new DefaultDataSourceFactory(
                            context,
                            Util.getUserAgent(
                                    context,
                                    context.getString(R.string.app_name)
                            )
                    );
            MediaSource videoSource = new ExtractorMediaSource
                    .Factory(dataSourceFactory)
                    .setExtractorsFactory(extractorsFactory)
                    .createMediaSource(videoUri);
            player.prepare(videoSource);
        }
        player.clearVideoSurface();
        player.setVideoSurfaceView((SurfaceView) exoPlayerView.getVideoSurfaceView());
        player.seekTo(player.getCurrentPosition() + 1);
        exoPlayerView.setPlayer(player);
    }

所以我必须在lifecycleOberserver中获取上下文并进行查看,但是我找不到解决方法,有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用活动参数使您的lifeCycleObserver类构造函数

lifeCycleObserver(yourActivity param){
}

然后将此参数用于上下文。