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 nào tuân thủ VAST 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 duy trì 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 ở đầu 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 ExoPlayer IMA. 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ề IMA phía máy khách
Việc triển khai IMA phía máy khách liên quan đến 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í IMA hiển thị các phần tử giao diện người dùng quảng cáo và đo lường khả năng xem, bao gồm cả Chế độ xem đang kích hoạt và Đ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 bản sao một trình tải quảng cáo, có thể sử dụng lại 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. Yêu cầu quảng cáo chỉ định URL cho thẻ quảng cáo VAST, cũng như các tham số bổ sung, chẳng hạn như phương diện 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 chế độ 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 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).
- Trên trang Choose your project (Chọn dự án), hãy chọn mẫu Empty Activity (Hoạt động trống).
- Nhấp vào Tiếp theo.
- Trên trang Configure your project (Định cấu hình dự án), hãy đặt tên cho dự án và chọn Java cho ngôn ngữ.
- Nhấp vào Hoàn tất.
2. Thêm tiện ích ExoPlayer IMA 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ầ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. Điều này là 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.
android { namespace 'com.google.ads.interactivemedia.v3.samples.exoplayerexample' compileSdkVersion 34 compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } } defaultConfig { applicationId "com.google.ads.interactivemedia.v3.samples.exoplayerexample" 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.3.1' implementation 'androidx.media3:media3-exoplayer:1.3.1' implementation 'androidx.media3:media3-exoplayer-ima:1.3.1' ... }
Thêm các quyền mà người dùng cần có để SDK IMA 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 SDK --> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> ... </manifest>
Thêm nội dung 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 SDK IMA yêu cầu bạn phải khai báo rõ ràng ý định mở đường liên kết web. Thêm đoạn mã sau vào tệp kê khai của ứng dụng để bật lượt nhấp vào 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>
3. Tạo vùng chứa giao diện người dùng quảng cáo
Tạo thành phần hiển thị để sử dụng làm ExoPlayer PlayerView bằng cách tạo đối tượng StyledPlayerView
có mã nhận dạng thích hợp. Ngoài ra, hãy thay đổi androidx.constraintlayout.widget.ConstraintLayout
thành LinearLayout
.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.media3.ui.PlayerView android:id="@+id/player_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
4. Thêm URL nội dung và URL thẻ quảng cáo cho yêu cầu quảng cáo
Thêm các mục vào strings.xml
để lưu trữ URL nội dung và URL thẻ quảng cáo VAST.
<resources> <string name="app_name">Your_Project_Name</string> <string name="content_url"><![CDATA[https://storage.googleapis.com/gvabox/media/samples/stock.mp4]]></string> <string name="ad_tag_url"><![CDATA[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&impl=s&correlator=]]></string> </resources>
5. Nhập tiện ích ExoPlayer IMA
Thêm câu lệnh nhập cho tiện ích ExoPlayer. Sau đó, hãy cập nhật lớp MainActivity
để mở rộng Activity
bằng cách thêm các biến riêng tư cho PlayerView
, SimpleExoPlayer
và ImaAdsLoader
.
import android.app.Activity; import android.net.Uri; import android.os.Bundle; 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.ImaAdsLoader; import androidx.media3.exoplayer.source.DefaultMediaSourceFactory; import androidx.media3.exoplayer.source.MediaSource; import androidx.media3.ui.PlayerView; import androidx.multidex.MultiDex; ... public class MainActivity extends Activity { private PlayerView playerView; private ExoPlayer player; private ImaAdsLoader adsLoader; }
6. Tạo một thực thể adsLoader
Ghi đè phương thức onCreate
và thêm các chỉ định biến bắt buộc để tạo một đối tượng adsLoader
mới có URL thẻ quảng cáo.
... public class MainActivity extends Activity { private PlayerView playerView; private ExoPlayer player; private ImaAdsLoader adsLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MultiDex.install(this); playerView = findViewById(R.id.player_view); // Create an AdsLoader. adsLoader = new ImaAdsLoader.Builder(/* context= */ this) .setAdEventListener(buildAdEventListener()) .build(); } public AdEvent.AdEventListener buildAdEventListener() { AdEvent.AdEventListener imaAdEventListener = event -> { AdEvent.AdEventType eventType = event.getType(); // Log IMA events for debugging. // The ExoPlayer IMA extension already handles IMA events and does not need anything // additional here to function. }; return imaAdEventListener; } }
7. Khởi chạy và phát hành trình phát
Thêm các phương thức để khởi chạy và phát hành trình phát. Trong phương thức khởi tạo, hãy tạo SimpleExoPlayer
. Sau đó, hãy tạo AdsMediaSource
và đặt thành trình phát.
public class MainActivity extends Activity { ... 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(getString(R.string.content_url)); Uri adTagUri = Uri.parse(getString(R.string.ad_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); } }
8. Xử lý sự kiện của người chơi
Cuối cùng, hãy tạo lệnh gọi lại cho các sự kiện trong vòng đời của người chơi:
onStart
onResume
onStop
onPause
onDestroy
public class MainActivity extends Activity { private PlayerView playerView; private SimpleExoPlayer player; private ImaAdsLoader adsLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); playerView = findViewById(R.id.player_view); // Create an AdsLoader. adsLoader = new ImaAdsLoader.Builder(/* context= */ this) .setAdEventListener(buildAdEventListener()) .build(); } @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 protected void onDestroy() { super.onDestroy(); adsLoader.release(); } ... }
Vậy là xong! Bạn hiện đang yêu cầu và hiển thị quảng cáo bằng SDK IMA. Để tìm hiểu thêm về các tính năng SDK khác, hãy xem các hướng dẫn khác hoặc các mẫu trên GitHub.