feat(m7b): ump consent flow with fail-safe ad gating and privacy options

This commit is contained in:
2026-10-25 00:39:41 +02:00
parent 5ab02ec2df
commit ad1360d17f
6 changed files with 216 additions and 18 deletions
+123 -14
View File
@@ -1,14 +1,13 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
/// AdMob integration.
/// AdMob integration with UMP consent.
///
/// The **application id** lives in `AndroidManifest.xml`
/// (`ca-app-pub-3909261635234286~8769927442`).
///
/// Until real ad units exist, Google's official **test units** are used on
/// purpose: showing live ads during development produces invalid traffic and can
/// get the AdMob account suspended.
/// Order matters (Google policy): consent is gathered **before** the Mobile Ads
/// SDK is initialised and before any ad request. Without consent, no ads are
/// requested at all — the UI simply reports "not available".
class AdsService {
/// Official Google test unit for rewarded video.
static const String rewardedUnitId =
@@ -18,6 +17,9 @@ class AdsService {
static const String interstitialUnitId =
'ca-app-pub-3940256099942544/1033173712';
/// Hashed id of the test device (MD5 of the Android ID, upper case).
static const String _testDeviceHashedId = '8FE2A5A74DC63E67AB86EE55E600589C';
/// Never show an interstitial during the first matches (retention).
static const int skipFirstMatches = 3;
@@ -26,23 +28,128 @@ class AdsService {
RewardedAd? _rewarded;
InterstitialAd? _interstitial;
bool _initialized = false;
bool _started = false;
bool _adsAllowed = false;
int _matchesFinished = 0;
bool get isInitialized => _initialized;
bool get isRewardedReady => _rewarded != null;
int get matchesFinished => _matchesFinished;
ConsentStatus _consentStatus = ConsentStatus.unknown;
bool _privacyOptionsRequired = false;
/// Initialises the SDK once and preloads both formats.
bool get isInitialized => _started;
bool get isRewardedReady => _rewarded != null;
bool get isAdsAllowed => _adsAllowed;
int get matchesFinished => _matchesFinished;
bool get privacyOptionsRequired => _privacyOptionsRequired;
String get consentLabel => switch (_consentStatus) {
ConsentStatus.obtained => 'Zustimmung erteilt',
ConsentStatus.required => 'Zustimmung erforderlich',
ConsentStatus.notRequired => 'Nicht erforderlich',
ConsentStatus.unknown => 'Unbekannt',
};
String get statusLabel =>
'Consent: $consentLabel · Ads: ${_adsAllowed ? 'aktiv' : 'inaktiv'}'
' · Rewarded: ${isRewardedReady ? 'geladen' : 'nicht geladen'}';
/// Gathers consent, then initialises the SDK only if ads may be requested.
Future<void> initialize() async {
if (_initialized) return;
if (_started) return;
_started = true;
await _gatherConsent();
_adsAllowed = await ConsentInformation.instance.canRequestAds();
if (!_adsAllowed) {
debugPrint('ads: no consent - SDK stays idle');
return;
}
await MobileAds.instance.initialize();
_initialized = true;
debugPrint('ads: SDK initialised');
_loadRewarded();
_loadInterstitial();
}
Future<void> _gatherConsent() async {
final params = ConsentRequestParameters(
consentDebugSettings: kDebugMode
? ConsentDebugSettings(
debugGeography: DebugGeography.debugGeographyEea,
testIdentifiers: const [_testDeviceHashedId],
)
: null,
);
final done = Completer<void>();
ConsentInformation.instance.requestConsentInfoUpdate(
params,
() async {
try {
if (await ConsentInformation.instance.isConsentFormAvailable()) {
await ConsentForm.loadAndShowConsentFormIfRequired(
(FormError? error) {
if (error != null) {
debugPrint('ads: consent form dismissed with error ${error.message}');
} else {
debugPrint('ads: consent form handled');
}
},
);
} else {
debugPrint('ads: no consent form available');
}
} catch (error) {
debugPrint('ads: consent form error $error');
} finally {
if (!done.isCompleted) done.complete();
}
},
(error) {
debugPrint('ads: consent update failed (${error.errorCode}) ${error.message}');
if (!done.isCompleted) done.complete();
},
);
await done.future;
_consentStatus = await ConsentInformation.instance.getConsentStatus();
_privacyOptionsRequired =
(await ConsentInformation.instance.getPrivacyOptionsRequirementStatus()) ==
PrivacyOptionsRequirementStatus.required;
debugPrint(
'ads: consent=$_consentStatus privacyOptionsRequired=$_privacyOptionsRequired',
);
}
/// Shows the UMP privacy options ("Datenschutz-Optionen") if required.
Future<void> showPrivacyOptions() async {
try {
await ConsentForm.showPrivacyOptionsForm((FormError? error) {
if (error != null) {
debugPrint('ads: privacy options error ${error.message}');
}
});
_consentStatus = await ConsentInformation.instance.getConsentStatus();
_adsAllowed = await ConsentInformation.instance.canRequestAds();
debugPrint('ads: privacy options closed, consent=$_consentStatus');
if (_adsAllowed && _rewarded == null) _loadRewarded();
} catch (error) {
debugPrint('ads: privacy options error $error');
}
}
/// Debug helper: forgets the stored consent and re-runs the flow next start.
Future<void> resetConsent() async {
await ConsentInformation.instance.reset();
_consentStatus = ConsentStatus.unknown;
_adsAllowed = false;
_rewarded?.dispose();
_rewarded = null;
_interstitial?.dispose();
_interstitial = null;
debugPrint('ads: consent reset');
}
void _loadRewarded() {
RewardedAd.load(
adUnitId: rewardedUnitId,
@@ -80,6 +187,7 @@ class AdsService {
/// Shows a rewarded video and returns the granted amount, or null if none was
/// available (the caller must not grant a reward in that case).
Future<int?> showRewarded() async {
if (!_adsAllowed) return null;
final ad = _rewarded;
if (ad == null) {
_loadRewarded();
@@ -107,6 +215,7 @@ class AdsService {
/// Called when a match ends; applies the frequency caps from the GDD.
void onMatchFinished() {
if (!_adsAllowed) return;
_matchesFinished++;
if (_matchesFinished <= skipFirstMatches) return;
if (_matchesFinished % everyNthMatch != 0) return;