Playing videos from storage is a lot more simple than streaming video from the server. There are many tasks that need to handled while streaming video like adaptive playback, composition, caching, bandwidth control, etc. Streaming video with android low-level API like MediaPlayer is complex. Android Streaming Video With  ExoPlayer 2 provides a big set of customization. Worlds largest video sharing network YouTube, Facebook, PlayMovies also uses ExoPlayer. Furthermore, there are more than 140,000 applications making use of ExoPlayer. In this tutorial, we will develop a simple video streaming application with ExoPlayer.

Download Source Code and Application

Demo Video

Android Streaming Video With ExoPlayer 2 ( With IMA Ads) |

Android Streaming Video With ExoPlayer 2

Adding ExoPlayer Libray to Android Studio Project

Create a new android studio project or open existing project. Open Gradle Scripts -> build.gradle(Module App). Add ExoPlayer and IMA Extension dependency to your file as shown below.(Note: IAM Extension dependency is optional add it only if you want to show video ads in between your videos like YouTube)

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation ''
    implementation ''
    /*Add ExoPlayer Dependency Here*/
    implementation ''
    /* Optional IMA Extension Dependency If you want to show Video Ads
    in between Your videos Like Youtube */
    implementation ''

Creating Full-Screen Activity

While playing video users needs to get full advantage of the screen that’s why we need to create full-screen immersive activity. Create a new class Package Name -> add the following code to it.

