Bắt đầu với tiện ích IMA ExoPlayer

ExoPlayer là một trình phát nội dung nghe nhìn cấp ứng dụng dành cho Android. Hướng dẫn này cho biết cách bạn có thể sử dụng phần mở rộng ExoPlayer IMA (gói IMA DAI SDK) để yêu cầu và phát một luồng đa phương tiện có cả quảng cáo và nội dung.

Sau đây là một số lợi ích của tiện ích này:

  • Đơn giản hoá mã cần thiết để tích hợp IMA với các tính năng.
  • Giảm thời gian phát triển cần thiết để cập nhật lên các phiên bản mới của IMA.

Tiện ích ExoPlayer IMA hỗ trợ giao thức phát trực tiếp HLS và DASH. Sau đây là nội dung tóm tắt:

Hỗ trợ luồng mở rộng ExoPlayer-IMA
Sự kiện phát trực tiếp Luồng VOD
HLS (Phát trực tuyến dựa trên HTTP) Dấu kiểm Dấu kiểm
DASH (Truyền phát thích ứng động qua HTTP) Dấu kiểm Dấu kiểm

Luồng phát trực tiếp DASH được hỗ trợ trên ExoPlayer-IMA phiên bản 1.1.0 trở lên.

Hướng dẫn này dựa trên hướng dẫn về ExoPlayer và cho biết cách tạo một ứng dụng hoàn chỉnh và tích hợp tiện ích này. Hãy xem ExoPlayerExample trên GitHub để tham khảo ví dụ về một ứng dụng mẫu hoàn chỉnh.

Điều kiện tiên quyết

Tạo một dự án Android Studio mới

Để tạo dự án Android Studio, hãy hoàn tất các bước sau:

  • Khởi động Android Studio.
  • Chọn Start a new Android Studio project (Bắt đầu một dự án Android Studio mới).
  • Trong trang Choose your project (Chọn dự án), hãy chọn mẫu No Activity (Không có hoạt động).
  • Nhấp vào Tiếp theo.
  • Trong trang Định cấu hình dự án của bạn, hãy đặt tên cho dự án và chọn Java làm ngôn ngữ.

  • Nhấp vào Hoàn tất.

Thêm tiện ích IMA của ExoPlayer vào dự án

Thêm các lệnh nhập cho tiện ích vào tệp build.gradle cấp ứng dụng trong phần dependencies.

Định cấu hình ứng dụng và bật multidex. Điều này là cần thiết do kích thước của tiện ích và bắt buộc đối với các ứng dụng có minSdkVersion được đặt thành Android 4.4W (API cấp 20) trở xuống.

Ví dụ:

app/build.gradle

android {

  ...

  defaultConfig {
      applicationId "com.google.ads.interactivemedia.v3.samples.videoplayerapp"
      minSdkVersion 21
      targetSdkVersion 34
      multiDexEnabled true
      versionCode 1
      versionName "1.0"
  }

    ...
}
dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.media3:media3-ui:1.7.1'
    implementation 'androidx.media3:media3-exoplayer:1.7.1'
    implementation 'androidx.media3:media3-exoplayer-hls:1.7.1'
    implementation 'androidx.media3:media3-exoplayer-dash:1.7.1'

    // Adding the ExoPlayer IMA extension for ads will also include the IMA
    // SDK as a dependency.
    implementation 'androidx.media3:media3-exoplayer-ima:1.7.1'
}

Thêm các quyền của người dùng mà IMA DAI SDK yêu cầu để yêu cầu quảng cáo:

app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.project name">

    <!-- Required permissions for the IMA DAI SDK -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    ...

</manifest>

Thêm khai báo ý định

Nếu ứng dụng của bạn nhắm đến Android 11 (API cấp 30) trở lên, thì các phiên bản hiện tại và gần đây của IMA DAI SDK yêu cầu bạn khai báo rõ ràng ý định mở các đường liên kết trên web. Thêm đoạn mã sau vào tệp kê khai của ứng dụng để bật lượt nhấp qua quảng cáo (người dùng nhấp vào nút Tìm hiểu thêm).

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.project name">

      ...

    </application>

    <queries>
      <intent>
          <action android:name="android.intent.action.VIEW" />
          <data android:scheme="https" />
      </intent>
      <intent>
          <action android:name="android.intent.action.VIEW" />
          <data android:scheme="http" />
      </intent>
    </queries>
  </manifest>

