バナー広告

バナー広告は、アプリの画面の一部に表示される長方形の広告です。アンカー アダプティブ バナーは、アスペクト比が固定された広告で、ユーザーがアプリを操作している間、画面の上部または下部に固定された状態で表示されます。

このガイドでは、アンカー アダプティブ バナー広告を Android アプリに読み込む方法について説明します。

前提条件

必ずテスト広告でテストする

アプリの開発とテストでは必ずテスト広告を使用し、配信中の実際の広告は使用しないでください。実際の広告を使用すると、アカウントが停止される可能性があります。

テスト広告を読み込むには、次に示す Android バナー向けのテスト専用広告ユニット ID を使う方法が便利です。

ca-app-pub-3940256099942544/9214589741

この ID は、すべてのリクエストに対してテスト広告を返す特別な ID で、アプリのコーディング、テスト、デバッグで自由に使うことができます。なお、アプリを公開する前に、必ずテスト用 ID をご自身の広告ユニット ID に置き換えてください。

Google Mobile Ads SDK(ベータ版)のテスト広告の仕組みについて詳しくは、テスト広告を有効にするをご覧ください。

広告ビューを定義する

XML レイアウト

アンカー アダプティブ バナー広告のコンテナとして機能するビューを、レイアウト XML ファイルに追加します。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

  <FrameLayout
      android:id="@+id/banner_view_container"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent">

  </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Jetpack Compose

Compose UI 内に AndroidView 要素を含め、バナー広告を保持する mutableStateOf<BannerAd?> 変数を定義します。

// Initialize required variables.
val context = LocalContext.current
var bannerAdState by remember { mutableStateOf<BannerAd?>(null) }

// The AdView is placed at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
  bannerAdState?.let { bannerAd ->
    Box(modifier = Modifier.fillMaxWidth()) {
      // Display the ad within an AndroidView.
      AndroidView(
        modifier = modifier.wrapContentSize(),
        factory = { bannerAd.getView(requireActivity()) },
      )
    }
  }
}

広告を読み込む

  1. 広告ユニット ID とアンカー付きアダプティブ バナーのサイズを指定して BannerAdRequest オブジェクトを作成します。
  2. BannerAd.load() を呼び出します。
  3. ビュー階層に BannerAd.getView() を追加します。

Kotlin

import com.google.android.libraries.ads.mobile.sdk.banner.AdSize
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRequest
import com.google.android.libraries.ads.mobile.sdk.common.AdLoadCallback
import com.google.android.libraries.ads.mobile.sdk.common.LoadAdError

class MainActivity : Activity() {

  private var bannerAd: BannerAd? = null
  private lateinit var binding: ActivityMainBinding
  private lateinit var adSize: AdSize
  private lateinit var bannerViewContainer: FrameLayout

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    // 320 is a placeholder value. Replace 320 with your banner container width.
    adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320)

    // Give the banner container a placeholder height to avoid a sudden layout
    // shifts when the ad loads.
    bannerViewContainer = binding.bannerViewContainer
    val bannerLayoutParams = bannerViewContainer.layoutParams
    bannerLayoutParams.height = adSize.getHeightInPixels(requireContext())
    bannerViewContainer.layoutParams = bannerLayoutParams

    // Step 1 - Create a BannerAdRequest object with ad unit ID and size.
    val adRequest = BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build()

    // Step 2 - Load the ad.
    BannerAd.load(
      adRequest,
      object : AdLoadCallback<BannerAd> {
        override fun onAdLoaded(ad: BannerAd) {
          // Assign the loaded ad to the BannerAd object.
          bannerAd = ad
          // Step 3 - Call BannerAd.getView() to get the View and add it
          // to view hierarchy on the UI thread.
          activity?.runOnUiThread {
            binding.bannerViewContainer.addView(ad.getView(requireActivity()))
          }
        }

        override fun onAdFailedToLoad(loadAdError: LoadAdError) {
          bannerAd = null
        }
      },
    )
  }
}

Java

import com.google.android.libraries.ads.mobile.sdk.banner.AdSize;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRequest;
import com.google.android.libraries.ads.mobile.sdk.common.AdLoadCallback;
import com.google.android.libraries.ads.mobile.sdk.common.LoadAdError;

