How to integrate ExoPlayer with other Android components?

Integrating ExoPlayer with other Android components enables you to create a seamless media playback experience. Below is a guide that outlines how to efficiently use ExoPlayer with activities, services, and view models.

Integrating ExoPlayer in an Activity

First, you'll want to integrate ExoPlayer into your activity. Here's a simple example:

// In your Activity ExoPlayer player = new ExoPlayer.Builder(context).build(); PlayerView playerView = findViewById(R.id.player_view); playerView.setPlayer(player); MediaItem mediaItem = MediaItem.fromUri("http://yourmediaurl.com/media.mp4"); player.setMediaItem(mediaItem); player.prepare(); player.play();

Using ExoPlayer in a Service

For background audio playback, you can utilize a Service:

public class PlaybackService extends Service { private ExoPlayer player; @Override public void onCreate() { super.onCreate(); player = new ExoPlayer.Builder(this).build(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { MediaItem mediaItem = MediaItem.fromUri("http://yourmediaurl.com/media.mp4"); player.setMediaItem(mediaItem); player.prepare(); player.play(); return START_NOT_STICKY; } @Override public void onDestroy() { player.release(); super.onDestroy(); } }

Integrating ExoPlayer with ViewModel

For lifecycle-aware handling, integrate with ViewModel:

public class PlayerViewModel extends ViewModel { private final ExoPlayer player; public PlayerViewModel(Application application) { player = new ExoPlayer.Builder(application).build(); } public void playMedia(String mediaUrl) { MediaItem mediaItem = MediaItem.fromUri(mediaUrl); player.setMediaItem(mediaItem); player.prepare(); player.play(); } @Override protected void onCleared() { player.release(); super.onCleared(); } }

ExoPlayer Android integration media playback Android components