バナー広告を設定する

バナー広告は、デバイス画面の上部や下部など、アプリのレイアウト内の固定位置に表示されます。これらの広告は、ユーザーがアプリを操作している間は画面に表示され続け、設定した時間が経過すると更新されます。アンカー アダプティブ バナーでは、指定した広告の幅を使用して、デバイスごとに広告のサイズが最適化されます。

このページでは、アンカー アダプティブ バナー広告を React Native ネイティブ アプリに統合する方法について説明します。

前提条件

先に進む前に、次のことを実施してください。

Android

ca-app-pub-3940256099942544/9214589741

iOS

ca-app-pub-3940256099942544/2435281174

広告サイズを取得する

アンカー アダプティブ バナー広告をリクエストするには、AdSize.getLargeAnchoredAdaptiveBannerAdSize メソッドを呼び出し、使用可能な広告コンテナの幅を密度非依存ピクセル(dp)で指定します。このメソッドは、AdSize オブジェクトに解決される Promise を返します。

次の例では、アンカー アダプティブ バナー広告の広告サイズを取得して返します。

export async function getAdaptiveAdSize(width: number): Promise<AdSize> {
  const adSize = await AdSize.getLargeAnchoredAdaptiveBannerAdSize(width);
  return adSize;
}

広告を読み込む

AdSize オブジェクトを取得したら、広告ユニット ID と広告サイズを指定して、BannerAd クラスの load メソッドを呼び出します。

次の例では、広告サイズと広告ユニット ID を指定してアンカー アダプティブ バナー広告を読み込み、成功した場合は読み込まれた BannerAd インスタンスを受け取り、失敗した場合はエラーをログに記録します。

export function loadBannerAd(
  adUnitId: string,
  adSize: AdSize,
  callback?: BannerAdLoadCallback,
): void {
  BannerAd.load(
    {adUnitId, adSize},
    {
      // Called when an ad has finished loading.
      onAdLoaded: (ad) => {
        console.log('Banner ad loaded successfully.');
        callback?.onAdLoaded?.(ad);
      },
      // Called when an ad request fails.
      onAdFailedToLoad: (error: LoadAdError) => {
        console.error('Failed to load banner ad:', error.message);
        callback?.onAdFailedToLoad?.(error);
      },
    },
  );
}

広告を更新する

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

バナー広告を表示する

読み込まれた BannerAd インスタンスを表示するには、ビュー階層内の BannerAdView コンポーネントの ad プロパティに広告インスタンスを渡します。

次の例では、広告を表示し、コンポーネントがマウント解除されたときに広告を破棄しています。

export function BannerAdViewComponent({ad}: {ad: BannerAd}): React.JSX.Element {
  useEffect(() => {
    // Destroy native resources when the component unmounts.
    return () => {
      ad.destroy();
    };
  }, [ad]);

  return <BannerAdView ad={ad} />;
}

この例では、コンポーネントがアンマウントされたとき、または広告インスタンスが置き換えられたときに、destroy メソッドを呼び出します。このプロセスにより、広告が使用するメモリとリソースが解放されます。

広告イベントをリッスンする

広告のインプレッションやクリックなどの広告イベントをリッスンするには、BannerAdView コンポーネントにコールバックを設定します。すべてのコールバックについては、BannerAdViewProps をご覧ください。

次の例では、バナー広告イベントをリッスンするコールバックを設定しています。

export function BannerEventsExample({ad}: {ad: BannerAd}): React.JSX.Element {
  return (
    <BannerAdView
      ad={ad}
      // Called when an impression is recorded for an ad.
      onAdImpression={() => {
        console.log('Banner ad recorded an impression.');
      }}
      // Called when a click is recorded for an ad.
      onAdClicked={() => {
        console.log('Banner ad clicked.');
      }}
      // Called when the ad opens an in-app overlay or landing page.
      onAdShowedFullScreenContent={() => {
        console.log('Banner ad opened overlay content.');
      }}
      // Called when the user dismisses the ad overlay.
      onAdDismissedFullScreenContent={() => {
        console.log('Banner ad overlay dismissed.');
      }}
      // Called when the ad is estimated to have earned money.
      onAdPaid={(adValue) => {
        console.log(
          `Banner ad paid: ${adValue.amountMicros} ${adValue.currencyCode}`,
        );
      }}
      // Called when the ad automatically refreshes.
      onAdRefreshed={() => {
        console.log('Banner ad refreshed.');
      }}
      // Called when the ad fails to automatically refresh.
      onAdFailedToRefresh={(error) => {
        console.error('Banner ad failed to refresh:', error.message);
      }}
    />
  );
}

この例では、広告の非表示、インプレッション、クリック、全画面表示、推定広告収入、更新の成功と失敗などの広告イベントをリッスンします。

サンプル全体を表示する

このセクションでは、バナー広告を React Native コンポーネントに統合する完全な例について説明します。

次の例では、バナー広告を React Native コンポーネントに統合し、広告インスタンスを状態管理しています。

export function BannerScreen() {
  const {width} = useWindowDimensions();
  const insets = useSafeAreaInsets();
  const [ad, setAd] = useState<BannerAd | null>(null);
  const [status, setStatus] = useState('Idle');

  useEffect(() => {
    return () => {
      ad?.destroy();
    };
  }, [ad]);

  const handleLoadAd = async () => {
    setStatus('Loading adaptive banner ad...');
    try {
      const adaptiveSize = await getAdaptiveAdSize(width);
      loadBannerAd(BANNER_AD_UNIT_ID, adaptiveSize, {
        onAdLoaded: (loadedAd) => {
          setAd(loadedAd);
          setStatus('Banner ad loaded successfully.');
        },
        onAdFailedToLoad: (error: LoadAdError) => {
          setStatus(`Failed to load banner ad: ${error.message}`);
        },
      });
    } catch (error) {
      setStatus(`Failed to get adaptive ad size: ${error}`);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Anchored Adaptive Banner Ad</Text>
      <Text style={styles.status}>Status: {status}</Text>
      <View style={styles.buttonGroup}>
        <Button title="Load Banner Ad" onPress={handleLoadAd} />
      </View>
      {ad ? (
        <View style={[styles.bannerContainer, {bottom: insets.bottom}]}>
          <BannerAdView
            ad={ad}
            onAdImpression={() => setStatus('Banner ad recorded impression.')}
            onAdClicked={() => setStatus('Banner ad clicked.')}
            onAdShowedFullScreenContent={() =>
              setStatus('Banner ad showed overlay content.')
            }
            onAdDismissedFullScreenContent={() =>
              setStatus('Banner ad overlay dismissed.')
            }
          />
        </View>
      ) : null}
    </View>
  );
}

BANNER_AD_UNIT_ID は、実際の広告ユニット ID に置き換えてください。

次のステップ

バナー広告を統合したら、次のトピックをご覧ください。