Bắt đầu sử dụng tiện ích IMA Exoplayer

SDK IMA giúp bạn dễ dàng tích hợp quảng cáo đa phương tiện vào trang web và ứng dụng của mình. SDK IMA có thể yêu cầu quảng cáo từ bất kỳ máy chủ quảng cáo tuân thủ VAST nào và quản lý việc phát quảng cáo trong ứng dụng của bạn. Với SDK phía máy khách IMA, bạn vẫn có quyền kiểm soát việc phát video nội dung, trong khi SDK xử lý việc phát quảng cáo. Quảng cáo phát trong một trình phát video riêng biệt nằm phía trên trình phát video nội dung của ứng dụng.

Hướng dẫn này minh hoạ cách tích hợp SDK IMA vào một dự án Android Studio trống bằng cách sử dụng tiện ích IMA ExoPlayer. Nếu bạn muốn xem hoặc làm theo một mẫu tích hợp hoàn chỉnh, hãy tải BasicExample xuống từ GitHub.

Tổng quan về phía máy khách IMA

Việc triển khai phía máy khách IMA bao gồm 4 thành phần SDK chính, được minh hoạ trong hướng dẫn này:

  • AdDisplayContainer: Một đối tượng vùng chứa chỉ định vị trí mà IMA hiển thị các phần tử giao diện người dùng của quảng cáo và đo lường khả năng xem, bao gồm cả Chế độ xem đang kích hoạtĐo lường mở.
  • AdsLoader: Một đối tượng yêu cầu quảng cáo và xử lý các sự kiện từ phản hồi yêu cầu quảng cáo. Bạn chỉ nên tạo một trình tải quảng cáo và có thể sử dụng lại trình tải này trong suốt thời gian hoạt động của ứng dụng.
  • AdsRequest: Một đối tượng xác định yêu cầu quảng cáo. Các yêu cầu về quảng cáo chỉ định URL cho thẻ quảng cáo VAST, cũng như các thông số bổ sung, chẳng hạn như kích thước quảng cáo.
  • AdsManager: Một đối tượng chứa phản hồi cho yêu cầu quảng cáo, kiểm soát việc phát quảng cáo và theo dõi các sự kiện quảng cáo do SDK kích hoạt.

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

Trước khi bắt đầu, bạn cần có Android Studio 3.0 trở lên.

1. 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:

  1. Khởi động Android Studio.
  2. Chọn Start a new Android Studio project (Bắt đầu một dự án Android Studio mới).
  3. Trong trang Choose your project (Chọn dự án của bạn), hãy chọn mẫu Empty Activity (Hoạt động trống).
  4. Nhấp vào Tiếp theo.
  5. Trên 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ữ.
  6. Nhấp vào Hoàn tất.

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

Trước tiên, trong tệp build.gradle ở cấp ứng dụng, hãy thêm các lệnh nhập cho tiện ích vào phần phụ thuộc. Do kích thước của tiện ích ExoPlayer IMA, hãy triển khai và bật multidex tại đây. Đây là điều cần thiết đối với các ứng dụng có minSdkVersion được đặt thành 20 trở xuống. Ngoài ra, hãy thêm compileOptions mới để chỉ định thông tin về khả năng tương thích của phiên bản Java.

apply plugin: 'com.android.application'

android {
    namespace 'com.google.ads.interactivemedia.v3.samples.exoplayerexample'
    compileSdk 36

    // Java 17 required by Gradle 8+
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }

    defaultConfig {
        applicationId "com.google.ads.interactivemedia.v3.samples.exoplayerexample"
        minSdkVersion 21
        targetSdkVersion 36
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    google()
    mavenCentral()
}

dependencies {
    def media3_version = "1.8.0"
    implementation "androidx.media3:media3-ui:$media3_version"
    implementation "androidx.media3:media3-exoplayer:$media3_version"

    // The library adds the IMA ExoPlayer integration for ads.
    implementation "androidx.media3:media3-exoplayer-ima:$media3_version"

    implementation 'androidx.multidex:multidex:2.0.1'
}

3. Tạo vùng chứa giao diện người dùng quảng cáo

Tạo khung hiển thị để dùng làm PlayerView ExoPlayer bằng cách tạo một androidx.media3.ui.PlayerView. Ngoài ra, hãy thay đổi androidx.constraintlayout.widget.ConstraintLayout thành LinearLayout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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="wrap_content" />

    <!-- UI element for viewing SDK event log -->
    <TextView
        android:id="@+id/logText"
        android:gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="100"
        android:scrollbars="vertical"
        android:textSize="@dimen/font_size">
    </TextView>

