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

IMA SDK를 사용하면 멀티미디어 광고를 웹사이트와 앱에 쉽게 통합할 수 있습니다. IMA SDK는 원하는 형식에서 광고를 <ph type="x-smartling-placeholder"></ph> VAST 호환 광고 서버를 사용하고 앱에서 광고 재생을 관리할 수 있습니다. IMA 클라이언트 측 SDK를 사용하면 SDK는 광고 재생을 처리하는 동안 콘텐츠 동영상 재생은 계속 제어할 수 있습니다. 다음 시간 동안 광고 재생 앱의 콘텐츠 동영상 플레이어 위에 배치된 별도의 동영상 플레이어입니다.

이 가이드에서는 ExoPlayer IMA 확장 프로그램을 사용합니다. 완료된 샘플 통합을 보거나 함께 보려면 다음을 다운로드하세요. 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. 마침을 클릭합니다.

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

먼저 애플리케이션 수준의 build.gradle 파일에서 확장 프로그램에 대한 가져오기를 종속 항목 섹션을 참조하세요. ExoPlayer IMA 확장 프로그램의 크기로 인해 멀티덱스를 살펴보겠습니다. 이는 minSdkVersion이 20 이하로 설정된 앱에 필요합니다. 또한 새 compileOptions를 추가하여 Java 버전 호환성 정보를 지정합니다.

app/build.gradle <ph type="x-smartling-placeholder">
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'

    ...
}
</ph>

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

app/src/main/AndroidManifest.xml <ph type="x-smartling-placeholder">
<?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>
</ph>

인텐트 선언 추가

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

StyledPlayerView를 만들어 ExoPlayer PlayerView로 사용할 뷰를 만듭니다. 객체를 지정합니다. 또한 androidx.constraintlayout.widget.ConstraintLayoutLinearLayout로 변환합니다.

app/src/main/res/layout/activity_main.xml <ph type="x-smartling-placeholder">
<?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>
</ph>

4. 광고 요청을 위한 콘텐츠 URL 및 광고 태그 URL 추가

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

app/src/main/res/values/strings.xml <ph type="x-smartling-placeholder">
<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>
</ph>

5. ExoPlayer IMA 확장 프로그램 가져오기

ExoPlayer 확장 프로그램의 가져오기 문을 추가합니다. 그런 다음 MainActivity 클래스가 비공개 변수를 추가하여 Activity를 확장합니다. PlayerView, SimpleExoPlayer, ImaAdsLoader

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를 사용하여 광고를 요청하고 표시합니다. 자세히 알아보려면 자세한 내용은 다른 가이드 또는 GitHub의 샘플