public class MainActivity extends AppCompatActivity {

  private BannerAd bannerAd;
  private ActivityMainBinding binding;
  private AdSize adSize;
  private FrameLayout bannerViewContainer;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    // 320 is a placeholder value. Replace 320 with your banner container width.
    adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320);

    // Give the banner container a placeholder height to avoid a sudden layout
    // shifts when the ad loads.
    bannerViewContainer = binding.bannerViewContainer;
    LayoutParams bannerLayoutParams = bannerViewContainer.getLayoutParams();
    bannerLayoutParams.height = adSize.getHeightInPixels(this);
    bannerViewContainer.setLayoutParams(bannerLayoutParams);

    // Step 1 - Create a BannerAdRequest object with ad unit ID and size.
    BannerAdRequest adRequest = new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741",
        adSize).build();

    // Step 2 - Load the ad.
    BannerAd.load(
        adRequest,
        new AdLoadCallback<BannerAd>() {
          @Override
          public void onAdLoaded(@NonNull BannerAd ad) {
            // Assign the loaded ad to the BannerAd object.
            bannerAd = ad;
            // Step 3 - Call BannerAd.getView() to get the View and add it
            // to view hierarchy on the UI thread.
            runOnUiThread(
                () -> binding.bannerViewContainer.addView(ad.getView(MainActivity.this)));
          }

          @Override
          public void onAdFailedToLoad(@NonNull LoadAdError adError) {
            bannerAd = null;
          }
        });
  }
}

Jetpack Compose

// Request an anchored adaptive banner with a width of 360.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(requireContext(), 360)

// Load the ad when the screen is active.
val coroutineScope = rememberCoroutineScope()
val isPreviewMode = LocalInspectionMode.current
LaunchedEffect(context) {
  bannerAdState?.destroy()
  if (!isPreviewMode) {
    coroutineScope.launch {
      when (val result = BannerAd.load(BannerAdRequest.Builder(AD_UNIT_ID, adSize).build())) {
        is AdLoadResult.Success -> {
          bannerAdState = result.ad
        }
        is AdLoadResult.Failure -> {
          showToast("Banner failed to load.")
          Log.w(Constant.TAG, "Banner ad failed to load: $result.error")
        }
      }
    }
  }
}

広告を更新する

広告ユニットの更新を有効にしていれば、広告の読み込みに失敗しても、別の広告をリクエストする必要はありません。Google Mobile Ads SDK(ベータ版)では、AdMob の管理画面で指定した更新頻度が使用されます。更新を有効にしていない場合は、新しいリクエストを発行します。更新頻度の設定など、広告ユニットの更新について詳しくは、バナー広告の自動更新を使用するをご覧ください。

広告リソースを解放する

バナー広告の使用が終了したら、バナー広告のリソースを解放できます。

広告のリソースを解放するには、ビュー階層から広告を削除し、関連するすべての参照も削除します。

Kotlin

// Remove banner from view hierarchy.
val parentView = adView?.parent
if (parentView is ViewGroup) {
  parentView.removeView(adView)
}

// Destroy the banner ad resources.
adView?.destroy()

// Drop reference to the banner ad.
adView = null

Java

// Remove banner from view hierarchy.
if (adView.getParent() instanceof ViewGroup) {
  ((ViewGroup) adView.getParent()).removeView(adView);
}
// Destroy the banner ad resources.
adView.destroy();
// Drop reference to the banner ad.
adView = null;

Jetpack Compose


// Destroy the ad when the screen is disposed.
DisposableEffect(Unit) { onDispose { bannerAdState?.destroy() } }

広告イベント

広告のインプレッションとクリック、広告の開始と終了など、広告のライフサイクルで生じるさまざまなイベントをリッスンできます。バナーを表示する前にコールバックを設定することをおすすめします。

Kotlin

