Exoplayer IMA 확장 프로그램 시작하기

IMA SDK를 사용하면 멀티미디어 광고를 웹사이트와 앱에 쉽게 통합할 수 있습니다. IMA SDK는 VAST 호환 광고 서버에서 광고를 요청하고, 앱에서 광고 재생을 관리할 수 있습니다. IMA 클라이언트 측 SDK를 사용하면 SDK가 광고 재생을 처리하는 동안 콘텐츠 동영상 재생에 대한 제어는 유지됩니다. 앱의 콘텐츠 동영상 플레이어 상단에 위치한 별도의 동영상 플레이어에서 광고가 재생됩니다.

이 가이드에서는 ExoPlayer IMA 확장 프로그램을 사용하여 IMA SDK를 빈 Android 스튜디오 프로젝트에 통합하는 방법을 보여줍니다. 완료된 샘플 통합을 확인하거나 따라 하려면 GitHub에서 BasicExample을 다운로드하세요.

IMA 클라이언트측 개요

IMA 클라이언트 측 구현에는 네 가지 주요 SDK 구성요소가 포함됩니다. 이러한 구성요소는 이 가이드에 나와 있습니다.

  • AdDisplayContainer: 광고가 렌더링되는 컨테이너 객체입니다.
  • AdsLoader: 광고를 요청하고 광고 요청 응답에서 발생한 이벤트를 처리하는 객체입니다. 애플리케이션의 수명 주기 내내 재사용할 수 있는 하나의 광고 로더만 인스턴스화해야 합니다.
  • AdsRequest: 광고 요청을 정의하는 객체입니다. 광고 요청은 VAST 광고 태그의 URL 및 광고 크기와 같은 추가 매개변수를 지정합니다.
  • AdsManager: 광고 요청에 대한 응답을 포함하고 광고 재생을 제어하며 SDK에서 시작한 광고 이벤트를 수신 대기하는 객체입니다.

기본 요건

시작하려면 Android 스튜디오 3.0 이상이 필요합니다.

1. 새 Android 스튜디오 프로젝트 만들기

Android 스튜디오 프로젝트를 만들려면 다음 단계를 완료하세요.

  1. Android 스튜디오를 시작합니다.
  2. Start a new Android Studio project를 선택합니다.
  3. Choose your project 페이지에서 Empty Activity 템플릿을 선택합니다.
  4. 다음을 클릭합니다.
  5. Configure your project 페이지에서 프로젝트 이름을 지정하고 언어로 Java를 선택합니다.
  6. Finish를 클릭합니다.

2. 프로젝트에 ExoPlayer IMA 확장 프로그램 추가

먼저 애플리케이션 수준의 build.gradle 파일에서 종속 항목 섹션에 확장 프로그램의 가져오기를 추가합니다. ExoPlayer IMA 확장 프로그램의 크기 때문에 여기에서 멀티덱스를 구현하고 사용 설정합니다. minSdkVersion이 20 이하로 설정된 앱에 필요합니다. 또한 새 compileOptions를 추가하여 자바 버전 호환성 정보를 지정합니다.

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'

    ...
}

광고를 요청하기 위해 IMA SDK에서 요구하는 사용자 권한을 추가합니다.

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>

인텐트 선언 추가

앱이 Android 11 (API 수준 30) 이상을 타겟팅하는 경우 현재 및 최신 버전의 IMA SDK에서 웹 링크를 열려면 명시적인 인텐트 선언이 필요합니다. 광고 클릭연결을 사용 설정하려면 앱의 매니페스트 파일에 다음 스니펫을 추가합니다 (사용자가 자세히 알아보기 버튼 클릭).
  <?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. 광고 UI 컨테이너 만들기

ExoPlayer PlayerView로 사용할 뷰를 만들려면 적절한 ID로 StyledPlayerView 객체를 만듭니다. 또한 androidx.constraintlayout.widget.ConstraintLayoutLinearLayout로 변경합니다.

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. 광고 요청에 콘텐츠 URL 및 광고 태그 URL 추가

strings.xml에 항목을 추가하여 콘텐츠 URL과 VAST 광고 태그 URL을 저장합니다.

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. ExoPlayer IMA 확장 프로그램 가져오기

ExoPlayer 확장 프로그램의 import 문을 추가합니다. 그런 다음 PlayerView, SimpleExoPlayerImaAdsLoader의 비공개 변수를 추가하여 Activity를 확장하도록 MainActivity 클래스를 업데이트합니다.

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. adsLoader 인스턴스 만들기

onCreate 메서드를 덮어쓰고 필수 변수 할당을 추가하여 광고 태그 URL로 새 adsLoader 객체를 만듭니다.

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. 플레이어 초기화 및 해제

플레이어를 초기화하고 해제하는 메서드를 추가합니다. 초기화 메서드에서 SimpleExoPlayer를 만듭니다. 그런 다음 AdsMediaSource를 만들어 플레이어로 설정합니다.

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. 플레이어 이벤트 처리

마지막으로 플레이어의 수명 주기 이벤트에 대한 콜백을 생성합니다.

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

  ...

}

작업이 끝났습니다. 이제 IMA SDK를 사용하여 광고를 요청하고 표시합니다. 추가 SDK 기능에 관한 자세한 내용은 다른 가이드 또는 GitHub 샘플을 참고하세요.