Thiết lập giao diện người dùng của ExoPlayer

Tạo đối tượng PlayerView để ExoPlayer sử dụng.

Thay đổi androidx.constraintlayout.widget.ConstraintLayout thành LinearLayout. Đây là lựa chọn nên dùng cho tiện ích ExoPlayer IMA.

Ví dụ:

app/src/main/res/layout/activity_my.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/black"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MyActivity"
    tools:ignore="MergeRootFrame">

    <androidx.media3.ui.PlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Thêm thông số luồng phát

Hãy xem trang luồng mẫu IMA để biết các thành phần luồng mẫu nhằm kiểm thử dự án của bạn. Bạn cũng có thể xem mục Ad Manager trên DAI để biết thông tin về cách thiết lập luồng phát của riêng bạn.

Bước này minh hoạ cách thiết lập một sự kiện phát trực tiếp, nhưng tiện ích ExoPlayer IMA cũng hỗ trợ các luồng VOD DAI. Hãy xem bước dành cho luồng video theo yêu cầu (VOD) để biết những thay đổi mà ứng dụng của bạn cần xử lý luồng VOD.

Nhập tiện ích IMA của ExoPlayer

Thêm câu lệnh nhập cho tiện ích ExoPlayer.

Thêm các biến riêng tư sau vào MyActivity.java:

Thêm khoá thành phần của luồng HLS Big Buck Bunny (Live) để kiểm thử bằng luồng này. Bạn có thể kiểm thử thêm nhiều luồng trên trang luồng mẫu của IMA.

Tạo một hằng số KEY_ADS_LOADER_STATE để lưu và truy xuất trạng thái AdsLoader.

Ví dụ:

app/src/main/java/com/example/project name/MyActivity.java


import static androidx.media3.common.C.CONTENT_TYPE_HLS;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.media3.common.MediaItem;
import androidx.media3.common.util.Util;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.ima.ImaServerSideAdInsertionMediaSource;
import androidx.media3.exoplayer.ima.ImaServerSideAdInsertionUriBuilder;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.util.EventLogger;
import androidx.media3.ui.PlayerView;
import androidx.multidex.MultiDex;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;

...

public class MyActivity extends Activity {

  private static final String KEY_ADS_LOADER_STATE = "ads_loader_state";
  private static final String SAMPLE_ASSET_KEY = "c-rArva4ShKVIAkNfy6HUQ";

  private PlayerView playerView;
  private ExoPlayer player;
  private ImaSdkSettings imaSdkSettings;
  private ImaServerSideAdInsertionMediaSource.AdsLoader adsLoader;
  private ImaServerSideAdInsertionMediaSource.AdsLoader.State adsLoaderState;

}

Tạo một thực thể adsLoader

Ghi đè phương thức onCreate để tìm PlayerView và kiểm tra AdsLoader.State đã lưu. Bạn có thể dùng AdsLoader.State khi khởi tạo đối tượng adsLoader.

Ngoài ra, hãy bật multidex nếu số lượng phương thức và minSdkVersion của ứng dụng yêu cầu (như giải thích trong bước 2).

Ví dụ:

app/src/main/java/com/example/project name/MyActivity.java

...

public class MyActivity extends Activity {

  private static final String KEY_ADS_LOADER_STATE = "ads_loader_state";
  private static final String SAMPLE_ASSET_KEY = "c-rArva4ShKVIAkNfy6HUQ";

  private PlayerView playerView;
  private ExoPlayer player;
  private ImaSdkSettings imaSdkSettings;
  private ImaServerSideAdInsertionMediaSource.AdsLoader adsLoader;
  private ImaServerSideAdInsertionMediaSource.AdsLoader.State adsLoaderState;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    MultiDex.install(this);

