0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】React Native + expo + Google Mobile Ads

Last updated at Posted at 2025-02-12

1年以上前ですが、ReactNativeにadmobを実装したコードを備忘録として残します。
react-native-google-mobile-ads はネイティブコードを必要とするため、npx expo start(Expoの開発サーバー)では動作せず、EAS Build(Expo Application Services)を使ってビルド→実行して動作確認を。

App.tsx
import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, Platform } from 'react-native';
import { InterstitialAd, AdEventType } from 'react-native-google-mobile-ads';
import Toast from 'react-native-toast-message';

// 広告ユニットIDの設定(開発環境か本番環境かで切り替え)
const adUnitId = __DEV__
  ? 'ca-app-pub-???' // 開発用テスト広告 ID
  : Platform.select({
      ios: 'ca-app-pub-???',
      android: 'ca-app-pub-???',
    }) ?? '';

// インタースティシャル広告の作成
const interstitial = InterstitialAd.createForAdRequest(adUnitId, {
  requestNonPersonalizedAdsOnly: true,
  keywords: ['fashion', 'clothing'],
});

export default function App() {
  // 広告の読み込み状態を管理
  const [loaded, setLoaded] = useState(false);

  // 広告の初期化
  useEffect(() => {
    adInit();
  }, []);

  const adInit = () => {
    interstitial.load(); // 広告の読み込み開始

    // 広告の読み込み完了時のイベントリスナー
    const unsubscribeLoaded = interstitial.addAdEventListener(
      AdEventType.LOADED,
      () => {
        setLoaded(true);
      }
    );

    // 広告が閉じられたときのイベントリスナー
    const unsubscribeClosed = interstitial.addAdEventListener(
      AdEventType.CLOSED,
      () => {
        setLoaded(false);
        interstitial.load(); // 次の広告を準備
        
        Toast.show({
          type: 'success',
          text1: '広告が再生されました',
        });
      }
    );

    // 広告の読み込みエラー時のイベントリスナー
    const unsubscribeError = interstitial.addAdEventListener(
      AdEventType.ERROR,
      (error) => {
        console.error('広告の読み込み中にエラーが発生しました:', error);
      }
    );

    // コンポーネントのアンマウント時にリスナーを解除
    return () => {
      unsubscribeLoaded();
      unsubscribeClosed();
      unsubscribeError();
    };
  };

  // 広告を表示する関数
  const showInterstitialAd = () => {
    if (loaded) {
      interstitial.show();
    }
  };

  return (
    <View>
      <TouchableOpacity onPress={showInterstitialAd}>
        <Text>広告を再生する</Text>
      </TouchableOpacity>
    </View>
  );
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?