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

How to get context and view in android lifecycleobserver?

我想把处理exoplayer into a lifecycleOberserver的代码放在class,但是要初始化一个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 中获取上下文和视图,但我找不到方法,有人可以帮助我吗?

您可以使用 activity 参数创建您的 lifeCycleObserver class 构造函数,例如

lifeCycleObserver(yourActivity param){
}

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