    // Initialize the IMA SDK as early as possible when the app starts. If your app already
    // overrides Application.onCreate(), call this method inside the onCreate() method.
    // https://developer.android.com/topic/performance/vitals/launch-time#app-creation
    ImaSdkFactory.getInstance().initialize(this, getImaSdkSettings());

    playerView = findViewById(R.id.player_view);

    // Checks if there is a saved AdsLoader state to be used later when
    // initiating the AdsLoader.
    if (savedInstanceState != null) {
      Bundle adsLoaderStateBundle = savedInstanceState.getBundle(KEY_ADS_LOADER_STATE);
      if (adsLoaderStateBundle != null) {
        adsLoaderState =
            ImaServerSideAdInsertionMediaSource.AdsLoader.State.fromBundle(
                adsLoaderStateBundle);
      }
    }
  }

  private ImaSdkSettings getImaSdkSettings() {
    if (imaSdkSettings == null) {
      imaSdkSettings = ImaSdkFactory.getInstance().createImaSdkSettings();
      // Set any IMA SDK settings here.
    }
    return imaSdkSettings;
  }

}

Thêm các phương thức để khởi chạy trình phát

Thêm một phương thức để khởi chạy trình phát và làm như sau:

  • Tạo một thực thể AdsLoader.
  • Tạo ExoPlayer.
  • Tạo một MediaItem bằng khoá tài sản của sự kiện phát trực tiếp.
  • Đặt MediaItem cho trình phát của bạn.

Ví dụ:

app/src/main/java/com/example/project name/MyActivity.java

public class MyActivity extends Activity {

  ...

  
  // Create a server side ad insertion (SSAI) AdsLoader.
  private ImaServerSideAdInsertionMediaSource.AdsLoader createAdsLoader() {
    ImaServerSideAdInsertionMediaSource.AdsLoader.Builder adsLoaderBuilder =
        new ImaServerSideAdInsertionMediaSource.AdsLoader.Builder(this, playerView);

    // Attempt to set the AdsLoader state if available from a previous session.
    if (adsLoaderState != null) {
      adsLoaderBuilder.setAdsLoaderState(adsLoaderState);
    }

    return adsLoaderBuilder
        .setImaSdkSettings(getImaSdkSettings())
        .build();
  }

  private void initializePlayer() {
    adsLoader = createAdsLoader();

    // Set up the factory for media sources, passing the ads loader.
    DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);
    DefaultMediaSourceFactory mediaSourceFactory = new DefaultMediaSourceFactory(dataSourceFactory);

    // MediaSource.Factory to create the ad sources for the current player.
    ImaServerSideAdInsertionMediaSource.Factory adsMediaSourceFactory =
        new ImaServerSideAdInsertionMediaSource.Factory(adsLoader, mediaSourceFactory);

    // 'mediaSourceFactory' is an ExoPlayer component for the DefaultMediaSourceFactory.
    // 'adsMediaSourceFactory' is an ExoPlayer component for a MediaSource factory for IMA server
    // side inserted ad streams.
    mediaSourceFactory.setServerSideAdInsertionMediaSourceFactory(adsMediaSourceFactory);

    // Create an ExoPlayer and set it as the player for content and ads.
    player = new ExoPlayer.Builder(this).setMediaSourceFactory(mediaSourceFactory).build();
    playerView.setPlayer(player);
    adsLoader.setPlayer(player);

    // Build an IMA SSAI media item to prepare the player with.
    Uri ssaiLiveUri =
        new ImaServerSideAdInsertionUriBuilder()
            .setAssetKey(SAMPLE_ASSET_KEY)
            .setFormat(CONTENT_TYPE_HLS) // Use CONTENT_TYPE_DASH for dash streams.
            .build();

    // Create the MediaItem to play, specifying the stream URI.
    MediaItem ssaiMediaItem = MediaItem.fromUri(ssaiLiveUri);

    // Prepare the content and ad to be played with the ExoPlayer.
    player.setMediaItem(ssaiMediaItem);
    player.prepare();

    // Set PlayWhenReady. If true, content and ads will autoplay.
    player.setPlayWhenReady(false);
  }
}

Thêm phương thức để giải phóng trình phát

