🚀 快速开始
版本 GroMore

⚡ 快速开始

按照本指南完成 GroMore 插件的初始化、事件监听和首个广告请求。

1. 导入与初始化

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:gromore_ads/gromore_ads.dart';

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  AdEventSubscription? _adEventSubscription;

  @override
  void initState() {
    super.initState();
    _bootstrapAds();
  }

  Future<void> _bootstrapAds() async {
    try {
      // 1) 可选隐私权限
      if (Platform.isIOS) {
        await GromoreAds.requestIDFA;
      } else if (Platform.isAndroid) {
        await GromoreAds.requestPermissionIfNecessary;
      }

      // 2) 注册事件监听器
      _adEventSubscription = GromoreAds.onEvent(
        onEvent: (event) {
          debugPrint('📌 广告事件: ${event.action} (posId: ${event.posId})');
        },
        onError: (event) {
          debugPrint('❌ 广告错误 ${event.code}: ${event.message}');
        },
        onReward: (event) {
          if (event.verified) {
            debugPrint('✅ 奖励验证成功: ${event.rewardType ?? ''} x${event.rewardAmount ?? 0}');
          }
        },
      );

      // 3) 初始化 SDK
      final success = await GromoreAds.initAd(
        'your_app_id',
        useMediation: true,
        debugMode: true,
      );

      if (success) {
        // 4) 可选:预加载常用广告位
        await GromoreAds.preload(
          configs: const [
            PreloadConfig.rewardVideo(['reward_pos_id']),
            PreloadConfig.interstitial(['interstitial_pos_id']),
            PreloadConfig.feed(['feed_pos_id']),
            PreloadConfig.banner(['banner_pos_id']),
          ],
        );
      } else {
        debugPrint('SDK初始化失败,请检查配置');
      }
    } catch (e) {
      debugPrint('广告SDK启动异常: $e');
    }
  }

  @override
  void dispose() {
    _adEventSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: Placeholder());
  }
}

💡 预加载提示: 支持激励视频、插屏、Feed、DrawFeed、Banner等所有广告类型的预加载。详见预加载功能文档。

2. 初始化参数详解

必填参数

参数名类型说明
appIdString穿山甲平台分配的应用ID,在穿山甲开发者平台创建应用后获取
useMediationbool是否启用聚合功能。true=启用广告聚合(推荐),false=仅使用穿山甲广告
debugModebool是否开启调试模式。true=输出详细日志,false=生产环境使用

可选参数

参数名类型默认值平台说明
configObject?null全平台本地配置文件,支持Flutter资源路径、绝对路径、JSON字符串或Map对象。用于聚合初始化加速场景
limitPersonalAdsint?SDK默认全平台是否限制个性化广告。1=限制,0=不限制。GDPR等隐私合规场景使用
limitProgrammaticAdsint?SDK默认全平台是否限制程序化广告。1=限制,0=不限制。隐私合规场景使用
themeStatusint?SDK默认全平台SDK主题模式。0=正常模式,1=夜间模式
ageGroupint?0全平台用户年龄组。0=成人,1=青少年(15-18岁),2=未成年人(<15岁)
supportMultiProcessbool?SDK默认💡 Android是否支持多进程。多进程应用需设置为true仅Android支持此参数

⚠️ 平台差异说明

supportMultiProcess参数仅在Android平台有效,iOS平台会自动忽略此参数。这是因为:

  • Android使用多进程架构,需要显式配置进程间通信
  • iOS采用单进程模型,不需要此配置

跨平台开发建议:可以在所有平台传入此参数,插件会自动处理平台差异。

参数使用示例

// 最简配置(仅必填参数)
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,
);

// 完整配置(包含所有可选参数)
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,
  config: 'assets/gromore_config.json',  // 本地配置文件
  limitPersonalAds: 1,                   // 限制个性化广告
  limitProgrammaticAds: 1,               // 限制程序化广告
  themeStatus: 0,                        // 正常主题
  ageGroup: 0,                          // 成人用户
  supportMultiProcess: true,             // @android 多进程支持
);

// GDPR合规场景
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: false,
  limitPersonalAds: 1,      // 欧盟用户限制个性化
  limitProgrammaticAds: 1,  // 限制程序化广告
);

// 青少年模式
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: false,
  ageGroup: 1,  // 青少年模式,会自动限制部分功能
);

💡 参数传递原则

  • 只传你需要的参数:可选参数如果不传,SDK会使用其内部默认值
  • 避免过度配置:大多数场景只需要传入必填参数即可
  • 禁止猜测默认值:如果不确定某个参数的作用,保持不传让SDK使用默认值

3. 常见问题(FAQ)

初始化失败怎么办?

try {
  final success = await GromoreAds.initAd(
    'your_app_id',
    useMediation: true,
    debugMode: true,
  );

  if (!success) {
    // 初始化失败,检查以下问题:
    // 1. appId是否正确(在穿山甲平台复制完整ID)
    // 2. 网络连接是否正常
    // 3. 是否在测试环境使用了生产appId
    print('SDK初始化失败');
  }
} catch (e) {
  // 捕获异常情况
  print('SDK初始化异常: $e');
}