public class VideoStreamingActivity extends AppCompatActivity {
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        public void run() {
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    private final Runnable mHideRunnable = new Runnable() {
        public void run() {

    protected void onCreate(Bundle savedInstanceState) {
        mContentView = findViewById(;

    protected void onPostCreate(Bundle savedInstanceState) {

    private void hide() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);

    private void delayedHide(int delayMillis) {
        mHideHandler.postDelayed(mHideRunnable, delayMillis);


Create new layout res->layout->activity_video_streaming.xml. This will be the layout for VideoStreamingActivity. Add the following lines to it

<FrameLayout xmlns:android=""

    <! – The primary full-screen view. This can be replaced with whatever view
         is needed to present your content, e.g. VideoView, SurfaceView,
         TextureView, etc. – >


Adding SimpleExoPlayerView To Layout

SimpleExoPlayerView is a component that provides predefined video player skin. This component contains the surface view, player controller, etc. open res -> layout -> activity_video_streaming.xml and paste following lines inside fullscreen_content  FrameLayout as shown below.

        <!--Add SimpleExoPlayerView Here – >
            app:resize_mode="fill" />

Creating Media Source 

ExoPlayer does not take directly Video Url as input it takes media source as its input. There are many types of media sources like ExtractorMediaSourceConcatenatingMediaSource(Used for playing playlist), HlsMediaSource(Used for Live Streaming), DashMediaSource, etc. For our application, we will create ExtractorMediaSource. Open Package Name -> . Add the following function to it.

private MediaSource createMediaSource(String videoUrl) {
        //Getting UserAgent
        String UserAgent = Util.getUserAgent(this, getString(R.string.app_name));
        //Creating Media Source
        MediaSource contentMediaSource = new ExtractorMediaSource(Uri.parse(videoUrl),
                new DefaultHttpDataSourceFactory(UserAgent),
                new DefaultExtractorsFactory(),
                null, null);
        //return media source
        return contentMediaSource;

Creating Media Source with Ads 

If you are creating quality video content. You want to earn something from it. Then ExoPlayer provides IMA extension. This extension provides video ads integration during video playback. If you want to create media source with ads then Open Package Name -> Add the following function to it.

private ImaAdsMediaSource createMediaSourceWithAds(String videoUrl, SimpleExoPlayerView exoPlayerView) {
        //Getting UserAgent
        String UserAgent = Util.getUserAgent(this, getString(R.string.app_name));
        // Creating  Video Content Media Source
        MediaSource contentMediaSource = new ExtractorMediaSource(Uri.parse(videoUrl),
                new DefaultHttpDataSourceFactory(UserAgent),
                new DefaultExtractorsFactory(), null, null);
        //Creating  Ima Ads Loader 
        ImaAdsLoader imaAdsLoader = new ImaAdsLoader(this, Uri.parse(getResources().getString(R.string.ad_tag_url)));
        //Creating Video Content Media Source With Ads
        ImaAdsMediaSource contentMediaSourceWithAds = new ImaAdsMediaSource(
                contentMediaSource,//Video Content Media Source
                new DefaultDataSourceFactory(this, UserAgent),
                exoPlayerView.getOverlayFrameLayout());//Overlay During Ads Playback
        //return media source with ads
        return contentMediaSourceWithAds;

Creating Video Player Configuration

Create new class for defining Video Player Configuration Package Name ->

public class VideoPlayerConfig {
    //Minimum Video you want to buffer while Playing
    public static final int MIN_BUFFER_DURATION = 25000;
    //Max Video you want to buffer during PlayBack
    public static final int MAX_BUFFER_DURATION = 30000;
    //Min Video you want to buffer before start Playing it
    public static final int MIN_PLAYBACK_START_BUFFER = 10000;
    //Min video You want to buffer when user resumes video
    public static final int MIN_PLAYBACK_RESUME_BUFFER = 10000;
    //Video Url
    public static final String VIDEO_URL = "";
  1. MIN_BUFFER_DURATION: Minimum Video you want to buffer while Playing
  2. MAX_BUFFER_DURATION: Max Video you want to buffer during PlayBack
  3. MIN_PLAYBACK_START_BUFFER: Min Video you want to buffer before start Playing it
  4. MIN_PLAYBACK_RESUME_BUFFER: Min video You want to buffer when user resumes video

Initializing ExoPlayer 

Now our Media Source and Video Player Configuration are ready. Define To initialize ExoPlayer create a new function initializePlayer() in Package Name -> Add the following lines to it.

//Define Field for SimpleExoPlayer
    SimpleExoPlayer player;

    private void initializePlayer() {
        //Biding xml view to exoPlayerView object
        SimpleExoPlayerView exoPlayerView = findViewById(;
        //Creating Load Control
        LoadControl loadControl = new DefaultLoadControl(
                new DefaultAllocator(true, 16),

        //Initializing ExoPlayer
        player = ExoPlayerFactory.newSimpleInstance(
                new DefaultRenderersFactory(this),
                new DefaultTrackSelector(),
        //binding exoPlayerView to SimpleExoPlayer
        //preparing player with media Source
        //Uncomment following line remove above line if you want to play Ads between Video
        //adding Listener to SimpleExoPlayer
        player.addListener(new Player.EventListener() {
            public void onTimelineChanged(Timeline timeline, Object manifest) {

            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {

            public void onLoadingChanged(boolean isLoading) {

            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                switch (playbackState) {
                    case Player.STATE_BUFFERING:
                        //Player is in state State buffering show some loading progress
                    case Player.STATE_READY:
                        //Player is ready to Play. Remove loading progress
                        // hideProgress();

            public void onRepeatModeChanged(int repeatMode) {

            public void onPlayerError(ExoPlaybackException error) {

            public void onPositionDiscontinuity() {

            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {


Managing Player with Activity Life Cycle

Now it is important to change player state during different activity lifecycle events like onPause(), onResume() and onDestroy() methods. Open Package Name -> add following lines to it.

/*   Activity Life Cycle*/
    protected void onResume() {

    protected void onPause() {

    protected void onDestroy() {


Open Package Name -> initialize player inside onCreate() Method

    protected void onCreate(Bundle savedInstanceState) {
        mContentView = findViewById(;
        mProgressBar = findViewById(;
        //initialize Player


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

   <uses-permission android:name="android.permission.INTERNET"/>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />



<?xml version="1.0" encoding="utf-8"?>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="black_overlay">#90000000</color>
    <color name="black">#000000</color>


right click res -> values folder and select New ->  Values resource file. Enter the name as attrs and press ok. Paste following lines in it.


    <! – Declare custom theme attributes that allow changing which styles are
         used for button bars depending on the API level.
         ?android:attr/buttonBarStyle is new as of API 11 so this is
         necessary to support previous API levels. – >
    <declare-styleable name="ButtonBarContainerTheme">
        <attr name="metaButtonBarStyle" format="reference" />
        <attr name="metaButtonBarButtonStyle" format="reference" />



add following strings to your res -> values -> strings.xml file.

    <string name="app_name">AndroidVideoStrammingSample</string>
    <string name="ad_tag_url"></string>
    <string name="title_activity_video_streaming">VideoStreamingActivity</string>


Add following styles to your res -> values -> styles.xml  file.

    <! – Base application theme. – >
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <! – Customize your theme here. – >
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

    <style name="FullscreenTheme" parent="AppTheme">
        <item name="android:actionBarStyle">@style/FullscreenActionBarStyle</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="metaButtonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>

    <style name="FullscreenActionBarStyle" parent="Widget.AppCompat.ActionBar">
        <item name="android:background">@color/black_overlay</item>


Running  Application 

Run the application and see the results.

Android Streaming Video With ExoPlayer 2 - Output Ads
Android Streaming Video With ExoPlayer 2 - Video

If you still have any queries, please post them in the comments section below, I will be happy to help you.


Hello there, My name is Amardeep founder of I have experience in many technologies like Android, Java, Php, etc. In this variety of technologies, I love Android App Development. If you have any idea and you want me to develop for you then let's have chat Conatct


  1. Vijay Kansala Reply

    Hi, I want to add my custom mp4 type ads to exoplayer, I dont have vast for these ads, how I can do that?

  2. when ever we are watching match at that time some ads come out on screen in side and bottom then automatically screen should be minimised . so… i want to play that type of ads in exoplayer , what i have to do for that could u please help me……

  3. Is it possible to play custom ads ? Ads which are basically from a url ??

  4. Suggest me how do i insert custom video ads (url like mp4 of 10 to 15 sec) in AdsLoader instead of IMA ads?

  5. hi
    is there any way to play IMA midroll and postroll ads with VAST.If possible then how?

  6. karan singh Reply

    how can i play video from url that i can change. Like setup firebase to load url in exoplayer.

  7. Hello sir,
    How can I play DASH URL with Widevine DRM protection? As from research, I was able to play only DASH URL using DashMediaSource but then I am not being able to URL which are Widevine DRM protected.

    Can you please help?

    • I don’t think so there is any other way to play DRM protected videos. You should do some research probably you will get something

  8. Kartikpathe Reply

    but How can I get My Ad code i.e.Google Ads Publisher Id for showing ads and earn some revenue

    • You should visit google DPF website their you can get to what things needs to be done in order to place video ads

  9. Mayank Langalia Reply

    Hello sir. I need small help. I want to add my custom advertisement is it possible or not ? Also i want to add advertisement indication (Yellow dot). Please help me Im stuck last few days.

  10. Hi,
    Can you help me to How I can change embedded subtitle and track in Hls?

  11. Hi Amardeep, Can you please tell me how I can listen to ads events such as adError(), adPaused(), adResumed() and adFinished()?
    I have been trying to do this for the past 2 days, still no result.
    I have this code which is playing the ads but I can not listen to ads events:
    MediaSource mediaSourceWithAds = new AdsMediaSource(

    • You can create adsmanager with that you can listen to events like adError(), adPaused(), adResumed() and adFinished()

  12. Vivek Shukla Reply

    Hii Sir I followed the process but the video didn’t streamed

      • Ìn VideoPlayerConfig.class change he URL from VIDEO_URL to public static final String VIDEO_URL = “”; it’s worksing with this url.

  13. Hi
    using the IMA Extension can we show ads in between the videos?

    • with SimpleExoPlayerView you cant’t set aspect ratio, instead you have to use surface view and there you can set aspect ratio

    • Yes for sure create hlsmedisource for m3u8 files it has several parameters as shown below
      HlsMediaSource(uri, mediaDataSourceFactory, mainHandler, null);

  14. Android Developer Reply

    Can we play Facebook or Vimeo video in this player? If yes, how can I do that?

    • Thanks for your question, Facebook and Vimeo don’t provide there media source URLs as per my knowledge. But maybe there is a way to get these Media Source URLs by using there API. Read there API and find a way to obtain Media Source URLs. If you find Media Source URL then it is easy to implement with ExoPlayer.

      // Creating  Video Content Media Source
              MediaSource contentMediaSource = new ExtractorMediaSource(Uri.parse(MEDIA_SOURCE_URL),
                      new DefaultHttpDataSourceFactory(UserAgent),
                      new DefaultExtractorsFactory(), null, null);

      Now Media Source is ready, pass it to play with ExoPlayer
      To start Playing Video

  15. Kalpesh Bhangare Reply

    Good Work, Sir How can I create a playlist of video or audio using ExoPlayer?

    • Thank You Mate, You can use ConcatenatingMediaSource. Refer this example to create PlayList of video or audio using ExoPlayer

       File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
          File file1 = new File(file,"file1.mp4");
          File file2 = new File(file,"file2.mp4");
          File file3 = new File(file,"file3.mp4");
          MediaSource firstSource = new ExtractorMediaSource(Uri.parse(file1.getAbsolutePath()),mediaDataSourceFactory,new DefaultExtractorsFactory(),
          MediaSource secondSource = new ExtractorMediaSource(Uri.parse(file2.getAbsolutePath()),mediaDataSourceFactory,new DefaultExtractorsFactory(),
          MediaSource thirdSource = new ExtractorMediaSource(Uri.parse(file3.getAbsolutePath()),mediaDataSourceFactory,new DefaultExtractorsFactory(),
          ConcatenatingMediaSource PlayListMediaSource= new ConcatenatingMediaSource(firstSource,secondSource,thirdSource);
        • I’m new to programming, could you show me how you put this list into this program? thank you

Write A Comment