使用 IMA SDK,即可輕鬆將多媒體廣告整合至網站和應用程式。IMA SDK 可向任何 符合 VAST 規定的廣告伺服器請求廣告,並在應用程式中管理廣告播放。使用 IMA 用戶端 SDK 時,您可以控管內容影片的播放,SDK 則負責處理廣告播放。廣告會在應用程式內容影片播放器上方的獨立影片播放器中播放。
本指南說明如何使用 ExoPlayer IMA 擴充功能,將 IMA SDK 整合至空白的 Android Studio 專案。如要查看或跟著完成範例整合,請從 GitHub 下載 BasicExample。
IMA 用戶端總覽
導入 IMA 用戶端需要四個主要 SDK 元件,本指南將說明這些元件:
AdDisplayContainer
: 容器物件,用於指定 IMA 要在何處算繪廣告 UI 元素及評估可視度,包括 Active View 和 Open Measurement。AdsLoader
: 要求廣告並處理廣告請求回應事件的物件。您應該只例項化一個廣告載入器,這個載入器可在應用程式的整個生命週期中重複使用。AdsRequest
: 定義廣告請求的物件。廣告請求會指定 VAST 廣告代碼的網址,以及廣告尺寸等其他參數。AdsManager
: 這個物件包含廣告請求的回應、控管廣告播放,並監聽 SDK 觸發的廣告事件。
必要條件
開始之前,您需要 Android Studio 3.0 以上版本。
1. 建立新的 Android Studio 專案
如要建立 Android Studio 專案,請完成下列步驟:
- 啟動 Android Studio。
- 選取「Start a new Android Studio project」。
- 在「選擇專案」頁面中,選取「空白活動」範本。
- 點選 [下一步]。
- 在「Configure your project」頁面中,為專案命名並選取 Java 做為語言。
- 按一下「完成」。
2. 在專案中新增 ExoPlayer IMA 擴充功能
首先,在應用程式層級的 build.gradle 檔案中,將擴充功能的匯入項目新增至依附元件區段。由於 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. 匯入 ExoPlayer IMA 擴充功能
新增 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
類別,加入 PlayerView
、ExoPlayer
、ImaAdsLoader
和 ImaSdkSettings
的私有變數,藉此擴充 Activity
:
/** 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
物件。
@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 事件進行偵錯。ExoPlayer IMA 擴充功能已處理 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 上的範例。