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.
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();
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();
}
}
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();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?