BannerAd.load(
  BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
  object : AdLoadCallback<BannerAd> {
    override fun onAdLoaded(ad: BannerAd) {
      ad.adEventCallback =
        object : BannerAdEventCallback {
          override fun onAdImpression() {
            // Banner ad recorded an impression.
          }

          override fun onAdClicked() {
            // Banner ad recorded a click.
          }

          override fun onAdShowedFullScreenContent() {
            // Banner ad showed.
          }

          override fun onAdDismissedFullScreenContent() {
            // Banner ad dismissed.
          }

          override fun onAdFailedToShowFullScreenContent(
            fullScreenContentError: FullScreenContentError
          ) {
            // Banner ad failed to show.
          }
        }
    }
    // ...
  }
)

Java

BannerAd.load(
    new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
    new AdLoadCallback<BannerAd>() {
      @Override
      public void onAdLoaded(@NonNull BannerAd ad) {
        ad.setAdEventCallback(new BannerAdEventCallback() {
          @Override
          public void onAdImpression() {
            // Banner ad recorded an impression.
          }

          @Override
          public void onAdClicked() {
            // Banner ad recorded a click.
          }

          @Override
          public void onAdShowedFullScreenContent() {
            // Banner ad showed.
          }

          @Override
          public void onAdDismissedFullScreenContent() {
            // Banner ad dismissed.
          }

          @Override
          public void onAdFailedToShowFullScreenContent(
              @NonNull FullScreenContentError fullScreenContentError) {
            // Banner ad failed to show.
          }
        });

        // ...
      }
    });

広告更新コールバック

バナー広告で自動更新を使用する場合、BannerAdRefreshCallback は広告の更新イベントを処理します。広告ビューをビュー階層に追加する前に、必ずコールバックを設定してください。広告の更新について詳しくは、広告を更新するをご覧ください。

Kotlin

BannerAd.load(
  BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
  object : AdLoadCallback<BannerAd> {
    override fun onAdLoaded(ad: BannerAd) {
      ad.bannerAdRefreshCallback =
        object : BannerAdRefreshCallback {
          // Set the ad refresh callbacks.
          override fun onAdRefreshed() {
            // Called when the ad refreshes.
          }

          override fun onAdFailedToRefresh(loadAdError: LoadAdError) {
            // Called when the ad fails to refresh.
          }
        }

      // ...
    }
  }
)

Java

BannerAd.load(
    new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
    new AdLoadCallback<BannerAd>() {
      @Override
      public void onAdLoaded(@NonNull BannerAd ad) {
        ad.setBannerAdRefreshCallback(
            // Set the ad refresh callbacks.
            new BannerAdRefreshCallback() {
              @Override
              public void onAdRefreshed() {
                // Called when the ad refreshes.
              }

              @Override
              public void onAdFailedToRefresh(@NonNull LoadAdError adError) {
                // Called when the ad fails to refresh.
              }
            });
        // ...
      }
    });

動画広告のハードウェア アクセラレーション

バナー広告で動画広告を正常に表示するには、ハードウェア アクセラレーションを有効にする必要があります。

ハードウェア アクセラレーションはデフォルトで有効になっていますが、一部のアプリでは無効にすることもできます。お客様のアプリで無効にできる場合、広告を使用する Activity クラスのハードウェア アクセラレーションを有効にすることをおすすめします。

ハードウェア アクセラレーションを有効にする

ハードウェア アクセラレーションをグローバルに有効にするとアプリが正しく動作しない場合は、個々のアクティビティでの設定が可能です。ハードウェア アクセラレーションを有効または無効にするには、AndroidManifest.xml<application> および <activity> 要素で android:hardwareAccelerated 属性を使用できます。次の例では、アプリ全体でハードウェア アクセラレーションを有効にしつつ、1 つのアクティビティで無効にしています。

<application android:hardwareAccelerated="true">
    <!-- For activities that use ads, hardwareAcceleration should be true. -->
    <activity android:hardwareAccelerated="true" />
    <!-- For activities that don't use ads, hardwareAcceleration can be false. -->
    <activity android:hardwareAccelerated="false" />
</application>

ハードウェア アクセラレーションを制御するオプションについて詳しくは、ハードウェア アクセラレーション ガイドをご覧ください。アクティビティが無効の場合、個々の広告ビューではハードウェア アクセラレーションを有効にできないため、アクティビティ自体でハードウェア アクセラレーションが有効になっている必要があります。

Google Mobile Ads SDK(ベータ版)の使用方法を示したサンプルアプリをダウンロードし、実行してください。