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

IMA SDK 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 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 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 tiện ích IMA ExoPlayer. Nếu bạn muốn xem hoặc làm theo quy trình tích hợp mẫu hoàn chỉnh, hãy tải BasicExample xuống từ GitHub.

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

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

  • AdDisplayContainer: Đối tượng vùng chứa nơi quảng cáo hiển thị.
  • AdsLoader: Đối tượng yêu cầu quảng cáo và xử lý sự kiện từ phản hồi yêu cầu quảng cáo. Bạn chỉ nên tạo thực thể cho một trình tải quảng cáo. Bạn 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: Đố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 thông số bổ sung, chẳng hạn như kích thước quảng cáo.
  • AdsManager: Đố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 mới trong Android Studio

Để 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. Trên trang Chọn dự án của bạn, hãy chọn mẫu Hoạt động trống.
  4. Nhấp vào Tiếp theo.
  5. Trên trang Configure your project (Định cấu hình dự án), hãy đặt tên cho dự án rồi chọn Java cho ngôn ngữ.
  6. Nhấp vào Hoàn tất.

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

Trước tiên, trong tệp build.gradle ở cấp ứng dụng, hãy thêm các mục nhập cho tiện ích vào mục phần phụ thuộc. Do kích thước của tiện ích IMA ExoPlayer, hãy triển khai và bật multidex tại đây. Điều này cần thiết cho 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.

app/build.gradle
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 quyền của người dùng theo yêu cầu của 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 phần khai báo ý định

Nếu ứng dụng của bạn nhắm mục tiêu đế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 khai báo ý định rõ ràng để mở các đườ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 tính năng 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 khung hiển thị để dùng làm ExoPlayer PlayerView bằng cách tạo một đố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.

app/src/main/res/layout/activity_main.xml
<?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 của bạn 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 của bạn.

app/src/main/res/values/strings.xml
<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 IMA ExoPlayer

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, SimpleExoPlayerImaAdsLoader.

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

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 chỉ định biến bắt buộc để tạo đối tượng adsLoader mới bằng URL thẻ quảng cáo.

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

...

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 động và giải phóng trình phát

Thêm phương thức để khởi chạy và giải phóng trình phát. Trong phương thức khởi chạy, hãy tạo SimpleExoPlayer. Sau đó, hãy tạo AdsMediaSource và đặt thành trình phát.

app/src/main/java/com/example/project name/MainActivity.java
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
app/src/main/java/com/example/project name/MainActivity.java
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 về các tính năng bổ sung của SDK, hãy xem hướng dẫn khác hoặc mẫu trên GitHub.