Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,37 @@ public class FlutterFirebaseMessagingPlugin

FlutterFirebasePermissionManager permissionManager;

@VisibleForTesting
interface NotificationDelegationHandler {
Task<Void> setEnabled(Map<String, Object> arguments, boolean enabled);

boolean isEnabled(Map<String, Object> arguments);
}

private final NotificationDelegationHandler delegationHandler;

public FlutterFirebaseMessagingPlugin() {
this(
new NotificationDelegationHandler() {
@Override
public Task<Void> setEnabled(Map<String, Object> arguments, boolean enabled) {
return FlutterFirebaseMessagingUtils.getFirebaseMessagingForArguments(arguments)
.setNotificationDelegationEnabled(enabled);
}

@Override
public boolean isEnabled(Map<String, Object> 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
Expand Down Expand Up @@ -346,6 +377,42 @@ private Task<Void> setDeliveryMetricsExportToBigQuery(Map<String, Object> argume
return taskCompletionSource.getTask();
}

private Task<Void> setNotificationDelegationEnabled(Map<String, Object> arguments) {
TaskCompletionSource<Void> taskCompletionSource = new TaskCompletionSource<>();

cachedThreadPool.execute(
() -> {
try {
Boolean enabled = (Boolean) Objects.requireNonNull(arguments.get("enabled"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent a potential NullPointerException, perform a null check on arguments before attempting to retrieve the 'enabled' key.

            if (arguments == null) {
              throw new IllegalArgumentException("Arguments cannot be null");
            }
            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<Map<String, Object>> isNotificationDelegationEnabled(Map<String, Object> args) {
TaskCompletionSource<Map<String, Object>> taskCompletionSource = new TaskCompletionSource<>();

cachedThreadPool.execute(
() -> {
try {
Map<String, Object> 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<Map<String, Object>> getInitialMessage() {
TaskCompletionSource<Map<String, Object>> taskCompletionSource = new TaskCompletionSource<>();

Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Object> successValue = new AtomicReference<>();
final AtomicReference<String> errorCode = new AtomicReference<>();
final AtomicReference<String> errorMessage = new AtomicReference<>();
final AtomicReference<Object> 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<Void> setEnabled(Map<String, Object> arguments, boolean enabled) {
lastSetEnabled = enabled;
if (setError != null) {
return Tasks.forException(setError);
}
this.enabled = enabled;
return Tasks.forResult(null);
}

@Override
public boolean isEnabled(Map<String, Object> arguments) {
if (getError != null) {
throw getError;
}
return enabled;
}
}

@Test
public void setNotificationDelegationEnabledUpdatesState() throws Exception {
FakeDelegationHandler handler = new FakeDelegationHandler();
FlutterFirebaseMessagingPlugin plugin = new FlutterFirebaseMessagingPlugin(handler);

Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> enabledMap = (Map<String, Object>) 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<String, Object> disabledMap = (Map<String, Object>) 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<String, Object> 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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low

Avoid using the ! operator to adhere to the repository style guide. Since sdkInt is a mutable instance/closure variable, copying it to a local variable allows Dart's flow analysis to promote it to non-nullable safely.

Suggested change
final expected = sdkInt != null && sdkInt! >= 29;
final currentSdkInt = sdkInt;
final expected = currentSdkInt != null && currentSdkInt >= 29;
References
  1. NO ! operator. Use ? and flow analysis (e.g. if (x != null)). (link)

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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> 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<bool> isNotificationDelegationEnabled() {
return _delegate.isNotificationDelegationEnabled();
}

/// Sets the presentation options for Apple notifications when received in
/// the foreground.
///
Expand Down
Loading