เริ่มต้นใช้งานส่วนขยาย IMA ของ Exoplayer

IMA SDK ช่วยให้ผสานรวมโฆษณามัลติมีเดียเข้ากับเว็บไซต์และแอปได้อย่างง่ายดาย IMA SDK สามารถ ขอโฆษณาจากเซิร์ฟเวอร์โฆษณา ที่รองรับ VAST และจัดการการเล่นโฆษณาในแอปได้ เมื่อใช้ SDK ฝั่งไคลเอ็นต์ของ IMA คุณจะควบคุมการเล่นวิดีโอเนื้อหาได้ ในขณะที่ SDK จะจัดการการเล่นโฆษณา โฆษณาจะเล่นในวิดีโอเพลเยอร์ แยกต่างหากซึ่งวางอยู่ด้านบนของวิดีโอเพลเยอร์เนื้อหาของแอป

คู่มือนี้แสดงวิธีผสานรวม IMA SDK เข้ากับโปรเจ็กต์ Android Studio ที่ว่างเปล่าโดยใช้ส่วนขยาย IMA ของ ExoPlayer หากต้องการดูหรือทำตามตัวอย่างการผสานรวมที่เสร็จสมบูรณ์แล้ว ให้ดาวน์โหลด BasicExample จาก GitHub

ภาพรวมฝั่งไคลเอ็นต์ของ IMA

การใช้ IMA ฝั่งไคลเอ็นต์เกี่ยวข้องกับคอมโพเนนต์ SDK หลัก 4 อย่าง ซึ่งแสดงให้เห็นในคำแนะนำนี้

  • AdDisplayContainer: ออบเจ็กต์คอนเทนเนอร์ที่ระบุตําแหน่งที่ IMA แสดงองค์ประกอบ UI ของโฆษณาและวัดการมองเห็นโฆษณา รวมถึงมุมมองแอ็กทีฟและ Open Measurement
  • AdsLoader: ออบเจ็กต์ที่ขอโฆษณาและจัดการเหตุการณ์จากการตอบกลับคำขอโฆษณา คุณควรสร้างอินสแตนซ์ของ AdLoader เพียงรายการเดียว ซึ่งสามารถนำกลับมาใช้ใหม่ได้ตลอดอายุการใช้งานของแอปพลิเคชัน
  • AdsRequest: ออบเจ็กต์ที่กำหนดคำขอโฆษณา คำขอโฆษณาระบุ URL สำหรับแท็กโฆษณา VAST รวมถึง พารามิเตอร์เพิ่มเติม เช่น ขนาดโฆษณา
  • AdsManager: ออบเจ็กต์ที่มีการตอบกลับคำขอโฆษณา ควบคุมการเล่นโฆษณา และรอฟังเหตุการณ์โฆษณา ที่ SDK เรียกใช้

ข้อกำหนดเบื้องต้น

ก่อนเริ่ม คุณต้องมี Android Studio 3.0 ขึ้นไป

1. สร้างโปรเจ็กต์ Android Studio ใหม่

หากต้องการสร้างโปรเจ็กต์ Android Studio ให้ทำตามขั้นตอนต่อไปนี้

  1. เริ่มใช้ Android Studio
  2. เลือก Start a new Android Studio project
  3. ในหน้าเลือกโปรเจ็กต์ ให้เลือกเทมเพลตกิจกรรมว่าง
  4. คลิกถัดไป
  5. ในหน้ากำหนดค่าโปรเจ็กต์ ให้ตั้งชื่อโปรเจ็กต์และเลือก Java เป็นภาษา
  6. คลิกเสร็จสิ้น

2. เพิ่มส่วนขยาย IMA ของ ExoPlayer ลงในโปรเจ็กต์

ก่อนอื่นในไฟล์ build.gradle ระดับแอปพลิเคชัน ให้เพิ่มการนำเข้าสำหรับส่วนขยายไปยังส่วน dependencies เนื่องจากส่วนขยาย ExoPlayer IMA มีขนาดใหญ่ ให้ใช้และเปิดใช้ Multidex ที่นี่ ซึ่งจำเป็นสำหรับแอปที่มี minSdkVersion ตั้งค่าเป็น 20 หรือต่ำกว่า นอกจากนี้ ให้เพิ่ม compileOptions ใหม่เพื่อระบุข้อมูลความเข้ากันได้ของเวอร์ชัน 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. สร้างคอนเทนเนอร์ UI โฆษณา

สร้างมุมมองเพื่อใช้เป็น ExoPlayer PlayerView โดยการสร้าง androidx.media3.ui.PlayerView นอกจากนี้ ให้เปลี่ยน androidx.constraintlayout.widget.ConstraintLayout เป็น 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. นำเข้าส่วนขยาย IMA ของ ExoPlayer

เพิ่มคำสั่งนำเข้าสำหรับส่วนขยาย 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;

จากนั้นอัปเดตคลาส MainActivity เพื่อขยาย Activity โดยเพิ่ม ตัวแปรส่วนตัวสำหรับ PlayerView, ExoPlayer, ImaAdsLoader และ ImaSdkSettings ดังนี้

/** 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. สร้างอินสแตนซ์ adsLoader

เขียนทับเมธอด onCreate และเพิ่มการกําหนดตัวแปรที่จําเป็นเพื่อสร้างออบเจ็กต์ adsLoader ใหม่ที่มี URL แท็กโฆษณา

@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();
}

สร้างเมธอด buildAdEventListener() เพื่อส่งคืนออบเจ็กต์ AdEventListener เพื่อบันทึกเหตุการณ์ IMA สําหรับการแก้ไขข้อบกพร่อง ส่วนขยาย IMA ของ ExoPlayer จัดการเหตุการณ์ IMA อยู่แล้ว และไม่จำเป็นต้องมีสิ่งใดเพิ่มเติมที่นี่เพื่อทำงาน

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

สร้างเมธอดตัวช่วย getImaSdkSettings() เพื่อส่งคืนออบเจ็กต์ ImaSdkSettings เพื่อตั้งค่า IMA SDK

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

6. เริ่มต้นและปล่อยโปรแกรมเล่น

เพิ่มเมธอดเพื่อเผยแพร่และเริ่มต้นโปรแกรมเล่น ในinitializePlayer() เมธอด ให้สร้าง ExoPlayer จากนั้นสร้าง AdsMediaSource และตั้งค่าให้กับเพลเยอร์โดยทำดังนี้

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. จัดการเหตุการณ์ของผู้เล่น

สุดท้าย ให้สร้างการเรียกกลับสำหรับเหตุการณ์วงจรของผู้เล่น

  • 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();
}

ตอนนี้คุณขอและแสดงโฆษณาด้วย IMA SDK ได้สำเร็จแล้ว ดูข้อมูลเพิ่มเติมเกี่ยวกับ ฟีเจอร์ขั้นสูงได้จากคำแนะนำอื่นๆ หรือตัวอย่างใน GitHub