Thêm một phương thức để phát hành trình phát theo trình tự sau:

  • Đặt các tham chiếu của trình phát thành giá trị rỗng và giải phóng tài nguyên của trình phát.
  • Giải phóng trạng thái của adsLoader.

app/src/main/java/com/example/project name/MyActivity.java

public class MyActivity extends Activity {

  ...

  private void releasePlayer() {
    // Set the player references to null and release the player's resources.
    playerView.setPlayer(null);
    player.release();
    player = null;

    // Release the adsLoader state so that it can be initiated again.
    adsLoaderState = adsLoader.release();
  }

Xử lý sự kiện của trình phát

Cuối cùng, hãy tạo các lệnh gọi lại cho các sự kiện trong vòng đời của hoạt động để xử lý việc phát trực tuyến.

Để hỗ trợ SDK Android phiên bản 24 trở lên:

Để hỗ trợ các phiên bản SDK Android thấp hơn 24:

onStart()onResume() tương ứng với playerView.onResume(), còn onStop()onPause() tương ứng với playerView.onPause().

Bước này cũng sử dụng sự kiện onSaveInstanceState() để cố gắng lưu adsLoaderState.

app/src/main/java/com/example/project name/MyActivity.java

public class MyActivity extends Activity {

  ...

  @Override
  public void onStart() {
    super.onStart();
    if (Util.SDK_INT > 23) {
      initializePlayer();
      if (playerView != null) {
        playerView.onResume();
      }
    }
  }

  @Override
  public void onResume() {
    super.onResume();
    if (Util.SDK_INT <= 23 || player == null) {
      initializePlayer();
      if (playerView != null) {
        playerView.onResume();
      }
    }
  }

  @Override
  public void onPause() {
    super.onPause();
    if (Util.SDK_INT <= 23) {
      if (playerView != null) {
        playerView.onPause();
      }
      releasePlayer();
    }
  }

  @Override
  public void onStop() {
    super.onStop();
    if (Util.SDK_INT > 23) {
      if (playerView != null) {
        playerView.onPause();
      }
      releasePlayer();
    }
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    // Attempts to save the AdsLoader state to handle app backgrounding.
    if (adsLoaderState != null) {
      outState.putBundle(KEY_ADS_LOADER_STATE, adsLoaderState.toBundle());
    }
  }

  ...

}

Thiết lập luồng VOD (không bắt buộc)

Nếu ứng dụng của bạn bắt buộc phải phát nội dung VOD có quảng cáo, thì bạn cần làm như sau:

  1. Thêm CMS IDVideo ID cho luồng kiểm thử VOD.
  2. Tạo URI VOD SSAI bằng ImaServerSideAdInsertionUriBuilder().
  3. Sử dụng URI mới này làm mục nội dung nghe nhìn của trình phát.

app/src/main/java/com/example/project name/MyActivity.java

public class MyActivity extends Activity {

  private static final String KEY_ADS_LOADER_STATE = "ads_loader_state";
  private static final String SAMPLE_ASSET_KEY = "c-rArva4ShKVIAkNfy6HUQ";
  private static final String SAMPLE_CMS_ID = "2548831";
  private static final String SAMPLE_VIDEO_ID = "tears-of-steel";

  ...

  private void initializePlayer() {

     ...

    Uri ssaiVodUri =
        new ImaServerSideAdInsertionUriBuilder()
            .setContentSourceId(SAMPLE_CMS_ID)
            .setVideoId(SAMPLE_VIDEO_ID)
            .setFormat(CONTENT_TYPE_HLS)
            .build();

    // Create the MediaItem to play, specifying the stream URI.
    MediaItem ssaiMediaItem = MediaItem.fromUri(ssaiVodUri);

    // Prepare the content and ad to be played with the ExoPlayer.
    player.setMediaItem(ssaiMediaItem);
    player.prepare();

    // Set PlayWhenReady. If true, content and ads will autoplay.
    player.setPlayWhenReady(false);
  }

Vậy là xong! Giờ đây, bạn đang yêu cầu và phát một luồng nội dung nghe nhìn bằng tiện ích IMA của ExoPlayer. Hãy xem các mẫu DAI trên Android trên GitHub để biết mã hoàn chỉnh.