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
+48 -1
View File
@@ -1,4 +1,5 @@
import 'package:flame/game.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -117,7 +118,52 @@ class _MatchScreenState extends State<MatchScreen> {
_toast('Replay läuft');
}
/// Settings sheet: privacy options (UMP requirement) and ad status.
void _openSettings() {
showModalBottomSheet<void>(
context: context,
backgroundColor: const Color(0xFF0B1220),
builder: (sheetContext) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Icons.privacy_tip_outlined),
title: const Text('Datenschutz-Optionen'),
subtitle: Text(_ads.consentLabel),
onTap: () async {
Navigator.pop(sheetContext);
await _ads.showPrivacyOptions();
if (mounted) _toast('Consent: ${_ads.consentLabel}');
},
),
ListTile(
leading: const Icon(Icons.campaign_outlined),
title: const Text('Werbe-Status'),
subtitle: Text(_ads.statusLabel),
),
if (kDebugMode)
ListTile(
leading: const Icon(Icons.restart_alt),
title: const Text('Consent zuruecksetzen (Debug)'),
onTap: () async {
Navigator.pop(sheetContext);
await _ads.resetConsent();
if (mounted) _toast('Consent zurueckgesetzt - App neu starten');
},
),
const SizedBox(height: 8),
],
),
),
);
}
Future<void> _showRewardedAd() async {
if (!_ads.isAdsAllowed) {
_toast('Anzeigen erst nach Zustimmung');
return;
}
final reward = await _ads.showRewarded();
if (!mounted) return;
_toast(reward == null ? 'Keine Anzeige verfügbar' : 'Belohnung: +$reward');
@@ -163,7 +209,8 @@ class _MatchScreenState extends State<MatchScreen> {
const SizedBox(height: 6),
AnimatedBuilder(
animation: _session,
builder: (context, _) => StatusBar(session: _session),
builder: (context, _) =>
StatusBar(session: _session, onSettings: _openSettings),
),
],
),
+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;
+11 -1
View File
@@ -53,9 +53,10 @@ class Hud extends StatelessWidget {
/// Connection state and pending-replay counter.
class StatusBar extends StatelessWidget {
const StatusBar({super.key, required this.session});
const StatusBar({super.key, required this.session, required this.onSettings});
final MatchSession session;
final VoidCallback onSettings;
@override
Widget build(BuildContext context) {
@@ -82,6 +83,15 @@ class StatusBar extends StatelessWidget {
const SizedBox(width: 8),
Text('· ${session.queued} pending',
style: const TextStyle(fontSize: 11, color: Color(0xFFFFC107))),
const SizedBox(width: 4),
InkWell(
onTap: onSettings,
borderRadius: BorderRadius.circular(12),
child: const Padding(
padding: EdgeInsets.all(4),
child: Icon(Icons.tune, size: 16, color: Color(0xFF90A4AE)),
),
),
],
],
);