In my app there is a recyclerview that with an exoplayer. When I leave my app or change the screen, the video keeps playing. I need to make it pause when I leave the screen.
I tried using the onViewRecycled method but the video is only paused when I return to the screen where the video is playing.
@Override
public void onViewRecycled(@NonNull MyViewHolder holder) {
super.onViewRecycled(holder);
if (holder.simpleExoPlayer != null) {
holder.positionExo = holder.simpleExoPlayer.getCurrentPosition();
holder.simpleExoPlayer.setPlayWhenReady(false);
}
}
My Adapter:
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//...
holder.simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(context);
// Bind the player to the view.
holder.videoCnt.setPlayer(holder.simpleExoPlayer);
holder.videoUri = Uri.parse(content.getVideo());
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, context.getString( R.string.app_name)));
// This is the MediaSource representing the media to be played.
MediaSource videoSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(holder.videoUri);
// Prepare the player with the source.
holder.simpleExoPlayer.prepare(videoSource);
//...
}
How to pause the video correctly?