javaandroidexoplayer

Issue with ExoPlayer


when i push the button to comeback to previous activity, exoplayer continue to playing sound. Why?

This is my code:

public class MainActivity extends AppCompatActivity {

    SimpleExoPlayerView exoPlayerView;
    SimpleExoPlayer exoPlayer;
    String videoURL = "myurl";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        exoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exo_player_view);
     try {


         BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
         TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
         exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);

         Uri videoURI = Uri.parse(videoURL);

         DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");
         ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
         MediaSource mediaSource = new ExtractorMediaSource(videoURI, dataSourceFactory, extractorsFactory, null, null);

         exoPlayerView.setPlayer(exoPlayer);
         exoPlayer.prepare(mediaSource);
         exoPlayer.setPlayWhenReady(true);
     }catch (Exception e){
         Log.e("MainAcvtivity"," exoplayer error "+ e.toString());
     }

    }
}

Any suggestion?


Solution

  • it is because you didn't release the resource. just use this code

    @Override
    public void onPause() {
    super.onPause();
    if (Util.SDK_INT <= 23) {
     exoPlayer.release();
    }
    
    }
    
    @Override
    public void onStop() {
    super.onStop();
    if (Util.SDK_INT > 23) {
       exoPlayer.release();
     }
    }