Flutter广告集成插件flutter_applovin_max的使用

Flutter广告集成插件flutter_applovin_max的使用

插件简介

flutter_applovin_max 是一个用于在 Flutter 应用中展示 AppLovin MAX 广告的插件。MAX 是 AppLovin 的应用内变现解决方案,它通过单一的无偏拍卖机制为广告商提供平等的广告库存访问权,并同时进行竞价,从而提高竞争性和更高的CPM。

开始使用

Android 配置

AndroidManifest.xml 文件中添加以下代码:

<meta-data android:name="applovin.sdk.key"
    android:value="YOUR_SDK_KEY"/>
iOS 配置

Info.plist 文件中添加以下代码:

<key>AppLovinSdkKey</key>
<string>YOUR_SDK_KEY</string>
<key>SKAdNetworkItems</key>
<array>
    <dict>
        <key>SKAdNetworkIdentifier</key>
        <string>2U9PT9HC89.skadnetwork</string>
    </dict>
    <!-- 其他 SKAdNetworkIdentifiers -->
</array>
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>

准备中介网络

请参考官方文档以获取更多信息:

注意:在安装 IronSource 时可能会出现错误提示,可以按照错误信息中的建议进行处理。

使用此插件

下面是一个完整的示例演示如何使用 flutter_applovin_max 插件:

import 'package:flutter/material.dart';
import 'package:flutter_applovin_max/banner.dart';
import 'package:flutter_applovin_max/flutter_applovin_max.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // 初始化广告单元ID
  [@override](/user/override)
  void initState() {
    // 初始化奖励视频广告和插屏广告
    FlutterApplovinMax.initRewardAd('YOUR_AD_UNIT_ID');
    FlutterApplovinMax.initInterstitialAd('YOUR_AD_UNIT_ID');
    
    // 设置用户ID
    FlutterApplovinMax.setUser('TestUserId');
    
    super.initState();
  }

  // 广告事件监听器
  void listener(AppLovinAdListener event) {
    print(event);
    if (event == AppLovinAdListener.onUserRewarded) {
      print('👍get reward'); // 用户获得奖励
    }
  }

  bool isRewardedVideoAvailable = false;
  bool isInterstitialVideoAvailable = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              const Spacer(),
              // 显示奖励视频按钮
              TextButton(
                onPressed: () async {
                  isRewardedVideoAvailable = await FlutterApplovinMax.isRewardLoaded(listener);
                  if (isRewardedVideoAvailable) {
                    FlutterApplovinMax.showRewardVideo((AppLovinAdListener event) => listener(event));
                  }
                },
                child: const Text('Show Reward Video'),
              ),
              // 显示插屏视频按钮
              TextButton(
                onPressed: () async {
                  isInterstitialVideoAvailable = await FlutterApplovinMax.isInterstitialLoaded(listener);
                  if (isInterstitialVideoAvailable) {
                    FlutterApplovinMax.showInterstitialVideo((AppLovinAdListener event) => listener(event));
                  }
                },
                child: const Text('Show Interstitial Video'),
              ),
              const Spacer(),
            ],
          )
        ),
        // 底部导航栏显示横幅广告
        bottomNavigationBar: BannerMaxView((AppLovinAdListener event) => print(event), BannerAdSize.banner, "YOUR_AD_UNIT_ID"),
      ),
    );
  }
}
1 回复

更多关于Flutter广告集成插件flutter_applovin_max的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中集成和使用flutter_applovin_max插件的示例代码。这个插件允许你在Flutter应用中集成Applovin Max广告。

步骤 1: 添加依赖

首先,在你的pubspec.yaml文件中添加flutter_applovin_max依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_applovin_max: ^latest_version  # 请替换为最新的版本号

然后运行flutter pub get来安装依赖。

步骤 2: 配置Android和iOS项目

Android

  1. android/app/src/main/AndroidManifest.xml中添加必要的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  1. android/app/build.gradle文件中添加以下内容以配置AppLovin SDK:
android {
    ...
    defaultConfig {
        ...
        manifestPlaceholders = [
                applovinSdkKey    : "YOUR_APPLOVIN_SDK_KEY",  // 替换为你的AppLovin SDK Key
                applovinAdUnitIds: "[\"YOUR_INTERSTITIAL_AD_UNIT_ID\", \"YOUR_BANNER_AD_UNIT_ID\"]"  // 替换为你的广告单元ID
        ]
    }
}

iOS

  1. ios/Runner/Info.plist中添加必要的配置:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
  1. ios/Podfile中添加以下内容以确保使用正确的AppLovin SDK版本:
platform :ios, '10.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug': :debug,
  'Profile': :release,
  'Release': :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return File.expand_path(matches[1], __FILE__) if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try running flutter pub get in your flutter project."
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
  1. 在Xcode中,打开Runner项目,确保在Info.plist中配置了AppLovinSdkKeyAppLovinAdUnitIds

步骤 3: 初始化并使用插件

在你的Flutter应用中,你可以这样初始化并使用flutter_applovin_max插件:

import 'package:flutter/material.dart';
import 'package:flutter_applovin_max/flutter_applovin_max.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter AppLovin Max Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () {
                  _showInterstitialAd();
                },
                child: Text('Show Interstitial Ad'),
              ),
              SizedBox(height: 20),
              BannerAdWidget(
                adUnitId: 'YOUR_BANNER_AD_UNIT_ID', // 替换为你的Banner广告单元ID
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showInterstitialAd() {
    FlutterApplovinMax.initialize(
      sdkKey: 'YOUR_APPLOVIN_SDK_KEY', // 替换为你的AppLovin SDK Key
      testAdsEnabled: true, // 在开发阶段设置为true,发布时设置为false
    ).then((_) {
      FlutterApplovinMax.loadInterstitialAd(
        adUnitId: 'YOUR_INTERSTITIAL_AD_UNIT_ID', // 替换为你的Interstitial广告单元ID
      ).then((_) {
        FlutterApplovinMax.showInterstitialAd().catchError((error) {
          print('Failed to show interstitial ad: $error');
        });
      }).catchError((error) {
        print('Failed to load interstitial ad: $error');
      });
    }).catchError((error) {
      print('Failed to initialize SDK: $error');
    });
  }
}

class BannerAdWidget extends StatefulWidget {
  final String adUnitId;

  BannerAdWidget({required this.adUnitId});

  @override
  _BannerAdWidgetState createState() => _BannerAdWidgetState();
}

class _BannerAdWidgetState extends State<BannerAdWidget> {
  BannerAd? _bannerAd;

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

  void _loadBannerAd() {
    FlutterApplovinMax.loadBannerAd(
      adUnitId: widget.adUnitId,
      size: AdSize.banner, // 或者其他尺寸如AdSize.largeBanner, AdSize.mediumRectangle等
    ).then((bannerAd) {
      setState(() {
        _bannerAd = bannerAd;
      });
    }).catchError((error) {
      print('Failed to load banner ad: $error');
    });
  }

  @override
  Widget build(BuildContext context) {
    return _bannerAd != null
        ? Container(
            child: AdWidget(ad: _bannerAd!),
            height: AdSize.banner.height, // 根据你选择的尺寸调整高度
          )
        : Container();
  }

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

以上代码展示了如何初始化AppLovin Max SDK,加载并显示Interstitial广告和Banner广告。请确保替换YOUR_APPLOVIN_SDK_KEYYOUR_INTERSTITIAL_AD_UNIT_IDYOUR_BANNER_AD_UNIT_ID为你的实际值。

这个示例应该能帮助你在Flutter项目中集成并使用flutter_applovin_max插件。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!