From 0d7670c14e823b354d68ec7e4eac1d25d885475f Mon Sep 17 00:00:00 2001 From: ReoAndo Date: Sat, 28 Nov 2026 01:17:06 +0900 Subject: [PATCH] feat(messaging, android): expose Android notification delegation APIs Add setNotificationDelegationEnabled(bool enabled) and isNotificationDelegationEnabled() across firebase_messaging, firebase_messaging_platform_interface, firebase_messaging_web, and the Android plugin to wrap the Firebase Messaging Android SDK notification delegation APIs. On Android 10 (API 29) and higher, apps can query and toggle Google Play services notification delegation at runtime. On Android devices below API 29 and on non-Android platforms (iOS, macOS, web), setNotificationDelegationEnabled completes as a no-op and isNotificationDelegationEnabled returns false. Co-Authored-By: Antigravity (Gemini 4 Neon) --- .../FlutterFirebaseMessagingPlugin.java | 73 ++++++ .../FlutterFirebaseMessagingUtils.java | 1 + ...seMessagingNotificationDelegationTest.java | 220 ++++++++++++++++++ .../example/integration_test/e2e_test.dart | 26 +++ .../firebase_messaging/lib/src/messaging.dart | 21 ++ .../test/firebase_messaging_test.dart | 32 +++ .../firebase_messaging/test/mock.dart | 18 ++ .../method_channel_messaging.dart | 35 +++ .../platform_interface_messaging.dart | 25 ++ .../method_channel_messaging_test.dart | 165 +++++++++++++ .../platform_interface_messaging_test.dart | 26 +++ .../lib/firebase_messaging_web.dart | 11 + .../test/firebase_messaging_web_test.dart | 14 ++ 13 files changed, 667 insertions(+) create mode 100644 packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingNotificationDelegationTest.java diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java index 12021ee2ed6c..a98ca16faf77 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java @@ -89,6 +89,37 @@ public class FlutterFirebaseMessagingPlugin FlutterFirebasePermissionManager permissionManager; + @VisibleForTesting + interface NotificationDelegationHandler { + Task setEnabled(Map arguments, boolean enabled); + + boolean isEnabled(Map arguments); + } + + private final NotificationDelegationHandler delegationHandler; + + public FlutterFirebaseMessagingPlugin() { + this( + new NotificationDelegationHandler() { + @Override + public Task setEnabled(Map arguments, boolean enabled) { + return FlutterFirebaseMessagingUtils.getFirebaseMessagingForArguments(arguments) + .setNotificationDelegationEnabled(enabled); + } + + @Override + public boolean isEnabled(Map arguments) { + return FlutterFirebaseMessagingUtils.getFirebaseMessagingForArguments(arguments) + .isNotificationDelegationEnabled(); + } + }); + } + + @VisibleForTesting + FlutterFirebaseMessagingPlugin(NotificationDelegationHandler delegationHandler) { + this.delegationHandler = delegationHandler; + } + // Sends a message to Dart. Messages sent before Dart has set up its handler on the channel wait // in a buffer that only keeps one by default, so it is enlarged with every message rather than // once at registration: engines created with `new FlutterEngine(...)` register plugins before @@ -346,6 +377,42 @@ private Task setDeliveryMetricsExportToBigQuery(Map argume return taskCompletionSource.getTask(); } + private Task setNotificationDelegationEnabled(Map arguments) { + TaskCompletionSource taskCompletionSource = new TaskCompletionSource<>(); + + cachedThreadPool.execute( + () -> { + try { + Boolean enabled = (Boolean) Objects.requireNonNull(arguments.get("enabled")); + Tasks.await(delegationHandler.setEnabled(arguments, enabled)); + taskCompletionSource.setResult(null); + } catch (Exception e) { + taskCompletionSource.setException(e); + } + }); + + return taskCompletionSource.getTask(); + } + + private Task> isNotificationDelegationEnabled(Map args) { + TaskCompletionSource> taskCompletionSource = new TaskCompletionSource<>(); + + cachedThreadPool.execute( + () -> { + try { + Map result = new HashMap<>(); + result.put( + FlutterFirebaseMessagingUtils.IS_NOTIFICATION_DELEGATION_ENABLED, + delegationHandler.isEnabled(args)); + taskCompletionSource.setResult(result); + } catch (Exception e) { + taskCompletionSource.setException(e); + } + }); + + return taskCompletionSource.getTask(); + } + private Task> getInitialMessage() { TaskCompletionSource> taskCompletionSource = new TaskCompletionSource<>(); @@ -636,6 +703,12 @@ public void onMethodCall(final MethodCall call, @NonNull final Result result) { case "Messaging#setDeliveryMetricsExportToBigQuery": methodCallTask = setDeliveryMetricsExportToBigQuery(call.arguments()); break; + case "Messaging#setNotificationDelegationEnabled": + methodCallTask = setNotificationDelegationEnabled(call.arguments()); + break; + case "Messaging#isNotificationDelegationEnabled": + methodCallTask = isNotificationDelegationEnabled(call.arguments()); + break; case "Messaging#requestPermission": if (Build.VERSION.SDK_INT >= 33) { // Android version >= Android 13 requires user input if notification permission not diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingUtils.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingUtils.java index f424c76e574c..378399be0cbf 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingUtils.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingUtils.java @@ -23,6 +23,7 @@ interface ErrorCallback { class FlutterFirebaseMessagingUtils { static final String IS_AUTO_INIT_ENABLED = "isAutoInitEnabled"; + static final String IS_NOTIFICATION_DELEGATION_ENABLED = "isNotificationDelegationEnabled"; static final String SHARED_PREFERENCES_KEY = "io.flutter.firebase.messaging.callback"; static final String EXTRA_REMOTE_MESSAGE = "notification"; static final int JOB_ID = 2020; diff --git a/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingNotificationDelegationTest.java b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingNotificationDelegationTest.java new file mode 100644 index 000000000000..5c9f63e06a28 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingNotificationDelegationTest.java @@ -0,0 +1,220 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +package io.flutter.plugins.firebase.messaging; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import android.os.Looper; +import androidx.annotation.Nullable; +import com.google.android.gms.tasks.Task; +import com.google.android.gms.tasks.Tasks; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.Shadows; +import org.robolectric.annotation.Config; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 28) +public class FlutterFirebaseMessagingNotificationDelegationTest { + + private static final class RecordingResult implements MethodChannel.Result { + final AtomicBoolean completed = new AtomicBoolean(false); + final AtomicBoolean succeeded = new AtomicBoolean(false); + final AtomicReference successValue = new AtomicReference<>(); + final AtomicReference errorCode = new AtomicReference<>(); + final AtomicReference errorMessage = new AtomicReference<>(); + final AtomicReference errorDetails = new AtomicReference<>(); + + @Override + public void success(@Nullable Object result) { + successValue.set(result); + succeeded.set(true); + completed.set(true); + } + + @Override + public void error(String code, @Nullable String message, @Nullable Object details) { + errorCode.set(code); + errorMessage.set(message); + errorDetails.set(details); + completed.set(true); + } + + @Override + public void notImplemented() { + completed.set(true); + } + + void await() throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!completed.get() && System.nanoTime() < deadline) { + Shadows.shadowOf(Looper.getMainLooper()).idle(); + Thread.sleep(10); + } + Shadows.shadowOf(Looper.getMainLooper()).idle(); + assertTrue("Timed out waiting for MethodChannel.Result", completed.get()); + } + } + + private static final class FakeDelegationHandler + implements FlutterFirebaseMessagingPlugin.NotificationDelegationHandler { + boolean enabled; + Boolean lastSetEnabled; + RuntimeException setError; + RuntimeException getError; + + @Override + public Task setEnabled(Map arguments, boolean enabled) { + lastSetEnabled = enabled; + if (setError != null) { + return Tasks.forException(setError); + } + this.enabled = enabled; + return Tasks.forResult(null); + } + + @Override + public boolean isEnabled(Map arguments) { + if (getError != null) { + throw getError; + } + return enabled; + } + } + + @Test + public void setNotificationDelegationEnabledUpdatesState() throws Exception { + FakeDelegationHandler handler = new FakeDelegationHandler(); + FlutterFirebaseMessagingPlugin plugin = new FlutterFirebaseMessagingPlugin(handler); + + Map enableArgs = new HashMap<>(); + enableArgs.put("appName", "[DEFAULT]"); + enableArgs.put("enabled", true); + MethodCall enableCall = + new MethodCall("Messaging#setNotificationDelegationEnabled", enableArgs); + RecordingResult enableResult = new RecordingResult(); + + plugin.onMethodCall(enableCall, enableResult); + enableResult.await(); + + assertTrue(enableResult.succeeded.get()); + assertNull(enableResult.successValue.get()); + assertEquals(Boolean.TRUE, handler.lastSetEnabled); + + Map disableArgs = new HashMap<>(); + disableArgs.put("appName", "[DEFAULT]"); + disableArgs.put("enabled", false); + MethodCall disableCall = + new MethodCall("Messaging#setNotificationDelegationEnabled", disableArgs); + RecordingResult disableResult = new RecordingResult(); + + plugin.onMethodCall(disableCall, disableResult); + disableResult.await(); + + assertTrue(disableResult.succeeded.get()); + assertNull(disableResult.successValue.get()); + assertEquals(Boolean.FALSE, handler.lastSetEnabled); + } + + @Test + public void setNotificationDelegationEnabledErrorsWhenArgumentMissing() throws Exception { + FakeDelegationHandler handler = new FakeDelegationHandler(); + FlutterFirebaseMessagingPlugin plugin = new FlutterFirebaseMessagingPlugin(handler); + + Map args = new HashMap<>(); + args.put("appName", "[DEFAULT]"); + MethodCall call = new MethodCall("Messaging#setNotificationDelegationEnabled", args); + RecordingResult result = new RecordingResult(); + + plugin.onMethodCall(call, result); + result.await(); + + assertFalse(result.succeeded.get()); + assertEquals("firebase_messaging", result.errorCode.get()); + assertNotNull(result.errorDetails.get()); + } + + @Test + public void setNotificationDelegationEnabledPropagatesTaskFailure() throws Exception { + FakeDelegationHandler handler = new FakeDelegationHandler(); + handler.setError = new IllegalStateException("delegation failed"); + FlutterFirebaseMessagingPlugin plugin = new FlutterFirebaseMessagingPlugin(handler); + + Map args = new HashMap<>(); + args.put("appName", "[DEFAULT]"); + args.put("enabled", true); + MethodCall call = new MethodCall("Messaging#setNotificationDelegationEnabled", args); + RecordingResult result = new RecordingResult(); + + plugin.onMethodCall(call, result); + result.await(); + + assertFalse(result.succeeded.get()); + assertEquals("firebase_messaging", result.errorCode.get()); + assertTrue(result.errorMessage.get().contains("delegation failed")); + } + + @Test + public void isNotificationDelegationEnabledReturnsCurrentState() throws Exception { + String key = FlutterFirebaseMessagingUtils.IS_NOTIFICATION_DELEGATION_ENABLED; + FakeDelegationHandler handler = new FakeDelegationHandler(); + handler.enabled = true; + FlutterFirebaseMessagingPlugin plugin = new FlutterFirebaseMessagingPlugin(handler); + + Map args = new HashMap<>(); + args.put("appName", "[DEFAULT]"); + MethodCall call = new MethodCall("Messaging#isNotificationDelegationEnabled", args); + + RecordingResult enabledResult = new RecordingResult(); + plugin.onMethodCall(call, enabledResult); + enabledResult.await(); + + assertTrue(enabledResult.succeeded.get()); + @SuppressWarnings("unchecked") + Map enabledMap = (Map) enabledResult.successValue.get(); + assertEquals(Boolean.TRUE, enabledMap.get(key)); + + handler.enabled = false; + RecordingResult disabledResult = new RecordingResult(); + plugin.onMethodCall(call, disabledResult); + disabledResult.await(); + + assertTrue(disabledResult.succeeded.get()); + @SuppressWarnings("unchecked") + Map disabledMap = (Map) disabledResult.successValue.get(); + assertEquals(Boolean.FALSE, disabledMap.get(key)); + } + + @Test + public void isNotificationDelegationEnabledPropagatesException() throws Exception { + FakeDelegationHandler handler = new FakeDelegationHandler(); + handler.getError = new IllegalStateException("status failed"); + FlutterFirebaseMessagingPlugin plugin = new FlutterFirebaseMessagingPlugin(handler); + + Map args = new HashMap<>(); + args.put("appName", "[DEFAULT]"); + MethodCall call = new MethodCall("Messaging#isNotificationDelegationEnabled", args); + RecordingResult result = new RecordingResult(); + + plugin.onMethodCall(call, result); + result.await(); + + assertFalse(result.succeeded.get()); + assertEquals("firebase_messaging", result.errorCode.get()); + assertEquals("status failed", result.errorMessage.get()); + } +} diff --git a/packages/firebase_messaging/firebase_messaging/example/integration_test/e2e_test.dart b/packages/firebase_messaging/firebase_messaging/example/integration_test/e2e_test.dart index b64ce8ad0a77..68fd156b26b6 100644 --- a/packages/firebase_messaging/firebase_messaging/example/integration_test/e2e_test.dart +++ b/packages/firebase_messaging/firebase_messaging/example/integration_test/e2e_test.dart @@ -391,6 +391,32 @@ void main() { ); }); + group('notification delegation', () { + test( + 'can disable and enable notification delegation on Android', + () async { + final originalValue = await messaging + .isNotificationDelegationEnabled(); + try { + await messaging.setNotificationDelegationEnabled(false); + expect(await messaging.isNotificationDelegationEnabled(), isFalse); + + await messaging.setNotificationDelegationEnabled(true); + final expected = sdkInt != null && sdkInt! >= 29; + expect(await messaging.isNotificationDelegationEnabled(), expected); + } finally { + await messaging.setNotificationDelegationEnabled(originalValue); + } + }, + skip: kIsWeb || defaultTargetPlatform != TargetPlatform.android, + ); + + test('returns false and is a no-op on non-Android platforms', () async { + await messaging.setNotificationDelegationEnabled(true); + expect(await messaging.isNotificationDelegationEnabled(), isFalse); + }, skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.android); + }); + test('a background message with no registered handler does not start ' 'the background service', () async { final probe = await probeBackgroundDelivery( diff --git a/packages/firebase_messaging/firebase_messaging/lib/src/messaging.dart b/packages/firebase_messaging/firebase_messaging/lib/src/messaging.dart index 3f145f34dca8..fd16914bbe3c 100644 --- a/packages/firebase_messaging/firebase_messaging/lib/src/messaging.dart +++ b/packages/firebase_messaging/firebase_messaging/lib/src/messaging.dart @@ -335,6 +335,27 @@ class FirebaseMessaging extends FirebasePlugin { return _delegate.setDeliveryMetricsExportToBigQuery(enabled); } + /// Enables or disables notification delegation for Android. + /// + /// When enabled on Android 10 (API level 29) and higher, Google Play services + /// can display FCM notification messages on the app's behalf. Disabling + /// delegation ensures incoming messages are delivered directly to the app's + /// messaging service. + /// + /// On Android devices below API level 29, and on non-Android platforms, this + /// method completes as a no-op. + Future setNotificationDelegationEnabled(bool enabled) { + return _delegate.setNotificationDelegationEnabled(enabled); + } + + /// Returns whether notification delegation is currently enabled on Android. + /// + /// Returns `false` on Android devices below API level 29 and on non-Android + /// platforms. + Future isNotificationDelegationEnabled() { + return _delegate.isNotificationDelegationEnabled(); + } + /// Sets the presentation options for Apple notifications when received in /// the foreground. /// diff --git a/packages/firebase_messaging/firebase_messaging/test/firebase_messaging_test.dart b/packages/firebase_messaging/firebase_messaging/test/firebase_messaging_test.dart index c86c8e00873d..b539db885a44 100644 --- a/packages/firebase_messaging/firebase_messaging/test/firebase_messaging_test.dart +++ b/packages/firebase_messaging/firebase_messaging/test/firebase_messaging_test.dart @@ -352,6 +352,38 @@ void main() { verify(kMockMessagingPlatform.setAutoInitEnabled(true)); }); }); + + group('setNotificationDelegationEnabled', () { + test('verify delegate method is called with correct args', () async { + when( + kMockMessagingPlatform.setNotificationDelegationEnabled(any), + ).thenAnswer((_) => Future.value()); + + await messaging!.setNotificationDelegationEnabled(false); + verify(kMockMessagingPlatform.setNotificationDelegationEnabled(false)); + + await messaging!.setNotificationDelegationEnabled(true); + verify(kMockMessagingPlatform.setNotificationDelegationEnabled(true)); + }); + }); + + group('isNotificationDelegationEnabled', () { + test('verify delegate method is called', () async { + when( + kMockMessagingPlatform.isNotificationDelegationEnabled(), + ).thenAnswer((_) => Future.value(true)); + + expect(await messaging!.isNotificationDelegationEnabled(), isTrue); + verify(kMockMessagingPlatform.isNotificationDelegationEnabled()); + + when( + kMockMessagingPlatform.isNotificationDelegationEnabled(), + ).thenAnswer((_) => Future.value(false)); + + expect(await messaging!.isNotificationDelegationEnabled(), isFalse); + verify(kMockMessagingPlatform.isNotificationDelegationEnabled()); + }); + }); group('subscribeToTopic', () { // setUp(() { // when(kMockMessagingPlatform.subscribeToTopic('')) diff --git a/packages/firebase_messaging/firebase_messaging/test/mock.dart b/packages/firebase_messaging/firebase_messaging/test/mock.dart index 4696b61777cd..7f2ed7acb9ed 100644 --- a/packages/firebase_messaging/firebase_messaging/test/mock.dart +++ b/packages/firebase_messaging/firebase_messaging/test/mock.dart @@ -168,6 +168,24 @@ class MockFirebaseMessaging extends Mock ); } + @override + Future setNotificationDelegationEnabled(bool? enabled) { + return super.noSuchMethod( + Invocation.method(#setNotificationDelegationEnabled, [enabled]), + returnValue: Future.value(), + returnValueForMissingStub: Future.value(), + ); + } + + @override + Future isNotificationDelegationEnabled() { + return super.noSuchMethod( + Invocation.method(#isNotificationDelegationEnabled, []), + returnValue: Future.value(false), + returnValueForMissingStub: Future.value(false), + ); + } + @override Stream get onTokenRefresh { return super.noSuchMethod( diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart index 80c60c8ba62e..c4a04bfb575b 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart @@ -544,4 +544,39 @@ class MethodChannelFirebaseMessaging extends FirebaseMessagingPlatform { convertPlatformException(e, stack); } } + + @override + Future setNotificationDelegationEnabled(bool enabled) async { + // Notification delegation is only available on Android. + if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) { + return; + } + try { + await channel.invokeMapMethod( + 'Messaging#setNotificationDelegationEnabled', + {'appName': app.name, 'enabled': enabled}, + ); + } catch (e, stack) { + convertPlatformException(e, stack); + } + } + + @override + Future isNotificationDelegationEnabled() async { + // Notification delegation is only available on Android. + if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) { + return false; + } + try { + Map? data = await channel + .invokeMapMethod( + 'Messaging#isNotificationDelegationEnabled', + {'appName': app.name}, + ); + + return data!['isNotificationDelegationEnabled'] as bool; + } catch (e, stack) { + convertPlatformException(e, stack); + } + } } diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart index b27a4016dbaf..cdad6cee5850 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart @@ -368,4 +368,29 @@ abstract class FirebaseMessagingPlatform extends PlatformInterface { 'setDeliveryMetricsExportToBigQuery() is not implemented', ); } + + /// Enables or disables notification delegation for Android. + /// + /// When enabled on Android 10 (API level 29) and higher, Google Play services + /// can display FCM notification messages on the app's behalf. Disabling + /// delegation ensures incoming messages are delivered directly to the app's + /// messaging service. + /// + /// On Android devices below API level 29, and on non-Android platforms, this + /// method completes as a no-op. + Future setNotificationDelegationEnabled(bool enabled) { + throw UnimplementedError( + 'setNotificationDelegationEnabled() is not implemented', + ); + } + + /// Returns whether notification delegation is currently enabled on Android. + /// + /// Returns `false` on Android devices below API level 29 and on non-Android + /// platforms. + Future isNotificationDelegationEnabled() { + throw UnimplementedError( + 'isNotificationDelegationEnabled() is not implemented', + ); + } } diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart index fb57c95cf5d2..093e837a39c6 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart @@ -473,6 +473,171 @@ void main() { ), ]); }); + + group('setNotificationDelegationEnabled', () { + test('sets to true on Android', () async { + await messaging.setNotificationDelegationEnabled(true); + + expect(log, [ + isMethodCall( + 'Messaging#setNotificationDelegationEnabled', + arguments: { + 'appName': defaultFirebaseAppName, + 'enabled': true, + }, + ), + ]); + }); + + test('sets to false on Android', () async { + await messaging.setNotificationDelegationEnabled(false); + + expect(log, [ + isMethodCall( + 'Messaging#setNotificationDelegationEnabled', + arguments: { + 'appName': defaultFirebaseAppName, + 'enabled': false, + }, + ), + ]); + }); + + test('is a no-op on non-Android platforms', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + await messaging.setNotificationDelegationEnabled(false); + + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + await messaging.setNotificationDelegationEnabled(true); + + expect(log, isEmpty); + }); + + test('converts PlatformException to FirebaseException', () async { + handleMethodCall((call) async { + log.add(call); + throw PlatformException( + code: 'unknown', + message: 'Delegation update failed', + details: { + 'code': 'unknown', + 'message': 'Delegation update failed', + }, + ); + }); + addTearDown(() { + handleMethodCall((call) async { + log.add(call); + return {}; + }); + }); + + await expectLater( + () => messaging.setNotificationDelegationEnabled(false), + throwsA( + isA() + .having((e) => e.plugin, 'plugin', 'firebase_messaging') + .having((e) => e.code, 'code', 'unknown'), + ), + ); + }); + }); + + group('isNotificationDelegationEnabled', () { + test('returns true on Android when enabled', () async { + handleMethodCall((call) async { + log.add(call); + if (call.method == 'Messaging#isNotificationDelegationEnabled') { + return {'isNotificationDelegationEnabled': true}; + } + return {}; + }); + addTearDown(() { + handleMethodCall((call) async { + log.add(call); + return {}; + }); + }); + + final enabled = await messaging.isNotificationDelegationEnabled(); + + expect(enabled, isTrue); + expect(log, [ + isMethodCall( + 'Messaging#isNotificationDelegationEnabled', + arguments: {'appName': defaultFirebaseAppName}, + ), + ]); + }); + + test('returns false on Android when disabled', () async { + handleMethodCall((call) async { + log.add(call); + if (call.method == 'Messaging#isNotificationDelegationEnabled') { + return {'isNotificationDelegationEnabled': false}; + } + return {}; + }); + addTearDown(() { + handleMethodCall((call) async { + log.add(call); + return {}; + }); + }); + + final enabled = await messaging.isNotificationDelegationEnabled(); + + expect(enabled, isFalse); + expect(log, [ + isMethodCall( + 'Messaging#isNotificationDelegationEnabled', + arguments: {'appName': defaultFirebaseAppName}, + ), + ]); + }); + + test( + 'returns false without calling native on non-Android platforms', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + expect(await messaging.isNotificationDelegationEnabled(), isFalse); + + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + expect(await messaging.isNotificationDelegationEnabled(), isFalse); + + expect(log, isEmpty); + }, + ); + + test('converts PlatformException to FirebaseException', () async { + handleMethodCall((call) async { + log.add(call); + throw PlatformException( + code: 'unknown', + message: 'Delegation query failed', + details: { + 'code': 'unknown', + 'message': 'Delegation query failed', + }, + ); + }); + addTearDown(() { + handleMethodCall((call) async { + log.add(call); + return {}; + }); + }); + + await expectLater( + () => messaging.isNotificationDelegationEnabled(), + throwsA( + isA() + .having((e) => e.plugin, 'plugin', 'firebase_messaging') + .having((e) => e.code, 'code', 'unknown'), + ), + ); + }); + }); }); } diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart index 3c2cd43d6640..68ffad0bd9b9 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart @@ -239,6 +239,32 @@ void main() { } fail('Should have thrown an [UnimplementedError]'); }); + + test('throws if setNotificationDelegationEnabled()', () async { + try { + await firebaseMessagingPlatform.setNotificationDelegationEnabled(true); + } on UnimplementedError catch (e) { + expect( + e.message, + equals('setNotificationDelegationEnabled() is not implemented'), + ); + return; + } + fail('Should have thrown an [UnimplementedError]'); + }); + + test('throws if isNotificationDelegationEnabled()', () async { + try { + await firebaseMessagingPlatform.isNotificationDelegationEnabled(); + } on UnimplementedError catch (e) { + expect( + e.message, + equals('isNotificationDelegationEnabled() is not implemented'), + ); + return; + } + fail('Should have thrown an [UnimplementedError]'); + }); }); } diff --git a/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart b/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart index cc8ec31773d6..28ea3e8f2a03 100644 --- a/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart +++ b/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart @@ -217,6 +217,17 @@ class FirebaseMessagingWeb extends FirebaseMessagingPlatform { return; } + @override + Future setNotificationDelegationEnabled(bool enabled) async { + // Noop out on web - notification delegation is Android only. + return; + } + + @override + Future isNotificationDelegationEnabled() async { + return false; + } + @override Future setForegroundNotificationPresentationOptions({ required bool alert, diff --git a/packages/firebase_messaging/firebase_messaging_web/test/firebase_messaging_web_test.dart b/packages/firebase_messaging/firebase_messaging_web/test/firebase_messaging_web_test.dart index cda4ee180904..6fd48feba973 100644 --- a/packages/firebase_messaging/firebase_messaging_web/test/firebase_messaging_web_test.dart +++ b/packages/firebase_messaging/firebase_messaging_web/test/firebase_messaging_web_test.dart @@ -5,6 +5,7 @@ @TestOn('chrome') import 'package:firebase_messaging_platform_interface/firebase_messaging_platform_interface.dart'; +import 'package:firebase_messaging_web/firebase_messaging_web.dart'; import 'package:firebase_messaging_web/src/utils.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -70,4 +71,17 @@ void main() { ); }); }); + + group('$FirebaseMessagingWeb', () { + test('setNotificationDelegationEnabled() completes as a no-op', () async { + final webMessaging = FirebaseMessagingWeb(); + await webMessaging.setNotificationDelegationEnabled(true); + await webMessaging.setNotificationDelegationEnabled(false); + }); + + test('isNotificationDelegationEnabled() returns false', () async { + final webMessaging = FirebaseMessagingWeb(); + expect(await webMessaging.isNotificationDelegationEnabled(), isFalse); + }); + }); }