常见原因

  1. appId错误:确保使用穿山甲平台创建应用后获取的完整ID
  2. 网络问题:SDK初始化需要联网验证,检查网络连接
  3. 重复初始化:不要多次调用initAd,应该在应用启动时只调用一次
  4. 平台配置错误:检查Android/iOS原生配置是否正确添加

如何判断SDK是否初始化成功?

final success = await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,
);

if (success) {
  print('SDK初始化成功,可以加载广告了');
  // 继续预加载广告或展示广告
  await GromoreAds.preload(configs: [...]);
} else {
  print('SDK初始化失败,请检查配置');
}

多次调用initAd会怎样?

插件内部会检测重复初始化:

  • 相同配置:复用现有实例,立即返回成功
  • 不同配置:返回错误,提示配置不兼容

最佳实践:在应用启动时(main()initState())调用一次即可。

如何在调试时查看SDK日志?

await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,  // ✅ 开启调试模式
);

开启debugMode后,会在控制台输出详细的SDK运行日志,包括:

  • SDK初始化状态
  • 广告加载过程
  • 错误详细信息

⚠️ 生产环境必须关闭debugMode,避免日志泄露和性能损耗。

配置文件(config参数)如何使用?

config参数支持多种格式:

// 方式1:Flutter资源路径
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,
  config: 'assets/gromore_config.json',
);

// 方式2:绝对路径
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,
  config: '/data/user/0/com.example.app/files/config.json',
);

// 方式3:JSON字符串
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,
  config: '{"key": "value"}',
);

// 方式4:Map对象
await GromoreAds.initAd(
  'your_app_id',
  useMediation: true,
  debugMode: true,
  config: {'key': 'value'},
);

使用场景

  • 离线配置:预先将聚合配置打包到应用中
  • 动态配置:从服务器下载配置后传入SDK
  • 加速初始化:避免SDK启动时联网获取配置

4. 事件监听器

插件使用订阅模式管理事件监听,支持多个订阅并发,每个订阅独立管理生命周期。

基础用法

class _MyPageState extends State<MyPage> {
  AdEventSubscription? _subscription;

  @override
  void initState() {
    super.initState();

    // 创建事件订阅
    _subscription = GromoreAds.onEvent(
      onEvent: (event) {
        debugPrint('📌 ${event.action} (posId: ${event.posId})');
      },
      onError: (event) {
        debugPrint('❌ 错误 ${event.code}: ${event.message}');
      },
      onReward: (event) {
        if (event.verified) {
          debugPrint('✅ 奖励: ${event.rewardType} x${event.rewardAmount}');
        }
      },
    );
  }

  @override
  void dispose() {
    _subscription?.cancel();  // 取消订阅
    super.dispose();
  }
}

针对特定广告位监听

// 只监听特定 posId 的事件
_subscription = GromoreAds.onAdEvents(
  'reward_video_001',
  onEvent: (event) {
    // 只会收到 reward_video_001 的事件
    debugPrint('事件: ${event.action}');
  },
);

便捷的类型化监听

// 激励视频专用监听
_subscription = GromoreAds.onRewardVideoEvents(
  'reward_video_001',
  onLoaded: (event) => debugPrint('✅ 加载成功'),
  onRewarded: (event) => _grantReward(event.rewardAmount),
  onCompleted: (event) => debugPrint('✅ 播放完成'),
  onError: (event) => debugPrint('❌ 错误: ${event.message}'),
);

详细的事件处理指南请参阅事件处理文档。

5. 常用 API 速览

功能方法说明
初始化initAd只保留你需要的可选参数即可,内部会过滤 null
广告事件onEvent, onAdEvents, onRewardVideoEvents订阅模式,支持多订阅并发,通过 cancel() 取消
开屏广告showSplashAd既可直接展示,也可通过 preload: true 先缓存
插屏广告loadInterstitialAd + showInterstitialAd记得先加载成功再展示
激励视频loadRewardVideoAd + showRewardVideoAd支持服务端验证字段 customDatauserId
信息流/DrawloadFeedAd / loadDrawFeedAd方法返回广告 id 列表,渲染时传给 widget
BannerloadBannerAdAdBannerWidgetWidget 模式最简单,无需额外销毁
预加载preload使用 PreloadConfig.* 描述首轮缓存
测试工具launchTestTools在测试包内启动 GroMore 官方调试工具

6. 最小可运行示例

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await GromoreAds.initAd(
      'app_id',
      useMediation: true,
      debugMode: true,
    );
  } catch (e) {
    debugPrint('SDK初始化失败: $e');
  }

  runApp(
    const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('GroMore ready'),
        ),
      ),
    ),
  );
}

完成以上步骤后,即可按照功能章节继续集成不同广告位。

需要进一步协助?

与 LightCore 技术顾问沟通,获取商业化策略与集成支持。