You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native集成AdMob初始化后Android应用崩溃问题

React Native AdMob初始化成功后Android崩溃的解决方案

核心问题:违反React Hook规则

你的代码中在useEffect内部调用useForeground Hook,这直接违反了React的Hook使用规则——所有Hook必须在组件的顶层作用域调用,不能嵌套在条件判断、副作用函数或其他函数内部。即使Android平台不会执行这个分支,React的Hook检测机制仍可能触发致命错误导致应用崩溃。

修正后的代码

将useForeground移到组件顶层:

import React, { useRef, useState, useEffect } from 'react';
import { View, Platform } from 'react-native';
import mobileAds, { BannerAd, BannerAdSize, TestIds, useForeground } from 'react-native-google-mobile-ads';

const adUnitId = __DEV__ ? TestIds.BANNER : process.env.BANNER_AD_UNIT_ID || '';

function App() {
    const [loaded, setLoaded] = useState(false);
    const bannerRef = useRef<BannerAd>(null);

    // 仅iOS平台使用useForeground,直接在顶层调用
    if (Platform.OS === 'ios') {
        useForeground(() => {
            bannerRef.current?.load();
        });
    }

    useEffect(() => {
        mobileAds().initialize()
            .then(() => {
                setLoaded(true);
                console.log('AdMob initialized successfully');
            })
            .catch((error) => console.error('AdMob initialization error:', error));
    }, []);

    if (!loaded) return null;
    if (!adUnitId) {
        console.log('Ad Unit ID is not set');
        return null;
    }

    return (
        <View style={{ height: 50 }}>
            <BannerAd
                ref={bannerRef}
                unitId={adUnitId}
                size={BannerAdSize.BANNER}
            />
        </View>
    );
}

export default App;

额外排查步骤

  • 验证AndroidManifest配置
    确认android/app/src/main/AndroidManifest.xml中存在AdMob应用ID的配置:

    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="@string/admob_app_id"/>
    

    同时检查android/app/src/main/res/values/strings.xml中是否有对应的字符串值:

    <string name="admob_app_id">你的Android App ID</string>
    
  • 清理项目缓存
    执行以下命令清理Android项目缓存并重新构建:

    cd android && ./gradlew clean
    cd .. && npx react-native run-android
    
  • 检查依赖兼容性
    确认react-native-google-mobile-ads版本与你的React Native版本兼容,建议使用最新稳定版。

  • 排查Google Play Services冲突
    检查项目中是否存在其他依赖引入了不同版本的Google Play Services,可在android/build.gradle中统一版本:

    ext {
        googlePlayServicesAdsVersion = "22.6.0" // 使用最新兼容版本
    }
    

内容的提问来源于stack exchange,提问作者Mostafa Elkaramany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:12:43