</LinearLayout>

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

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

import static android.os.Build.VERSION.SDK_INT;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.TextView;
import androidx.media3.common.MediaItem;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.ima.ImaAdsLoader;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.ui.PlayerView;
import androidx.multidex.MultiDex;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;

Sau đó, hãy cập nhật lớp MainActivity để mở rộng Activity bằng cách thêm các biến private cho PlayerView, ExoPlayer, ImaAdsLoaderImaSdkSettings:

/** Main Activity. */
@SuppressLint("UnsafeOptInUsageError")
/* @SuppressLint is needed for new media3 APIs. */
public class MyActivity extends Activity {

  private static final String SAMPLE_VIDEO_URL =
      "https://storage.googleapis.com/gvabox/media/samples/stock.mp4";
  private static final String SAMPLE_VAST_TAG_URL =
      "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/"
          + "single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90"
          + "&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&correlator=";
  private static final String LOG_TAG = "ImaExoPlayerExample";

  private PlayerView playerView;
  private TextView logText;
  private ExoPlayer player;
  private ImaAdsLoader adsLoader;
  private ImaSdkSettings imaSdkSettings;

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

Ghi đè phương thức onCreate và thêm các phép gán biến bắt buộc để tạo một đối tượng adsLoader mới bằng URL thẻ quảng cáo.

@Override
protected void onCreate(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);

  // Create an AdsLoader.
  adsLoader =
      new ImaAdsLoader.Builder(/* context= */ this)
          .setAdEventListener(buildAdEventListener())
          .setImaSdkSettings(getImaSdkSettings())
          .build();
}

Tạo phương thức buildAdEventListener() để trả về một đối tượng AdEventListener nhằm ghi lại các sự kiện IMA để gỡ lỗi. Tiện ích ExoPlayer IMA đã xử lý các sự kiện IMA và không cần thêm bất cứ điều gì để hoạt động.

public AdEvent.AdEventListener buildAdEventListener() {
  logText = findViewById(R.id.logText);
  logText.setMovementMethod(new ScrollingMovementMethod());

  return event -> {
    AdEvent.AdEventType eventType = event.getType();
    if (eventType == AdEvent.AdEventType.AD_PROGRESS) {
      return;
    }
    String log = "IMA event: " + eventType;
    if (logText != null) {
      logText.append(log + "\n");
    }
    Log.i(LOG_TAG, log);
  };
}

Tạo phương thức trợ giúp getImaSdkSettings() để trả về một đối tượng ImaSdkSettings nhằm đặt mọi chế độ cài đặt IMA SDK:

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

6. Khởi chạy và phát hành trình phát

Thêm các phương thức để phát hành và khởi động trình phát. Trong phương thức initializePlayer(), hãy tạo ExoPlayer. Sau đó, hãy tạo AdsMediaSource và đặt thành trình phát:

private void releasePlayer() {
  adsLoader.setPlayer(null);
  playerView.setPlayer(null);
  player.release();
  player = null;
}

private void initializePlayer() {
  // Set up the factory for media sources, passing the ads loader and ad view providers.
  DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);

  MediaSource.Factory mediaSourceFactory =
      new DefaultMediaSourceFactory(dataSourceFactory)
          .setLocalAdInsertionComponents(unusedAdTagUri -> adsLoader, playerView);

  // 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);

  // Create the MediaItem to play, specifying the content URI and ad tag URI.
  Uri contentUri = Uri.parse(SAMPLE_VIDEO_URL);
  Uri adTagUri = Uri.parse(SAMPLE_VAST_TAG_URL);
  MediaItem mediaItem =
      new MediaItem.Builder()
          .setUri(contentUri)
          .setAdsConfiguration(new MediaItem.AdsConfiguration.Builder(adTagUri).build())
          .build();

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

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

7. 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 trình phát:

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

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

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

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

@Override
protected void onDestroy() {
  adsLoader.release();

  super.onDestroy();
}

Giờ đây, bạn đã yêu cầu và hiển thị quảng cáo thành công bằng SDK IMA. Để tìm hiểu về các tính năng nâng cao khác, hãy khám phá các hướng dẫn khác hoặc các mẫu trên GitHub.